Mobile Checkout

Mobile Checkout APIs allow you to initiate Customer to Business (C2B) payments on a mobile subscriber's device. This allows for a smoother checkout experience, since the client will no longer need to remember the amount or an account number to complete the transaction.

Jump to:


How does it work? [Go Top]

In order to facilitate Mobile Checkout, we have implemented a RESTFul JSON API that allows your application to initiate a checkout request on a subscriber's phone number. The mobile subscriber will then be prompted to complete the payment on their phone, typically by interacting with a USSD prompt. it is generally a good idea to ensure that the user has their handset with them in order to increase the chances of completing a transaction.

Once the user confirms or rejects the payment, 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 a user completed the transaction or not.


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

You can initiate a mobile checkout request by sending a HTTP POST request to: https://payments.africastalking.com/mobile/checkout/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

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
phoneNumber String This contains the phone number (in international format) of the mobile subscriber that will complete this transaction. 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 confirm. Compulsory
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 checkout is complete. Optional

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

Below is a sample checkout request that you can send to our APIs (to https://api.africastalking.com/payment/mobile/checkout/request

{
  "username": "MyUsername"
  "productName": "My Online Store",
  "phoneNumber": "+254711XYYZZZ",
  "currencyCode": "KES",
  "amount": 500.5,
  "metadata" : {
	  "shopId" : "1234",
	  "itemId" : "abcdef"
   }
}					   

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

r

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

Variable Name Type Description Presence
status String This corresponds to the status of this request. Possible values are:
  • PendingConfirmation: This means that the request has been accepted and we are waiting for the subscriber to confirm the payment
  • InvalidRequest: This means that we could not accept the request because one of the fields was invalid. The description field will contain more information
  • NotSupported: Thie means that checkout to the provided phone number is not supported.
  • Failed: Thie means that the checkout request has failed for some other reason. The description field will have more details on the reason.
Compulsory
description String This provides a detailed description of the request status 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. Optional

What does a sample response look like? [Go Top]

Below is a sample JSON response for a successful checkout request

{
  "status": "PendingConfirmation",
  "description": "Waiting for user input",
  "transactionId": "ATPid_SampleTxnId123"
}					   


Sample code [Go Top]

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

Initiate Mobile Checkout using PHP

The PHP code snippet below shows how to initiate a checkout request 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";

// NOTE: If connecting to the sandbox, please use your sandbox login credentials

//Create an instance of our awesome gateway class and pass your credentials
$gateway = new AfricasTalkingGateway($username, $apiKey);

// NOTE: If connecting to the sandbox, please add the sandbox flag to the constructor:
/*************************************************************************************
             ****SANDBOX****
$gateway    = new AfricasTalkingGateway($username, $apiKey, "sandbox");
**************************************************************************************/

// Specify the name of your Africa's Talking payment product
$productName  = "My Online Store";
// The phone number of the customer checking out
$phoneNumber  = "+254711XXXYYY";
// The 3-Letter ISO currency code for the checkout amount
$currencyCode = "KES";
// The checkout amount
$amount       = 100.50;

// Any metadata that you would like to send along with this request
// This metadata will be  included when we send back the final payment notification
$metadata     = array("agentId"   => "654",
		              "productId" => "321");
try {
  // Initiate the checkout. If successful, you will get back a transactionId
  $transactionId = $gateway->initiateMobilePaymentCheckout($productName,
							   $phoneNumber,
							   $currencyCode,
							   $amount,
							   $metadata);
  echo "The id here is ".$transactionId;
}
catch(AfricasTalkingGatewayException $e){
  echo "Received error response: ".$e->getMessage();
}


?>
    

Initiate Mobile Checkout using Java

The Java code snippet below shows how to initiate a checkout request 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 or has been added to 
   referenced libraries if you are using an SDK like eclipse or netbeans*/
// Make sure the downloaded jar file is in the classpath
import org.json.*;
import java.util.HashMap;

// Make sure the downloaded jar file is in the classpath
public class TestMobilePaymentCheckout
{
    public static void main(String[] args_)
    {
	//Specify your credentials
	String username = "MyAfricasTalkingUsername";
	String apiKey   = "MyAfricasTalkingPassword";

	// NOTE: If connecting to the sandbox, please use your sandbox login credentials

	//Create an instance of our awesome gateway class and pass your credentials
	AfricasTalkingGateway gateway = new AfricasTalkingGateway(username, apiKey);
	
	// NOTE: If connecting to the sandbox, please add the sandbox flag to the constructor:
	/*************************************************************************************
	                        ****SANDBOX****
			AfricasTalkingGateway gateway    = new AfricasTalkingGateway(username, apikey, "sandbox");
	**************************************************************************************/
	
	// Specify the name of your Africa's Talking payment product
	String productName  = "My Online Store";
	// The phone number of the customer checking out
	String phoneNumber  = "+254711XXXYYY";
	// The 3-Letter ISO currency code for the checkout amount
	String currencyCode = "KES";
	// The checkout amount
	Double amount       = 100.50;
	// Any metadata that you would like to send along with this request
	// This metadata will be  included when we send back the final payment notification
	HashMap<String, String> metadata = new HashMap<String, String>();	
	metadata.put("agentId", "654");
	metadata.put("productId", "321");
	try {
	    // Initiate the checkout. If successful, you will get back a transactionId
	    String transactionId = gateway.initiateMobilePaymentCheckout(productName,
									 phoneNumber,
									 currencyCode,
									 amount,
									 metadata);
	    System.out.println("The transactionId is " + transactionId);
	}
	catch(Exception ex){
	    System.out.println("Received error response: " + ex.getMessage());
	}
    }
}


Initiate Mobile Checkout using Python

The PHP code snippet below shows how to initiate a checkout request 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"

# NOTE: If connecting to the sandbox, please use your sandbox login credentials

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

# NOTE: If connecting to the sandbox, please add the sandbox flag to the constructor:
#************************************************************************************#
#             ****SANDBOX****                                                        #
#gateway    = AfricasTalkingGateway(username, apiKey, "sandbox")                     #
#************************************************************************************#

# Specify the name of your Africa's Talking payment product
productName  = "My Online Store"
# The phone number of the customer checking out
phoneNumber  = "+254711XXXYYY"
# The 3-Letter ISO currency code for the checkout amount
currencyCode = "KES"
# The checkout amount
amount       = 100.50
# Any metadata that you would like to send along with this request
# This metadata will be  included when we send back the final payment notification
metadata     = {"agentId"   : "654",
		        "productId" : "321"}
try:
    # Initiate the checkout. If successful, you will get back a transactionId
    transactionId = gateway.initiateMobilePaymentCheckout(productName,
							  phoneNumber,
							  currencyCode,
							  amount,
							  metadata)
    print "The transactionId is " + transactionId
    
except AfricasTalkingGatewayException, e:
    print "Received error response: %s" % str(e)


Sending messages: Use short code/Sender id

# Sending Messages using sender id/short code

from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

username = "MyAfricasTalkingUsername"
apikey   = "MyAfricasTalkingAPIKey"

to      = "+254711XXXYYY,+254733YYYZZZ"

message = "I'm a lumberjack and it's ok, I sleep all night and I work all day"

# Specify your AfricasTalking shortCode or sender id
sender = "shortCode or senderId"

gateway = AfricasTalkingGateway(username, apikey)

try:
    
    results = gateway.sendMessage(to, message, sender)
    
    for recipient in results:
        # Note that only the Status "Success" means the message was sent
        print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'],
                                                            recipient['status'],
                                                            recipient['messageId'],
                                                            recipient['cost'])
except AfricasTalkingGatewayException, e:
    print 'Encountered an error while sending: %s' % str(e)

Sending messages: Queue messages to be sent later

# Message queueing 

from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

username = "MyAfricasTalkingUsername"
apikey   = "MyAfricasTalkingAPIKey"

to      = "+254711XXXYYY,+254733YYYZZZ"

message = "I'm a lumberjack and it's ok, I sleep all night and I work all day"

sender = None # sender = "shortCode or sender id"

bulkSMSMode = 1    # This should always be 1 for bulk messages

# enqueue flag is used to queue messages incase you are sending a high volume.
# The default value is 0.
enqueue = 1

gateway = AfricasTalkingGateway(username, apikey)

try:
    
    results = gateway.sendMessage(to, message, sender, bulkSMSMode, enqueue)
    
    for recipient in results:
        # Note that only the Status "Success" means the message was sent
        print 'number=%s;status=%s;messageId=%s;cost=%s' % (recipient['number'],
                                                            recipient['status'],
                                                            recipient['messageId'],
                                                            recipient['cost'])
except AfricasTalkingGatewayException, e:
    print 'Encountered an error while sending: %s' % str(e)

Sending premium rated messages

# Sending premium rated messages

from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException

username = "MyAfricasTalkingUsername"
apikey   = "MyAfricasTalkingAPIKey"

to      = "+254711XXXYYY"


message = "Get your daily message and thats how we roll.";

# Specify your premium shortCode and keyword
# Set keyword as None where not used (Mostly for onDemand services)

shortCode = "XXXXX"
keyword   = "premiumKeyword" # keyword = None

# Set the bulkSMSMode flag to 0 so that the subscriber gets charged
bulkSMSMode = 0

# Set the enqueue flag to 0 so that your message will not be queued or to 1 for many messages
enqueue    = 0

# Incase of an onDemand service, specify the link id. else set it to none
# linkId is received from the message sent by subscriber to your onDemand service
linkId = "messageLinkId" #linkId = None

# Specify retryDurationInHours: The numbers of hours our API should retry to send the message
# incase it doesn't go through. It is optional
retryDurationInHours = "No of hours to retry"

gateway = AfricasTalkingGateway(username, apikey)

try:
    
    recipients = gateway.sendMessage(to, message, shortCode, bulkSMSMode, enqueue, keyword, linkId, retryDurationInHours)
    for recipient in recipients:
        print 'number=%s;status=%s;messageId=%s' % (recipient['number'],
                                                    recipient['status'],
                                                    recipient['messageId'])
except AfricasTalkingGatewayException, e:
    print 'Encountered an error while sending: %s' % str(e)

Initiate Mobile Checkout using Ruby

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

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

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

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

# NOTE: If connecting to the sandbox, please use your sandbox login credentials

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

# The phone number of the customer checking out
phoneNumber  = "+254711XXXYYY"

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

# The checkout amount
amount       = 100.50

# Any metadata that you would like to send along with this request
# This metadata will be  included when we send back the final payment notification
metadata     = {"agentId"   : "654",
                "productId" : "321"}
                
# Create a new instance of our awesome gateway class
gateway = AfricasTalkingGateway.new(username, apikey)

# NOTE: If connecting to the sandbox, please add the sandbox flag to the constructor:
#************************************************************************************#
#             ****SANDBOX****                                                        #
#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
begin
	# Initiate the checkout. If successful, you will get back a transactionId
	transactionId = gateway.initiateMobilePaymentCheckout(productName, phoneNumber,  currencyCode, amount, metadata)
	puts transactionId
	
rescue Exception => ex
	puts "Encountered an error: " + ex.message
end

# DONE!