Mobile Business To Business (B2B)

Mobile Business To Business (B2B) APIs allow you to initiate payments TO businesses eg banks FROM your payment wallet.

Jump to:


How does it work? [Go Top]

In order to facilitate Mobile B2B transactions, we have implemented a RESTFul JSON API that allows your application to request B2B Payments to a business via their provider channel eg. their paybill number. The request is queued for processing and a notification sent when transaction is completed.

Once the payment provider confirms or rejects the payment request, our APIs will generate a payment notification and send it to the callback URL configured in your account. You can learn more about how to handle payment notifications in this section. Please note that a notification will be generated regardless of whether the transaction was successful or not.


How do I initiate a B2B request? [Go Top]

You can initiate a mobile B2B request by sending a HTTP POST request to: https://payments.africastalking.com/mobile/b2b/request.

The following headers will be required for all requests

a
Header Name Type Description Presence
apikey String This is your Africa's Talking API Key Compulsory
Content-Type String application/json Compulsory

The body of the request should be a JSON object containing the following fields:

Variable Name Type Description Presence
username String This is your Africa's Talking username Compulsory
productName String This value identifies the Africa's Talking Payment Product that should be used to initiate this transaction. Compulsory
provider String This contains the payment provider that is facilitating this transaction. Supported providers at the moment are:
  • Mpesa: This identifies payments facilitated by Safaricom's M-PESA's APIs
  • Athena: This identifies payments facilitated by our Developer Sandbox. This is obviously not available on our production systems
Compulsory
transferType String This contains the payment provider that is facilitating this transaction. Supported providers at the moment are:
  • BusinessBuyGoods
  • BusinessPayBill
  • DisburseFundsToBusiness
  • BusinessToBusinessTransfer
Compulsory
currencyCode String This is the 3-digit ISO format currency code for the value of this transaction (e.g KES, USD, UGX etc) Compulsory
amount Decimal This is the amount (in the provided currency) that the mobile subscriber is expected to receive. Compulsory
destinationChannel String This value contains the name or number of the channel that will receive payment by the provider. This could, for example, be the Mobile Provider's Paybill or Buy Goods number that belongs to your organization. Compulsory
destinationAccount String This value contains the account name used by the business to receive money on the provided destinationChannel. Compulsory

What does a B2B request look like? [Go Top]

Below is a sample B2B request that you can send to our APIs:
(to main account https://payments.africastalking.com/mobile/b2b/request)
(to sandbox https://payments.sandbox.africastalking.com/mobile/b2b/request)
					
{"username":"myUsername",
 "productName":"My Online Store",
 "provider":"PaymentProvider",
 "transferType":"BusinessBuyGoods",
 "currencyCode":"KES",
 "amount":100,
 "destinationChannel":"supplierProviderChannel",
 "destinationAccount":"supplierAccount",
 "metadata" : {
	  "shopId" : "1234",
	  "itemId" : "abcdef"
   }
}				    

How does the API respond to a B2B request? [Go Top]

The API responds to a B2B request with a JSON response containing the fields shown below.

Variable Name Type Description Presence
status String This is the status of the B2C transaction. Possible values are:
  • Queued: The transaction has been accepted and queued for processing by the payment provider. The result of this processing will be sent through the notification callback URL
  • InvalidRequest: This means that we could not accept the request because one of the fields was invalid. The errorMessage field will contain more information
  • NotSupported: This means that B2C requests to the provided phone number is not supported.
  • Failed: This means that the B2C request has failed for some other reason. The errorMessage field will have more details on the reason.
Compulsory
transactionId String This is a unique id that our API generates for a successful request. This is the transactionId that will be sent along with the final payment notification.
Not returned if entry had an error
Optional
transactionFee String This string contains the transaction fee charged by Africa's Talking for this transaction. The format of this string is: [3-digit currencyCode][space][Decimal Value]. An example would be: KES 1.50 or UGX 35.00. This value is only present in the case where a transaction was successful. Note that the transaction fee will be deducted from your Africa's Talking credits (not your payment wallet).
Not returned if entry had an error
Optional
providerChannel String This contains the provider channel which facilitated the payment.
Not returned if entry had an error
Optional
errorMessage String This string contains a more descriptive error message for this transaction, if it was not successfully queued for processing by the API.
Only returned if entry had an error
Optional

What does the API response look like? [Go Top]

Below is a sample JSON response for a successful B2B Request

{
"status": "Queued",
"transactionId": "ATPid_SampleTxnId123",
"transactionFee": "KES XXX",
"providerChannel": "myPaymentProviderChannel"
}				    


Sample code [Go Top]

Our gateway classes contain simple helper functions which make integrating B2C Requests into your applications a total breeze.


You need your AfricasTalking username and APIKey for any request to our API. If you don't have an APIKey, please click here to get one.
For sandbox APIKey, click here

Make B2B Payment Using Our APIs in PHP

The PHP code snippet below shows how to make Mobile B2B Payments using our API.

The code uses our PHP gateway class: AfricasTalkingGateway.php [ Download]

Also, please ensure that you have the php_curl module enabled. To enable it uncomment the line: ;extension=php_curl.dll in php.ini and restart apache

<?php
// Be sure to include the file you've just downloaded
require_once('AfricasTalkingGateway.php');

// Specify your login credentials
$username   = "MyAfricasTalkingUsername";
$apikey     = "MyAfricasTalkingAPIKey";

// Specify your product name
$productName = "myPaymentProductName";

// Specify the payment provider. eg. MPESA, ATHENA (AfricasTalking Sandbox), etc
$provider = "myPaymentProvider";

// Specify partner's business channel
$destinationChannel = "partnerBusinessChannel";

// Specify the transfer purpose
$transferType = "BusinessToBusinessTransfer";

$providerData = array('provider' => $provider,
                      'destinationChannel' => $destinationChannel,
                      'transferType' => $transferType);

// The 3-Letter ISO currency code for the checkout amount
$currencyCode = "KES";
$amount = 100;

// Specify the metadata options. These data will be sent to you in a notification when payment has been made
$metadata = array('shopId' => "1234",
                  'itemId' => "abcde");


// Create a new instance of our awesome gateway class
$gateway    = new AfricasTalkingGateway($username, $apikey);

/*************************************************************************************
 NOTE: If connecting to the sandbox:

 1. Use "sandbox" as the username
 2. Use the apiKey generated from your sandbox application
	https://account.africastalking.com/apps/sandbox/settings/key
 3. Add the "sandbox" flag to the constructor

 $gateway  = new AfricasTalkingGateway($username, $apiKey, "sandbox");
**************************************************************************************/

// Any gateway errors will be captured by our custom Exception class below, 
// so wrap the call in a try-catch block
try 
{ 
  // Thats it, hit send and we'll take care of the rest. 
  $results = $gateway->mobilePaymentB2BRequest($productName, $providerData, $currencyCode, $amount, $metadata);
  if($results->status == "Queued") {
    echo "TransactionId: " . $results->transactionId;
    echo "\nTransactionFee: " . $results->transactionFee;
    echo "\nProviderChannel: " . $results->providerChannel;
  }
  else {
    echo "ErrorMessage: " . $results->errorMessage;
  }
}
catch ( AfricasTalkingGatewayException $e )
{
  echo "Encountered an error while sending: ".$e->getMessage();
}
?>
    

Make B2B Payment Using Our APIs in Java

The Java code snippet below shows how to make Mobile B2B Payments using our API.

The code uses our Java gateway class: AfricasTalkingGateway.java [ Download]

To help decode JSON responses, you will need to add one of the available JAVA libraries as a dependency. For this tutorial we chose to use json-20090211.jar which you can download from this repository.

Note On SSL Certificate Validation Issues

Some of our users have experienced SSL Certificate validation issues when connecting to our website due to our use of https. The error you see may look something like this:

Unable to find valid certification path to requested target

Please do not panic! Our certificate is perfectly valid (as evidenced by these verification tests), and the error you are seeing is quite common amongst Java clients connecting to secure websites. Here is how to fix the issue:

  • Download and compile InstallCert.java (you can find the code here).
  • On the CMD prompt(Windows) or Terminal(*nix), run: java InstallCert api.africastalking.com
    This will download a copy of our Certificate and create a file named jssecacerts in the current directory.
  • You can now add our Certificate to your trusted store by copying the created jssecacerts file to the Java security directory under $JAVA_HOME/jre/lib/security
// Make sure the downloaded jar file is in the classpath
import org.json.*;
import java.util.HashMap;

public class TestMobilePaymentB2B
{
    public static void main(String[] args_)
    {
		// Specify your login credentials
		String username = "MyUsername";
		String apiKey   = "MyAPIKey";

		// Specify your product name
		String productName = "myPaymentProductName";
		
		// Specify the payment provider. eg. MPESA, ATHENA (AfricasTalking Sandbox), etc
		String provider = "myPaymentProvider";
		
		// Specify partner's business channel
		String destinationChannel = "partnerBusinessChannel";
		
		// Specify the transfer purpose
		String transferType = "BusinessToBusinessTransfer";
		
		HashMap<String, String> providerData = new HashMap<String, String>();
		providerData.put("provider", provider);
		providerData.put("destinationChannel", destinationChannel);
		providerData.put("transferType", transferType);
		
		// Specify 3-Letter ISO currency code and amount
		String currencyCode = "KES";
		float amount = 100;
		
		// Specify the metadata options. These data will be sent to you in a notification when payment has been made.
		//You can add as many parameters as you want
		
		HashMap<String, String> metadata = new HashMap<String, String>();
		metadata.put("shopId", "1234");
		metadata.put("itemId", "abcde");
	
	    // Create a new instance of our awesome gateway class
	    AfricasTalkingGateway gateway  = new AfricasTalkingGateway(username, apiKey);

		/*************************************************************************************
			NOTE: If connecting to the sandbox:

			1. Use "sandbox" as the username
			2. Use the apiKey generated from your sandbox application
				https://account.africastalking.com/apps/sandbox/settings/key
			3. Add the "sandbox" flag to the constructor

			AfricasTalkingGateway gateway = new AfricasTalkingGateway(username, apiKey, "sandbox");
		**************************************************************************************/

	    // Thats it, hit send and we'll take care of the rest. Any errors will
	    // be captured in the Exception class below
	    try {
	        JSONObject results = gateway.mobilePaymentB2BRequest(productName, providerData,
            currencyCode, amount, metadata);
	        
	        System.out.println("Status: " + results.getString("status"));
	        
	        if(results.getString("status").equals("Queued")) {	        
	        	System.out.println("TransactionId: " + results.getString("transactionId"));      
	        	System.out.println("TransactionFee: " + results.getString("transactionFee"));	        
	        	System.out.println("ProviderChannel: " + results.getString("providerChannel"));	        
	        } else {
	        	System.out.println("ErrorMessage: " + results.getString("errorMessage"));	        
	        }
		} catch (Exception e) {
			System.out.println("Encountered an error while sending " + e.getMessage());
		}
	}
}

Make B2B Payment Using Our APIs in Python

The Python code snippet below shows how to make Mobile B2C Payments using our API.

The code uses our Python gateway class: AfricasTalkingGateway.py [ Download]

# Import the helper gateway class
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

#Specify your credentials
username = "MyAfricasTalkingUsername"
apiKey   = "MyAfricasTalkingApiKey"

#Create an instance of our awesome gateway class and pass your credentials
gateway = AfricasTalkingGateway(username, apiKey)

#*************************************************************************************
#  NOTE: If connecting to the sandbox:
#
#  1. Use "sandbox" as the username
#  2. Use the apiKey generated from your sandbox application
#     https://account.africastalking.com/apps/sandbox/settings/key
#  3. Add the "sandbox" flag to the constructor
#
#  gateway = AfricasTalkingGateway(username, apiKey, "sandbox");
#**************************************************************************************

# Specify the name of your Africa's Talking payment product
productName  = "My Online Store"

# The 3-Letter ISO currency code for the checkout amount
currencyCode = "KES"

# Specify the amount to transfer
amount = 100

# Specify the payment provider. eg. MPESA, ATHENA (AfricasTalking Sandbox), etc
provider = "myPaymentProvider"

# Specify partner's business channel
destinationChannel = "partnerBusinessChannel"

# Specify partner's business channel account if needed. This is optional
destinationAccount = "partnerBusinessChannelAccount"

# Specify the transfer purpose
transferType = "BusinessToBusinessTransfer"

# Group providerData in a dict. This is done for convenience
providerData = {
				'provider' : provider,
				'destinationChannel' : destinationChannel,
				'destinationAccount' : destinationAccount,
				'transferType' : transferType
				}
				
# Specify the metadata options. These data will be sent to you in a notification when payment has been made
metadata = {'shopId' : "1234",
            'itemId' : "abcde"}
            
try:
    response = gateway.mobilePaymentB2BRequest(productName, providerData, currencyCode, amount, metadata)
    
    print 'Encountered an error while sending: %s' % response['status']
    
    if (response['status'] == "Queued"):
    	print 'transactionId=%s;transactionFee=%s;providerChannel=%s;' % (response['transactionId'],
    	                                                        recipient['transactionFee'],
    	                                                        recipient['providerChannel'])
    	                                                    
    else:
    	print 'errorMessage: %s' % response['errorMessage']
	    
except AfricasTalkingGatewayException, e:
    print 'Encountered an error while sending: %s' % str(e)
    

Make B2C Payment Using Our APIs

The Ruby code snippet below shows how to make Mobile B2C Payments using our API.

The code uses our Ruby and Rails gateway class: AfricasTalkingGateway.rb [ Download]

# Include the helper gateway class
require './AfricasTalkingGateway'

# Specify your login credentials
username = "myAfricasTalkingUsername";
apikey   = "myAfricasTalkingAPIKey";

# Specify the name of your Africa's Talking payment product
#productName  = "My Online Store"

# The 3-Letter ISO currency code for the checkout amount
currencyCode = "KES"

# Specify the amount to transfer
amount = 100

# Specify the payment provider. eg. MPESA, ATHENA (AfricasTalking Sandbox), etc
#provider = "myPaymentProvider"

# Specify partner's business channel
#destinationChannel = "partnerBusinessChannel"

# Specify partner's business channel account if needed. This is optional
#destinationAccount = "partnerBusinessChannelAccount"

# Specify the transfer purpose
transferType = "BusinessToBusinessTransfer"

# Group providerData in a hash. This is done for convenience
providerData = {
                'provider' => provider,
                'destinationChannel' => destinationChannel,
                'destinationAccount' => destinationAccount,
                'transferType' => transferType
               }
				
# Specify the metadata options. These data will be sent to you in a notification when payment has been made
metadata = {
            'shopId' => "1234",
            'itemId' => "abcde"
           }

# Create a new instance of our awesome gateway class
gateway = AfricasTalkingGateway.new(username, apikey)

#*************************************************************************************
#  NOTE: If connecting to the sandbox:
#
#  1. Use "sandbox" as the username
#  2. Use the apiKey generated from your sandbox application
#     https://account.africastalking.com/apps/sandbox/settings/key
#  3. Add the "sandbox" flag to the constructor
#
#  gateway = AfricasTalkingGateway(username, apiKey, "sandbox");
#**************************************************************************************

# Any gateway errors will be captured by our custom Exception class below,
# so wrap the call in a try-catch block
begin
	response = gateway.mobilePaymentB2BRequest(productName, providerData, currencyCode, amount, metadata)
	if (response['status'] == 'Queued')
		puts "TransactionId: " + transaction['status']
		puts "Provider: " + transaction['provider']
		puts "ProviderChannel: " + transaction['providerChannel']
		puts "Value: " + transaction['value']
		puts "TransactionFee: " + transaction['transactionFee']
	else
		puts transaction['errorMessage']
	end
rescue Exception => ex
	puts "Encountered an error: " + ex.message
end

# DONE!