Mobile Business To Consumer (B2C)

Mobile Business To Consumer (B2C) APIs allow you to initiate payments TO mobile subscribers FROM your payment wallet.

Jump to:


How does it work? [Go Top]

In order to facilitate Mobile B2C transactions, we have implemented a RESTFul JSON API that allows your application to request B2C Payments to a mobile subscriber's phone number. The amount specified will then be directly credited to the mobile subscriber's account. Our API allows you to initiate multiple B2C transactions in one request, all of which will be queued in our gateways for processing.

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 B2C request? [Go Top]

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

The following headers will be required for all requests

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
recipients List of Recipient Elements This contains a list of Recipient elements, each of which corresponds to a B2C Transaction request. The format for each of these recipients is described in the table below.
The below table shows content of each recipient
Compulsory

NB: You can currently pass a maximum of 10 recipients.
The recipient elements specifying the parameters for each B2C transaction will contain the following fields:

Variable Name Type Description Presence
name String This is the name of the B2C transaction recipient Compulsory
phoneNumber String This is the phone number of the B2C transaction recipient 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
providerChannel String This represents the payment channel the payment will be made from. eg paybill number. The payment channel must be mapped to you.
The AfricasTalking default provider channel is used if not specified.
Optional
reason String This field contains a string showing the purpose for the payment. If set, it should contain
  • SalaryPayment
  • ,
  • SalaryPaymentWithWithdrawalChargePaid
  • ,
  • BusinessPayment
  • ,
  • BusinessPaymentWithWithdrawalChargePaid
  • ,
  • PromotionPayment
    Optional
    metadata String Map This value contains a map of any metadata that you would like us to associate with this request. You can use this field to send data that will map notifications to checkout requests, since we will include it when we send notifications once the transaction is complete. Optional

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

    Below is a sample B2C request that you can send to our APIs:
    (to main account https://payments.africastalking.com/mobile/b2c/request)
    (to sandbox https://payments.sandbox.africastalking.com/mobile/b2c/request)
    					
    {
      "username": "MyUsername"
      "productName": "My Online Store",
      "recipients": [
       {
    	 "name": "Joe Sampler",
         "phoneNumber": "+254711XXXYYY",
         "currencyCode": "KES",
         "amount": 5000.10,
         "reason": "SalaryPayment",
         "metadata" : {
           "description" : "May Salary",
           "employeeId" : "123"
         }
       },
       {
    	 "name": "Alice Tester",
         "phoneNumber": "+254733YYYZZZ",
         "currencyCode": "KES",
         "amount": 10000.10,
         "reason": "SalaryPayment",
         "metadata" : {
           "description" : "May Salary",
           "employeeId" : "124"
         }
       }
    }				    

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

    r

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

    Variable Name Type Description Presence
    numQueued Int This shows the number of B2C transactions that were successfully queued as a result of this request. Compulsory
    totalValue String This shows the total value of all the transactions that were successfully queued as a result of this request. The format of this string is: [3-digit currencyCode][space][Decimal Value]. An example would be: KES 100.50 or UGX 3500.00.
    It's not returned if an error was encountered
    Optional
    totalTransactionFee String This shows the total transaction fee charged for all the transactions that were successfully queued as a result of this request. The format of this string is: [3-digit currencyCode][space][Decimal Value]. An example would be: KES 100.50 or UGX 3500.00.
    It's not returned if an error was encountered
    Optional
    errorMessage String This shows an optional error message if the ENTIRE request was rejected by the API. An example reason could be having too many requests, or having duplicate numbers in the request.
    It's only returned if an error was encountered
    Optional
    entries List of Response Entries This contains a list of Response entries, each of which corresponds to a recipient that came in with the B2C Transaction request. The format for each of these entries is described in the table below. Compulsory

    The Response Entries specifying the results for each B2C transaction will contain the following fields:

    Variable Name Type Description Presence
    phoneNumber String This is the phone number of the B2C transaction recipient Compulsory
    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
    provider String This value contains the provider that will be used to process the B2C Request. This will only be sent back for Queued transactions. Possible values are:
    • Mpesa: For Safaricom numbers
    • Athena: For ALL numbers when using the Sandbox environment

    Not returned if entry had an error
    Optional
    providerChannel String This value contains the code of the channel that will be used to process the B2C request for this phone number. The value will typically be the channel mapped to the product used for this request. An example is a PayBill or BuyGoods number mapped to your account.
    Not returned if entry had an error
    Optional
    value String This string contains the value to be sent to the mobile subscriber. The format of this string is: [3-digit currencyCode][space][Decimal Value]. An example would be: KES 100.50 or UGX 3500.00.
    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
    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 B2C Request that has one successful and one unsuccessful transaction
    
    {
      "numQueued": 1,
      "totalValue": "KES 100",
      "totalTransactionFee" : "KES 1.50",
      "entries": [
         {
           "phoneNumber": "+254711XXXYYY",
           "status": "Queued",
           "provider": "Mpesa",
           "providerChannel": "525900",
           "value": "KES 100",
           "transactionId": "ATPid_SampleTxnId123",
           "transactionFee", "KES 1.50"
         },
         {
           "phoneNumber": "+254733YYYZZZ",
           "status": "Failed",
           "errorMessage", "Insufficient Credit"
         }
      ]
    }				    


    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 B2C Payment Using Our APIs in PHP

    The PHP code snippet below shows how to make Mobile B2C 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
    require_once "AfricasTalkingGateway.php";
    
    //Specify your credentials
    $username = "MyAfricasTalkingUsername";
    $apiKey   = "MyAfricasTalkingApiKey";
    
    //Create an instance of our awesome gateway class and pass your credentials
    $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");
    **************************************************************************************/
    
    // 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";
    
    // Provide the details of a mobile money recipient
    $recipient1   = array("phoneNumber" => "+254711XXXYYY",
                           "currencyCode" => "KES",
    					   "amount"       => 10.50,
    					   "metadata"     => array("name"   => "Clerk",
    					                           "reason" => "May Salary")
    		      );
    // You can provide up to 10 recipients at a time
    $recipient2   = array("phoneNumber"  => "+254711YYYXXX",
                        "currencyCode" => "KES",
    					"amount"       => 50.10,
    					"metadata"     => array("name"   => "Accountant",
    					                        "reason" => "May Salary")
    		      );
    // Put the recipients into an array
    $recipients  = array($recipient1, $recipient2);
    
    try {
      $responses = $gateway->mobilePaymentB2CRequest($productName, $recipients);
      
      foreach($responses as $response) {
        // Parse the responses and print them out
        echo "phoneNumber=".$response->phoneNumber;
        echo ";status=".$response->status;
    	
        if ($response->status == "Queued") {
          echo ";transactionId=".$response->transactionId;
          echo ";provider=".$response->provider;
          echo ";providerChannel=".$response->providerChannel;
          echo ";value=".$response->value;
          echo ";transactionFee=".$response->transactionFee."\n";
        } else {
          echo ";errorMessage=".$response->errorMessage."\n";
        }
      }
      
    }
    catch(AfricasTalkingGatewayException $e){
      echo "Received error response: ".$e->getMessage();
    }
    ?>
    
        

    Make B2C Payment Using Our APIs in Java

    The Java code snippet below shows how to make Mobile B2C 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.*;
    
    // Make sure the downloaded jar file is in the classpath
    public class TestMobilePaymentB2C
    {
        public static void main(String[] args_)
        {
            //Specify your credentials
            String username = "MyAfricasTalkingUsername";
            String apiKey   = "MyAfricasTalkingApiKey";
    
            //Create an instance of our awesome gateway class and pass your credentials
            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");
            **************************************************************************************/
    
            // Specify the name of your Africa's Talking payment product
            String productName  = "My Online Store";
    
            // The 3-Letter ISO currency code for the checkout amount
            String currencyCode = "KES";
    
            // Provide the details of a mobile money recipient
            MobilePaymentB2CRecipient recipient1 = new MobilePaymentB2CRecipient("+254718XXXYYY",
                                                 "KES",
                                                 10.50);
            recipient1.addMetadata("name", "Clerk");
            recipient1.addMetadata("reason", "May Salary");
            
            // You can provide up to 10 recipients at a time
            MobilePaymentB2CRecipient recipient2 = new MobilePaymentB2CRecipient("+254718YYYXXX",
                                                 "KES",
                                                 50.10);
            recipient2.addMetadata("name", "Accountant");
            recipient2.addMetadata("reason", "May Salary");
    
            // Put the recipients into an array
            List<MobilePaymentB2CRecipient> recipients  = new ArrayList<MobilePaymentB2CRecipient>();
            recipients.add(recipient1);
            recipients.add(recipient2);
            try {
                JSONArray responses = gateway.mobilePaymentB2CRequest(productName, recipients);
                for( int i = 0; i < responses.length(); ++i ) {
                    // Parse the responses and print them out
                    JSONObject response = responses.getJSONObject(i);
                    System.out.print("phoneNumber=" + response.getString("phoneNumber"));
                    String status = response.getString("status");
                    System.out.print(";status=" + response.getString("status"));
                    if ( status.equals("Queued") ) {
                        System.out.print(";transactionId=" + response.getString("transactionId"));
                        System.out.print(";provider=" + response.getString("provider"));
                        System.out.print(";providerChannel=" + response.getString("providerChannel"));
                        System.out.print(";value=" + response.getString("value"));
                        System.out.println(";transactionFee=" + response.getString("transactionFee"));
                    } else {
                        System.out.println(";errorMessage=" + response.getString("errorMessage"));
                    }
                }
            }
            catch(Exception ex){
                System.out.println("Received error response: " + ex.getMessage());
            }
        }
    }
    

    Make B2C 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, "sandbox")
    
    #*************************************************************************************
    #  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"
    
    # Provide the details of a mobile money recipient
    recipient1   = {"phoneNumber"  : "+254711XXXYYY",
    		        "currencyCode" : "KES",
    		        "amount"       : 10.50,
    		        "metadata"     : {"name"   : "Clerk",
    				                  "reason" : "May Salary"}}
    # You can provide up to 10 recipients at a time
    recipient2   = {"phoneNumber"  : "+254711YYYXXX",
    		        "currencyCode" : "KES",
    		        "amount"       : 50.10,
    		        "metadata"     : {"name"   : "Accountant",
    				                  "reason" : "May Salary"}}
    # Put the recipients into an array
    recipients  = [recipient1, recipient2]
    
    try:
        responses = gateway.mobilePaymentB2CRequest(productName, recipients)
        for response in responses:
    	# Parse the responses and print them out
    	print "phoneNumber=%s;status=%s;" % (response['phoneNumber'],
    					                     response['status'])
    										 
    	if response['status'] == 'Queued':
    	    print "transactionId=%s;provider=%s;providerChannel=%s;" % (response['transactionId'],
    									response['provider'],
    									response['providerChannel'])
    	    print "value=%s;transactionFee=%s;" % (response['value'],
    						   response['transactionFee'])
    	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"
    
    productName = "AT"
    # Provide the details of a mobile money recipient
    recipient1   = {
          "phoneNumber"  => "+254711XXXYYY",
          "currencyCode" => "KES",
          "amount"       => 10.50,
          "metadata"     => {"name"   => "Clerk",
                             "reason" => "May Salary"
                            }
      }
    # You can provide up to 10 recipients at a time
    recipient2   = {
          "phoneNumber"  => "+254733YYYZZZ",
          "currencyCode" => "KES",
          "amount"       => 10.50,
          "metadata"     => {"name"   => "Clerk",
                             "reason" => "May Salary"
                            }
      }
    # Put the recipients into a list
    recipients  = [recipient1, recipient2]
    
    # 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
    	transactions = gateway.mobilePaymentB2CRequest(productName, recipients)
    	transactions.each{ |transaction|
    		if (transaction['status'] == 'Queued')
    			puts "TransactionId: " + transaction['transactionId']
    			puts "PhoneNumber: " + transaction['phoneNumber']
    			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!