Send Airtime

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.

The Java code snippet below shows how to send airtime 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.*;

public class TestAirime 
{

	public static void main(String[] args) 
	{

		//Specify your credentials
		String username = "myAfricasTalkingUsername";
		String apiKey   = "myAfricasTalkingAPIKey";

		//Specify the phone number/s and amount in the format shown
		//Specify the country currency and the amount as shown below (+254 for Kenya in this case)
		// Please ensure you include the country code for phone numbers (KES for Kenya in this case)
		
		//Declare an json array to hold the recipients and the amount to send
		JSONArray recipients = new JSONArray();
		
		//Add the first recipient and the amount as a json object to the json array
		recipients.put(new JSONObject().put("phoneNumber","+254711XXXYYY").put("amount","KES XX"));
		
		//Add the second recipient and the amount as a json object to the json array
		recipients.put(new JSONObject().put("phoneNumber","+254733YYYZZZ").put("amount","KES YY"));
		
		//Convert the recipient array into a string. The string produced will have the format:
		// [{"amount":"KES 100", "phoneNumber":+254711XXXYYY},{"amount":"KES 100", "phoneNumber":+254733YYYZZZ}]
		//A string with the shown format may be created directly and skip the above steps
		String recipientStringFormat = recipients.toString();

		//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");
		**************************************************************************************/

		// Thats it, hit send and we'll take care of the rest. Any errors will
   		// be captured in the Exception class as shown below
		try {
   			JSONArray results = gateway.sendAirtime(recipientStringFormat);
   			int length = results.length();
   			for(int i = 0; i < length; i++) {
   	 		JSONObject result = results.getJSONObject(i);
				System.out.println(result.getString("status"));
				System.out.println(result.getString("amount"));
				System.out.println(result.getString("phoneNumber"));
				System.out.println(result.getString("discount"));
				System.out.println(result.getString("requestId"));

				//Error message is important when the status is not Success
				System.out.println(result.getString("errorMessage"));
   			}
		} catch(Exception e){
   			System.out.println(e.getMessage());
   		}
	}
}
To send airtime you will need to make a HTTP POST request to the following url:
POST URL: http://api.africastalking.com/version1/airtime/send

Limits

We however have a limit of the amount you can send as shown below:

Minimum amount Maximum amount
KES 10 KES 10,000
The server expects:
Parameter Location Description Required
API key Header API key generated from your account settings Yes
Accept Header This is the format you would like your data formatted. It may be application/xml or application/json. The default is application/xml. The gateway classes provided uses appliaction/json. No
username Body This is your Africa'sTalking username Yes
recipients Body Contains the a list of airtime recipients in JSON format. It should look like:
[{"phoneNumber":"+254711XXXYYY","amount":"KES X"},{"phoneNumber":"+254733YYYZZZ","amount":"KES Y"}]
Yes
Upon successful processing, the server shall respond in the following format:
XML
                        
<?xml version="1.0"?>
  <AirtimeResponse>
    <numSent>n</numSent>
    <totalAmount>KES XXX</totalAmount>
    <totalDiscount>KES YYY</totalDiscount>
    <responses>
      <response>
        <phoneNumber>+254711XXXYYY</phoneNumber>
        <amount>KES 1000.0000</amount>
        <discount>40.0000</discount>
        <status>Success</status>
        <requestId>ATQid_4fbec14b3c6b976d398957f9f8a65b3d</requestId>
        <errorMessage>None</errorMessage>
      </response>
      .
      .
      .
      .
      <response>
        <phoneNumber>+254733YYYZZZ</phoneNumber>
        <amount>KES 2000.0000</amount>
        <discount>80.0000</discount>
        <status>Failed</status>
        <requestId>ATQid_7gbec14b5c7b876h375848fy8a56c2b</requestId>
        <errorMessage>None</errorMessage>
      </response>
    </responses>
    <errorMessage>None</errorMessage>
  </AirtimeResponse>
 
JSON

{
 "numSent": n,
 "totalAmount": "KES XXX",
 "totalDiscount" : "KES YYY",
 "responses" : [
      {
        "errorMessage":"None",
        "phoneNumber":"+254711XXXYYY",
        "amount":"KES 1000",
        "discount":"40.0000",
        "status":"sent",
        "requestId":"ATQid_4fbec14b3c6b976d398957f9f8a65b3d"
      },
      .
      .
      .
      .
      {
        "errorMessage":"None",
        "phoneNumber":"+254733YYYZZZ",
        "amount":"KES 2000",
        "discount":"80.0000",
        "status":"sent",
        "requestId":"ATQid_7gbec14b5c7b876h375848fy8a56c2b"
      }
  ],
  "errorMessage":"None"
 }