Send SMS

To send a message you will need to make a HTTP POST request to the following url:
POST URL: http://api.africastalking.com/version1/messaging
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 username Yes
to Body The recipients Yes
message Body This is the message to b sent Yes
from Body Shortcode or alphanumeric that is registered with your Africa's Talking account. If missing, the default value (20414) will be populated on the message No
bulkSMSMode Body This parameter will be used by the Mobile Service Provider to determine who gets billed for a message sent using a Mobile-Terminated ShortCode. The default value is 1 (which means that the sender(The AfricasTalking account being used ) gets charged). This parameter will be ignored for messages sent using alphanumerics or Mobile-Originated shortcodes. The value must be set to 1 for bulk messages No
enqueue Body This parameter is used for Bulk SMS clients that would like deliver as many messages to the API before waiting for an Ack from the Telcos. If enabled, the API will store the messages in its databases and send them out asynchronously after responding to the request No
keyword Body This parameter is used for premium services. It is essential for subscription premium services. No (Essential for subscription premium services)
linkId Body This parameter is used for premium services to send OnDemand messages. We forward the linkId to your application when the user send a message to your service. No (Essential for onDemand services.)
retryDurationInHours Body This parameter is used for premium messages. It specifies the number of hours your subscription message should be retried in case it's not delivered to the subscriber. No

Upon successful processing, the server shall respond in the following format:
XML
                        
<?xml version="1.0"?>
  <AfricastalkingResponse>
   <SMSMessageData>
     <Recipients>
       <Recipient>
         <number>+254711XXXYYY</number>
         <cost>KES YY</cost>
         <status>Success</status>
         <messageId>ATSid_1</messageId>
       </Recipient>
       .
       .
       .
       .
       <Recipient>
         <number>+254733YYYZZZ</number>
         <cost>KES XX</cost>
         <messageId>ATSid_2</messageId>
       </Recipient>
       
      </Recipients>
    </SMSMessageData>
  </AfricastalkingResponse>
 
JSON

{"SMSMessageData":
  {"Recipients":
    [
      {
       "number"    : "+254711XXXYYY",
       "cost"      : "KES YY",
       "status"    : "Success",
       "messageId" : "ATSid_1"
      },
      .
      .
      .
      .
      {
        "number"    : "+254733YYYZZZ",
        "cost"      : "KES XX",
        "status"    : "Success",
        "messageId" : "ATSid_n"
      }
    ]
  }
}
Example using CURL client
curl -v -H "Accept: application/xml" -d "username=myusername&message=hello test&to=+254711XXXYYY,+254733YYYZZZ" -H "Apikey:fb752d3417021812f0961y6c9464832dd1adb1
e555c73f1e7c32bcc006488674" -X POST http://api.africastalking.com/version1/messaging --insecure

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

Send messages using Java

The Java code snippet below shows how to send SMS Messages 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

Sending a Message

/* 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*/
import org.json.*;
import java.util.HashMap;

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

		// Specify the numbers that you want to send to in a comma-separated list
		// Please ensure you include the country code (+254 for Kenya in this case)
		String recipients = "+254711XXXYYY,+254733YYYZZZ";

		// And of course we want our recipients to know what we really do
		String message = "We are lumberjacks. We code all day and sleep all night";

		// 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 {
			JSONArray results = gateway.sendMessage(recipients, message);

			for( int i = 0; i < results.length(); ++i ) {
				JSONObject result = results.getJSONObject(i);
				System.out.print(result.getString("status") + ","); // status is either "Success" or "error message"
				System.out.print(result.getString("number") + ",");
				System.out.print(result.getString("messageId") + ",");
				System.out.println(result.getString("cost"));
			}
		} catch (Exception e) {
			System.out.println("Encountered an error while sending " + e.getMessage());
		}
	}
}

Sending messages: Use short code/Sender id

// Sending Messages using sender id/short code

import org.json.*;
import java.util.HashMap;

public class TestSending
{
    public static void main(String[] args_)
    {
	     String username = "MyUsername";
	     String apiKey   = "MyAPIKey";
	
	     String recipients = "+254711XXXYYY,+254733YYYZZZ";
	
	     String message = "We are lumberjacks. We code all day and sleep all night";
	     
	     // Specify your AfricasTalking shortCode or sender id
	     String from = "shortCode or senderId";
	
	     AfricasTalkingGateway gateway  = new AfricasTalkingGateway(username, apiKey);
	     
	    try {
	        JSONArray results = gateway.sendMessage(recipients, message, from);
			
	        for( int i = 0; i < results.length(); ++i ) {
		          JSONObject result = results.getJSONObject(i);
		          System.out.print(result.getString("status") + ",");
		          System.out.print(result.getString("number") + ",");
		          System.out.print(result.getString("messageId") + ",");
		          System.out.println(result.getString("cost"));
	    }
   	}
   	
   	catch (Exception e) {
	    System.out.println("Encountered an error while sending " + e.getMessage());
	    }
	
   }
}

Sending messages: Queue messages to be sent later

// Message queueing

import org.json.*;
import java.util.HashMap;

public class TestSending
{
    public static void main(String[] args_)
    {
	     String username = "MyUsername";
	     String apiKey   = "MyAPIKey";
	
	     String recipients = "+254711XXXYYY,+254733YYYZZZ";
	
	     String message = "We are lumberjacks. We code all day and sleep all night";
	     
	     String from = null; //String from = "shortCode or senderId";
	     
	     int 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.
	     HashMap<String, int> options = new HashMap<String, int>();
	     options.put("enqueue", 1);
	
	     AfricasTalkingGateway gateway  = new AfricasTalkingGateway(username, apiKey);
	     
	    try {
	        JSONArray results = gateway.sendMessage(recipients, message, from, bulkSMSMode, options);
			
	        for( int i = 0; i < results.length(); ++i ) {
		          JSONObject result = results.getJSONObject(i);
		          System.out.print(result.getString("status") + ",");
		          System.out.print(result.getString("number") + ",");
		          System.out.print(result.getString("messageId") + ",");
		          System.out.println(result.getString("cost"));
	    }
   	}
   	
   	catch (Exception e) {
	    System.out.println("Encountered an error while sending " + e.getMessage());
	    }
	
   }
}

Sending premium rated (subscription) messages

// Sending premium rated messages

import org.json.*;
import java.util.HashMap;

public class TestSending
{
    public static void main(String[] args_)
    {
    	
	     String username = "MyUsername";
	     String apiKey   = "MyAPIKey";
	     
	     String recipient = "+254711XXXYYY";
	     
	     String message = "Get your daily message and thats how we roll.";
	
	     // Specify your premium shortcode and keyword
	     String shortCode = "XXXXX";
	     String keyword = "premiumKeyword";
	     
	     // Set the bulkSMSMode flag to 0 so that the subscriber get charged
	     int bulkSMSMode = 0;
	     
	     // Create a hashmap which would hold the following parameters:
	     // keyword: Your premium keyword,
	     // retryDurationInHours: The numbers of hours our API should retry to send the message 
	     // incase it doesn't go through. It is optional
	     
	     HashMap<String, String> options = new HashMap<String, String>();
	     options.put("keyword", keyword);
	     options.put("retryDurationInHours", "No. of hours to retry sending message");
	     
	     AfricasTalkingGateway gateway  = new AfricasTalkingGateway(username, apiKey);
	     
	     try  {
	     	
	        JSONArray results = gateway.sendMessage(recipient, message, from, bulkSMSMode, options);
	        for( int i = 0; i < results.length(); ++i ) {
		          JSONObject result = results.getJSONObject(i);
		          System.out.print(result.getString("status") + ",");
		          System.out.print(result.getString("number") + ",");
		          System.out.print(result.getString("messageId") + ",");
	    }
   	}
   	
   	catch (Exception e) {
	    System.out.println("Encountered an error while sending " + e.getMessage());
	    }
	
   }
}

Sending premium rated (onDemand) messages

// Sending onDemand premium messages

import org.json.*;
import java.util.HashMap;

public class TestSending
{
    public static void main(String[] args_)
    {
    	
	     String username = "MyUsername";
	     String apiKey   = "MyAPIKey";
	     
	     String recipient = "+254711XXXYYY";
	     
	     String message = "Get your daily message and thats how we roll.";
	
	     String shortCode = "XXXXX";
	     String keyword = "premiumKeyword"; // String keyword = null;
	     
	     int bulkSMSMode = 0;
	     
	     // Create a hashmap which would hold parameters keyword, retryDurationInHours and linkId
	     // linkId is received from the message sent by subscriber to your onDemand service
	     String linkId = "messageLinkId";
	     
	     HashMap<String, String> options = new HashMap<String, String>();
	     options.put("keyword", keyword);
	     options.put("linkId", linkId);
	     options.put("retryDurationInHours", "No. of hours to retry sending message");
	     
	     AfricasTalkingGateway gateway  = new AfricasTalkingGateway(username, apiKey);
	     
	     try  {
	     	
	        JSONArray results = gateway.sendMessage(recipient, message, from, bulkSMSMode, options);
	        
	        for( int i = 0; i < results.length(); ++i ) {
		          JSONObject result = results.getJSONObject(i);
		          System.out.print(result.getString("status") + ",");
		          System.out.print(result.getString("number") + ",");
		          System.out.print(result.getString("messageId") + ",");
	    }
   	}
   	
   	catch (Exception e) {
	    System.out.println("Encountered an error while sending " + e.getMessage());
	    }
	
   }
}