Mobile Business To Consumer (B2C)

Below is an illustration on how the mobile B2C service works

MOBILE BUSINESS TO CONSUMER

Mobile Business To Consumer (B2C) APIs allow you to send payments to mobile subscribers from your Payment Wallet. Initiate a mobile B2C request by making a HTTP POST request to one of the following endpoint:

Endpoints

Live: https://payments.africastalking.com/mobile/b2c/request
Sandbox: https://payments.sandbox.africastalking.com/mobile/b2c/request

Notifications

Once the mobile payment provider confirms or rejects the payment, our APIs will generate a payment notification and send it to the callback URL configured in your account for the product used to initiate this transaction. You can learn more about how to handle payment notifications in this section.

Request Parameters

In addition to the standard request header, the body of the request should be a JSON object containing the following fields:

Parameter Description
username
String
Required
Africa's Talking application username
productName
String
Required
Africa's Talking Payment Product to initiate this transaction.
recipients
List
Required
A list of Recipient elements each corresponding to a B2C transaction request. Please note: You can currently pass a maximum of 10 recipient elements.

Recipient is a Map of a mobile subscribers account that will receive the B2C transaction.
  • name: String Optional Name of the B2C transaction recipient.
  • phoneNumber: String Required Phone number of the B2C transaction recipient
  • currencyCode: String Required 3-digit ISO format currency code for the value of this transaction (e.g KES, UGX, USD, ...)
  • amount: Decimal Required Amount - in the provided currency - that the client is expected to confirm.
  • providerChannel: String Optional The channel the payment will be made from e.g a paybill number. The payment channel must be mapped to your Africa's Talking payment product. If not specified, a default provider channel will be used. List of default payment provider channels
  • reason: String Optional Purpose of the payment. If set, it should contain one of:
    • SalaryPayment
    • SalaryPaymentWithWithdrawalChargePaid
    • BusinessPayment
    • BusinessPaymentWithWithdrawalChargePaid
    • PromotionPayment
  • metadata: Map<String, String> A map of any metadata that you would like us to associate with the request. Use this field to send data that will map notifications to B2C requests. It will be included in the notification we send once the B2C request is complete.

API Response

The body of the response will be a JSON object containing the following fields:

Parameter Description
numQueued
Int
The number of entries that have been accepted and queued for processing by the payment provider.
totalValue
String
The total amount of money transacted.
totalTransactionFee
String
The transaction fee charged by Africa's Talking for this entire transaction.
entries
List
A list of b2c entries. Each entry will have the following fields:
  • phoneNumber String RequiredThe phone number of the recipeint.
  • status String RequiredThe status of the B2C transaction. Possible values are:
    • Queued The transaction has been accepted and queued for processing by the payment provider.
    • InvalidRequest We could not accept the request because one of the fields was invalid. The errorMessage field will contain a detailed description of the requests status.
    • NotSupported B2C requests to the provided phone number is not supported.
    • Failed The B2C request failed for some other reason. The errorMessage field will contain a detailed description of the requests status.
  • provider String RequiredThe provider that facilitated the payment.
  • providerChannel String OptionalThe provider channel which facilitated the payment.
  • value String RequiredThe amount of money transacted in a specific entry.
  • transactionId String Optional: A unique id that our API generates for successful requests. This transactionId will be sent along with the payment notification.
  • transactionFee: String OptionalThe transaction fee charged by Africa's Talking for this transaction. Please note: The transaction fee will be deducted from your Africa's Talking credits NOT your payment wallet. The format of this string is: (3-digit Currency Code)(space)(Decimal Value) e.g KES 1.50
  • errorMessageString OptionalA more descriptive error message for the status of this transaction.

Below is a sample response for a successful request:

{
    "numQueued": 1,
    "totalValue": "KES 100000",
    "totalTransactionFee": "KES 2.00",
    "entries": [{
        "phoneNumber": "+254711XXXYYY",
        "status": "Queued",
        "provider": "Mpesa",
        "providerChannel": "525900",
        "value": "KES 100000",
        "transactionId": "ATPid_SampleTxnId123",
        "transactionFee": "KES 1.00"
    }, {
        "phoneNumber": "+254722XXXYYY",
        "provider": "Mpesa",
        "status": "Failed",
        "errorMessage": "Insufficient Credit",
        "value": "KES 100000"
    }]
}

Initiate mobile B2C Payment Sample code

The PHP code snippet below shows how to initiate a mobile b2c request.

The code uses our PHP SDK.

<?php
require 'vendor/autoload.php';
use AfricasTalking\SDK\AfricasTalking;

// Set your app credentials
$username   = "MyAppsUsername";
$apikey     = "MyAppAPIKey";

// Initialize the SDK
$AT         = new AfricasTalking($username, $apiKey);

// Get the payments service
$payments   = $AT->payments();

// Set the name of your Africa's Talking payment product
$productName  = "My Online Store";

// Set your mobile b2c recipients
$recipients = [[
    "phoneNumber"  => "+254711XXXYYY",
    "currencyCode" => "KES",
    "amount"       => 100.50,
    "reason"       => $payments::REASON["SALARY"],
    "metadata"     => [
        "name"     => "John Doe"
    ]
], [
    "phoneNumber"  => "+254733YYYZZZ",
    "currencyCode" => "KES",
    "amount"       => 80.50,
    "reason"       => $payments::REASON["BUSINESS"],
    "metadata"     => [
        "name"     => "Jane Doe"
    ]
]];

try {
    // That's it, hit send and we'll take care of the rest
    $results = $payments->mobileB2C([
        "productName" => $productName,
        "recipients"  => $recipients
    ]);

    print_r($results);
} catch(Exception $e) {
    echo "Error: ".$e->getMessage();
}

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

The code uses our Java SDK.

/* Import SDK classes */
import com.africastalking.Callback;
import com.africastalking.AfricasTalking;
import com.africastalking.PaymentService;
import com.africastalking.payment.recipient.Consumer;
import com.africastalking.payment.response.B2CResponse;

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;

public class TestMobileB2C
{
    public static void main(String[] args)
    {
		/* Set your app credentials */
		String USERNAME = "sandbox";
		String API_KEY = "";

		/* Initialize SDK */
		AfricasTalking.initialize(USERNAME, API_KEY);

		/* Get the payments service */
		PaymentService payment = AfricasTalking.getService(AfricasTalking.SERVICE_PAYMENT);

        /* Set the name of your Africa's Talking payment product */
        String productName = "SampleProduct";

		/* Set your mobile b2c recipients */
		List<Consumer> recipients = new ArrayList<Consumer>();
        Consumer consumer = new Consumer(
			"Bob Mwangi",
			"+25471xxxxxx",
			"KES",
			781,
			Consumer.REASON_BUSINESS
		);
        recipients.add(consumer);

		/* That's it, hit send and we'll take care of the rest */
		try {
			
			B2CResponse response = payment.mobileB2C(productName, recipients);
			System.out.println(response.toString());

		} catch(Exception ex) {
			ex.printStackTrace();
		}
   	}
}

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 SDK.

# works with both python 2 and 3
from __future__ import print_function

import africastalking

class MOBILE:
    def __init__(self):
		# Set your app credentials
        self.username = "YOUR_USERNAME"
        self.api_key = "YOUR_API_KEY"
		# Initialize the SDK
        africastalking.initialize(self.username, self.api_key)
		# Get the payments service
        self.payment = africastalking.Payment

    def b2c(self):
        # Set the name of your Africa's Talking payment product
        productName = "ABC"
		# Set your mobile b2c recipients
        consumers = [
            {
                "name": "Bob Mwangi",
                "phoneNumber": "+254718769882",
                "currencyCode": "KES",
                "amount": 6766.88,
                "providerChannel": "1212",
                "reason": 'SalaryPayment',
                "metadata": {}
            }
        ]

        try:
			# That's it, hit send and we'll take care of the rest
            res = self.payment.mobile_b2c(productName, consumers)
            print (res)
        except Exception as e:
            print ("Received error response:%s" %str(e))

if __name__ == '__main__':
    MOBILE().b2c()

The Ruby code snippet below shows how to initiate a checkout validation request using our API

The code uses our Ruby SDK.

require 'AfricasTalking'

# Set your app credentials
username = "MyAppUsername"
apikey   = "MyAppAPIKey"

# Initialize the SDK
AT=AfricasTalking::Initialize.new username, apikey

# Get the payments service
payments = AT.payments

# Set the name of your Africa's Talking payment product
productName = "AT-productName"

# Set your mobile b2c recipients
recipients = Array.new
recipients[0]   = {
      "phoneNumber"  => "+254722222222",
      "currencyCode" => "KES",
      "amount"       => 50000.50,
      "metadata"     => {
                          "name"   => "Jane",
                          "reason" => "May Salary"
                        }
}
recipients[1]   = {
      "phoneNumber"  => "254722333322",
      "currencyCode" => "KES",
      "amount"       => 100000.00,
      "metadata"     => {
                          "name"   => "Clerk",
                          "reason" => "May Salary"
                        }
}
options = {
    'productName' => productName,
    'recipients' => recipients
}
begin
  # That's it, hit send and we'll take care of the rest
  transactions = payments.mobileB2C options
  puts transactions.to_yaml
rescue Exception => ex
  puts "Encountered an error: " + ex.message
end

# DONE!

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

The code uses our Node SDK.

// Set your app credentials
const credentials = {
    apiKey: 'MyAppAPIkey',
    username: 'MyAppUsername'
}

// Initialize the SDK
const AfricasTalking = require('africastalking')(credentials);

// Get the payments service
const payments = AfricasTalking.PAYMENTS;

function initiateMobileB2C() {

    // Set the name of your Africa's Talking payment product
    const productName = "myPaymentProductName";

    // Set your mobile b2c recipients
    const recipients = [
        {
            phoneNumber: "+254711XXXYYY",
            currencyCode: "KES",
            amount: "Amount to be sent to customer",
            metadata: { "foor": "bar", "key": "value" },
            reason: "paymentsReason"
        },
        // ... more recipients
    ];

    // That's it, hit send and we'll take care of the rest
    payments.mobileB2C({ productName, recipients })
        .then(response => {
            console.log(response);
        }).catch(error => {
            console.log(error);
        });
}

initiateMobileB2C();