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 Node.js

The Node.js code snippet below shows how to send SMS Messages using our API.

Sending a Message

// We need this to build our post string

var querystring = require('querystring');
var https       = require('https');

// Your login credentials
var username = 'MyAfricasTalkingUsername';
var apikey   = 'MyAfricasTalkingApiKey';

function sendMessage() {
	
	// Define the recipient numbers in a comma separated string
	// Numbers should be in international format as shown
	var to      = '+254711XXXYYY,+254733YYYZZZ';
	
	// And of course we want our recipients to know what we really do
	var message = "I'm a lumberjack and its ok, I sleep all night and I work all day";
	
	// Build the post string from an object
	
	var post_data = querystring.stringify({
	    'username' : username,
	    'to'       : to,
	    'message'  : message
	});
	
	var post_options = {
		host   : 'api.africastalking.com',
		path   : '/version1/messaging',
		method : 'POST',
		
		rejectUnauthorized : false,
		requestCert        : true,
		agent              : false,
		
		headers: {
		    'Content-Type' : 'application/x-www-form-urlencoded',
		    'Content-Length': post_data.length,
		    'Accept': 'application/json',
		    'apikey': apikey
		}
	};
	
	var post_req = https.request(post_options, function(res) {
	    res.setEncoding('utf8');
	    res.on('data', function (chunk) {
		    var jsObject   = JSON.parse(chunk);
		    var recipients = jsObject.SMSMessageData.Recipients;
		    if ( recipients.length > 0 ) {
		    	for (var i = 0; i < recipients.length; ++i ) {
		    		var logStr  = 'number=' + recipients[i].number;
		    		logStr     += ';cost='   + recipients[i].cost;
		    		logStr     += ';status=' + recipients[i].status; // status is either "Success" or "error message"
		    		console.log(logStr);
		    		}
		    	} else {
		    		console.log('Error while sending: ' + jsObject.SMSMessageData.Message);
		    }
		});
	});
	
	// Add post parameters to the http request
	post_req.write(post_data);
	
	post_req.end();
}

//Call sendMessage method
sendMessage();

Sending messages: Use short code/Sender id

// Sending Messages using sender id/short code

var querystring = require('querystring');
var https       = require('https');

var username = 'MyAfricasTalkingUsername';
var apikey   = 'MyAfricasTalkingApiKey';

function sendMessage() {
	
	var to      = '+254711XXXYYY,+254733YYYZZZ';
	
	var message = "I'm a lumberjack and its ok, I sleep all night and I work all day";
	
	// Specify your AfricasTalking shortCode or sender id
	var from = "shortCode or senderId";
	
	var post_data = querystring.stringify({
		 'username' : username,
		 'to'       : to,
		 'message'  : message,
		 'from'     : from
	});
	
	var post_options = {
		host   : 'api.africastalking.com',
		path   : '/version1/messaging',
		method : 'POST',
		
		rejectUnauthorized : false,
		requestCert        : true,
		agent              : false,
		
		headers: {
		    'Content-Type' : 'application/x-www-form-urlencoded',
		    'Content-Length': post_data.length,
		    'Accept': 'application/json',
		    'apikey': apikey
		}
	};
	var post_req = https.request(post_options, function(res) {
		
		res.setEncoding('utf8');
		res.on('data', function (chunk) {
			var jsObject   = JSON.parse(chunk);
			var recipients = jsObject.SMSMessageData.Recipients;
			if ( recipients.length > 0 ) {
				for (var i = 0; i < recipients.length; ++i ) {
					var logStr  = 'number=' + recipients[i].number;
					logStr     += ';cost='   + recipients[i].cost;
					logStr     += ';status=' + recipients[i].status;
					console.log(logStr);
					}
				} else {
					console.log('Error while sending: ' + jsObject.SMSMessageData.Message);
				}
		});
	});
	
	post_req.write(post_data);
	
	post_req.end();
}

//Call sendMessage method
sendMessage();

Sending messages: Queue messages to be sent later

// Message queueing

var querystring = require('querystring');
var https       = require('https');

var username = 'MyAfricasTalkingUsername';
var apikey   = 'MyAfricasTalkingApiKey';

function sendMessage() {
	
	var to      = '+254711XXXYYY,+254733YYYZZZ';
	
	var message = "I'm a lumberjack and its ok, I sleep all night and I work all day";
	
	// enqueue flag is used to queue messages incase you are sending a high volume.
	// The default value is 0.
	var enqueue = 1;
	
	var post_data = querystring.stringify({
		  'username' : username,
		  'to'       : to,
		  'message'  : message,
		  'enqueue'  : enqueue
	});
	
	var post_options = {
		host   : 'api.africastalking.com',
		path   : '/version1/messaging',
		method : 'POST',
		
		rejectUnauthorized : false,
		requestCert        : true,
		agent              : false,
		
		headers: {
		    'Content-Type' : 'application/x-www-form-urlencoded',
		    'Content-Length': post_data.length,
		    'Accept': 'application/json',
		    'apikey': apikey
		}
	};
	var post_req = https.request(post_options, function(res) {
		
		res.setEncoding('utf8');
		res.on('data', function (chunk) {
			var jsObject   = JSON.parse(chunk);
			var recipients = jsObject.SMSMessageData.Recipients;
			if ( recipients.length > 0 ) {
				for (var i = 0; i < recipients.length; ++i ) {
					var logStr  = 'number=' + recipients[i].number;
					logStr     += ';cost='   + recipients[i].cost;
					logStr     += ';status=' + recipients[i].status;
					console.log(logStr);
					}
				} else {
					console.log('Error while sending: ' + jsObject.SMSMessageData.Message);
				}
		});
	});
	
	post_req.write(post_data);
	
	post_req.end();
}

//Call sendMessage method
sendMessage();

Sending premium rated (subscription) messages

// Sending premium rated messages

var querystring = require('querystring');
var https       = require('https');

var username = 'MyAfricasTalkingUsername';
var apikey   = 'MyAfricasTalkingApiKey';

function sendMessage() {
	
	    var to      = '+254711XXXYYY';
	    
	    // Specify your premium shortcode and keyword
	    var shortCode = "XXXXX";
	    var keyword = "premiumKeyword";
	    
	    // Set the bulkSMSMode flag to 0 so that the subscriber gets charged
	    var bulkSMSMode = 0;
	    
	    // retryDurationInHours: The numbers of hours our API should retry to send the message 
	    // before giving a failure status incase it doesn't go through. It is optional
	    // incase it doesn't go through. It is optional
	    
	    var retryDurationInHours = "No. of hours to retry";
	    
	    var message = "Get your daily message and thats how we roll.";
	    
    // Build the post string from an object
    var post_data = querystring.stringify({
	    'username'             : username,
	    'to'                   : to,
	    'message'              : message,
	    'from'                 : shortCode,
	    'keyword'              : keyword,
	    'retryDurationInHours' : retryDurationInHours
	});
	
	var post_options = {
		host   : 'api.africastalking.com',
		path   : '/version1/messaging',
		method : 'POST',
		
		rejectUnauthorized : false,
		requestCert        : true,
		agent              : false,
		
		headers: {
		    'Content-Type' : 'application/x-www-form-urlencoded',
		    'Content-Length': post_data.length,
		    'Accept': 'application/json',
		    'apikey': apikey
		}
	};
    
    var post_req = https.request(post_options, function(response) {
	    response.setEncoding('utf8');
	    response.on('data', function (chunk) {
	    	try {
	    		if(response.statusCode != 201)
	    		 throw chunk;
	    		 
	    		 var jsObject   = JSON.parse(chunk);
	    		 var recipients = jsObject.SMSMessageData.Recipients;
	    		 if ( recipients.length > 0 ) {
	    		 	for (var i = 0; i < recipients.length; ++i ) {
	    		 		var logStr  = 'number=' + recipients[i].number;
	    		 		logStr     += ';messageId='   + recipients[i].messageId;
	    		 		logStr     += ';status=' + recipients[i].status;
	    		 		console.log(logStr);
		    		}
		    	}
		    }
		   
		   catch(errorStr) {
		     console.log(errorStr);
		   }
		});
	});
    
    post_req.write(post_data);
    post_req.end();
}

sendMessage();

Sending premium rated (onDemand) messages

// Sending onDemand premium messages

var querystring = require('querystring');
var https       = require('https');

var username = 'MyAfricasTalkingUsername';
var apikey   = 'MyAfricasTalkingApiKey';

function sendMessage() {
	
	    var to      = '+254711XXXYYY';
	    
	    var shortCode = "XXXXX";
	    var keyword = "premiumKeyword"; // var keyword = null
	    
	    var bulkSMSMode = 0;
	    
	    // Set the linkId parameter
	    // linkId is received from the message sent by subscriber to your onDemand service
	    
	    var linkId = "messageLinkId";
	         
	    var retryDurationInHours = "No. of hours to retry";
	    
	    var message = "Get your daily message and thats how we roll.";
	    
    // Build the post string from an object
    var post_data = querystring.stringify({
	    'username'             : username,
	    'to'                   : to,
	    'message'              : message,
	    'from'                 : shortCode,
	    'keyword'              : keyword,
	    'linkId'               : linkId,
	    'retryDurationInHours' : retryDurationInHours
	});
	
	var post_options = {
		host   : 'api.africastalking.com',
		path   : '/version1/messaging',
		method : 'POST',
		
		rejectUnauthorized : false,
		requestCert        : true,
		agent              : false,
		
		headers: {
		    'Content-Type' : 'application/x-www-form-urlencoded',
		    'Content-Length': post_data.length,
		    'Accept': 'application/json',
		    'apikey': apikey
		}
	};
    
    var post_req = https.request(post_options, function(response) {
	    response.setEncoding('utf8');
	    response.on('data', function (chunk) {
	    	try {
	    		if(response.statusCode != 201)
	    		 throw chunk;
	    		 
	    		 var jsObject   = JSON.parse(chunk);
	    		 var recipients = jsObject.SMSMessageData.Recipients;
	    		 if ( recipients.length > 0 ) {
	    		 	for (var i = 0; i < recipients.length; ++i ) {
	    		 		var logStr  = 'number=' + recipients[i].number;
	    		 		logStr     += ';messageId='   + recipients[i].messageId;
	    		 		logStr     += ';status=' + recipients[i].status;
	    		 		console.log(logStr);
		    		}
		    	}
		    }
		   
		   catch(errorStr) {
		     console.log(errorStr);
		   }
		});
	});
    
    post_req.write(post_data);
    post_req.end();
}

sendMessage();