Generate Token
Before you begin API integrations you will have to generate authorization token. Below steps are outlined on how to generate authorization token. You need to create an account at SMS Africa. Once you have the account, login to your account
Step 1
Once logged in go to the bottom left red sidebar, look for cog wheel icon (show in the below image) and click it

Step 2
Setting popup will show once you click the cog wheel icon. Click the API section then click generate API Token button. Shown in the below image. Once the API is generated it will be displayed in the same popup window. Copy the API Token and store it securely.

Authentication headers
SMS Africa Portal uses API key to allow access to the API. You can register a new API key by logging in to your account and follow the above steps. SMS Africa Portal expects API key to be included in all API requests to the server in a header that looks like the following:
Authorization: secureapikeys
Bulk SMS APIs
Send Single SMS
Use this API to send single SMS or Same SMS upto 50 numbers at the same time.
API Endpoint
POST /api/message/send/sms
Query Input Parameters
The API expects a JSON payload with the following
| Key | Required | Data Type | Default | Description |
|---|---|---|---|---|
| message | yes | String | none | message ro send |
| msisdn | yes | String | true | Recipient phone number. To send same SMS to more than 1 number separate multiple numbers with comma ( , ) |
| sender_id | no | String | SMSSavvy | your registered sender ID |
| callback_url | no | String | none | Where DLR report will be send back |
This endpoint expects JSON in the below format:
{
"message": "message here",
"msisdn": "2547xxxxxxxx",
"sender_id": "SMSSavvy",
"callback_url": "https://callback.io/123/dlr"
}
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.smsafrica.tech/api/message/send/sms")
header = {'Content-Type': 'text/json','Authorization':'secureapikeys'}
user = {
message: 'message here',
msisdn: '2547xxxxxxxx',
sender_id: 'SMS Africa',
callback_url: 'https://callback.io/123/dlr'
}
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = user.to_json
# Send the request
response = http.request(request)
import requests
newHeaders = {'Content-type': 'application/json', 'Authorization': 'secureapikeys'}
payload = {'message': 'message here','msisdn':'2547xxxxxxxx','sender_id':'SMS Africa','callback_url': 'https://callback.io/123/dlr'}
response = requests.post('https://api.smsafrica.tech/api/message/send/sms',data=payload,headers=newHeaders)
print("Status code: ", response.status_code)
response_Json = response.json()
print("Printing Post JSON data")
print(response_Json['status'])
print(response_Json['message'])
curl --location --request POST 'https://api.smsafrica.tech/api/message/send/sms' \
--header 'Content-Type: application/json' \
--header 'Authorization: secureapikeys' \
--data-raw '{
"message": "You message",
"msisdn": "2547xxxxxxxx",
"sender_id": "SMS Africa",
"callback_url": "https://callback.io/123/dlr"
}'
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "https://api.smsafrica.tech/api/message/send/sms";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Authorization","secureapikeys");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 ) {
// Print received data from server
console.log(this.responseText.status);
console.log(this.responseText.message);
}
};
var message = {
"message": "message here",
"msisdn": "2547xxxxxxxx",
"sender_id": "SMS Africa",
"callback_url": "https://callback.io/123/dlr",
}
// Converting JSON data to string
var data = JSON.stringify(message);
// Sending data with the request
xhr.send(data);
package main
import (
"bytes"
"fmt"
"net/http"
"io/ioutil"
"encoding/json"
)
func main() {
url := "http://api.smsafrica.tech/api/message/send/sms"
method := "POST"
// construct your message using interface
message := map[string] interface{}{
"message": "You message",
"msisdn":"2547xxxxxxxx",
"sender_id":"SMS Africa",
"callback_url": "https://callback.io/123/dlr",
}
// convert to json
payload,err := json.Marshal(message)
if err != nil {
fmt.Println(err)
}
// make http request
client := &http.Client {}
req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
if err != nil {
fmt.Println(err)
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "secureapikeys")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
URL url = new URL ("https://api.smsafrica.tech/api/message/send/sms");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "secureapikeys");
con.setDoOutput(true);
//JSON String need to be constructed for the specific resource.
Map<String, String> map = new LinkedHashMap<>();
map.put("message","You message");
map.put("msisdn","2547xxxxxxxx");
map.put("sender_id","SMS Africa");
map.put("callback_url","https://callback.io/123/dlr");
Gson gson = new Gson();
String jsonInputString = gson.toJson(map);
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
}
<?php
$message = [
"message" => 'You message',
"msisdn" => "2547xxxxxxxx",
"sender_id" => "SMS Africa" ,
"callback_url" => "https://callback.io/123/dlr"
];
$data_string = json_encode($message);
$secureapikeys = "secureapikeys";
$httpRequest = curl_init("https://api.smsafrica.tech/api/message/send/sms");
curl_setopt($httpRequest,CURLOPT_POST,true);
curl_setopt($httpRequest,CURLOPT_POSTFIELDS,$data_string);
curl_setopt($httpRequest,CURLOPT_TIMEOUT,60);
curl_setopt($httpRequest,CURLOPT_RETURNTRANSFER,1);
curl_setopt($httpRequest,CURLOPT_HTTPHEADER,array(
"Content-Type:application/json",
"Authorization: $secureapikeys"
)
);
curl_setopt($httpRequest,CURLOPT_RETURNTRANSFER,true);
//curl_setopt($httpRequest,CURLOPT_HEADER,1);
$response = curl_exec($httpRequest);
$status = curl_getinfo($httpRequest,CURLINFO_HTTP_CODE);
curl_close($httpRequest);
echo $status;
echo $response;
The above command returns JSON structured like this on success:
{
"message": "SMS successfully queued for sending. Total recipients 1",
"status": 200,
"transaction_id": 2295
}
On failure the following is returned, refere to status codes for error types
{
"status": 428,
"message": "error message"
}
Schedule SMS
This API supports SMS Scheduling, an SMS that has been scheduled will be queued to be send later
API Endpoint
POST /api/message/send/sms
Query Input Parameters
The API expects a JSON payload with the following
| Key | Required | Data Type | Default | Description |
|---|---|---|---|---|
| message | yes | String | none | message ro send |
| msisdn | yes | String | true | Recipient phone number. To send same SMS to more than 1 number separate multiple numbers with comma ( , ) |
| country_code | no | String | ke | if this is not a kenya number, supply the country code |
| sender_id | no | String | SMSSavvy | your registered sender ID |
| callback_url | no | String | none | Where DLR report will be send back |
| schedule | no | Boolean | false | Is this SMS to be scheduled? |
| date | no | String | none | Date to send the SMS, date format YYYY-MM-DD |
| send_time | no | String | none | Time to send the SMS |
This endpoint expects JSON in the below format:
{
"message": "message here",
"msisdn": "2547xxxxxxxx",
"sender_id": "SMSSavvy",
"callback_url": "https://callback.io/123/dlr",
"schedule": true,
"date": "2030-01-01",
"send_time": "09:30:01"
}
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.smsafrica.tech/api/message/send/sms")
header = {'Content-Type': 'text/json','Authorization':'secureapikeys'}
user = {
message: 'message here',
msisdn: '2547xxxxxxxx',
sender_id: 'SMS Africa',
callback_url: 'https://callback.io/123/dlr',
schedule: true,
date: '2030-01-01',
send_time: '09:30:01'
}
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = user.to_json
# Send the request
response = http.request(request)
import requests
newHeaders = {'Content-type': 'application/json', 'Authorization': 'secureapikeys'}
payload = {'message': 'message here','msisdn':'2547xxxxxxxx','sender_id':'SMS Africa','callback_url': 'https://callback.io/123/dlr','schedule': true,'date':'2030-09-01','send_time':'09:30:01'}
response = requests.post('https://api.smsafrica.tech/api/message/send/sms',data=payload,headers=newHeaders)
print("Status code: ", response.status_code)
response_Json = response.json()
print("Printing Post JSON data")
print(response_Json['status'])
print(response_Json['message'])
curl --location --request POST 'https://api.smsafrica.tech/api/message/send/sms' \
--header 'Content-Type: application/json' \
--header 'Authorization: secureapikeys' \
--data-raw '{
"message": "You message",
"msisdn": "2547xxxxxxxx",
"sender_id": "SMS Africa",
"callback_url": "https://callback.io/123/dlr",
"schedule": true,
"date": "2030-01-01",
"send_time": "09:30:01"
}'
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "https://api.smsafrica.tech/api/message/send/sms";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Authorization","secureapikeys");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 ) {
// Print received data from server
console.log(this.responseText.status);
console.log(this.responseText.message);
}
};
var message = {
"message": "message here",
"msisdn": "2547xxxxxxxx",
"sender_id": "SMS Africa",
"callback_url": "https://callback.io/123/dlr",
"schedule": true,
"date": "2030-01-01",
"send_time": "09:30:01",
}
// Converting JSON data to string
var data = JSON.stringify(message);
// Sending data with the request
xhr.send(data);
package main
import (
"bytes"
"fmt"
"net/http"
"io/ioutil"
"encoding/json"
)
func main() {
url := "http://api.smsafrica.tech/api/message/send/sms"
method := "POST"
// construct your message using interface
message := map[string] interface{}{
"message": "You message",
"msisdn":"2547xxxxxxxx",
"sender_id":"SMS Africa",
"callback_url": "https://callback.io/123/dlr",
"schedule": true,
"date": "2030-01-01",
"send_time": "09:30:01",
}
// convert to json
payload,err := json.Marshal(message)
if err != nil {
fmt.Println(err)
}
// make http request
client := &http.Client {}
req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
if err != nil {
fmt.Println(err)
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "secureapikeys")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
URL url = new URL ("https://api.smsafrica.tech/api/message/send/sms");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "secureapikeys");
con.setDoOutput(true);
//JSON String need to be constructed for the specific resource.
Map<String, String> map = new LinkedHashMap<>();
map.put("message","You message");
map.put("msisdn","2547xxxxxxxx");
map.put("sender_id","SMS Africa");
map.put("callback_url","https://callback.io/123/dlr");
map.put("schedule",true);
map.put("date","2030-01-01");
map.put("send_time","09:30:01");
Gson gson = new Gson();
String jsonInputString = gson.toJson(map);
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
}
<?php
$message = [
"message" => 'You message',
"msisdn" => "2547xxxxxxxx",
"sender_id" => "SMS Africa" ,
"callback_url" => "https://callback.io/123/dlr"
];
$data_string = json_encode($message);
$secureapikeys = "secureapikeys";
$httpRequest = curl_init("https://api.smsafrica.tech/api/message/send/sms");
curl_setopt($httpRequest,CURLOPT_POST,true);
curl_setopt($httpRequest,CURLOPT_POSTFIELDS,$data_string);
curl_setopt($httpRequest,CURLOPT_TIMEOUT,60);
curl_setopt($httpRequest,CURLOPT_RETURNTRANSFER,1);
curl_setopt($httpRequest,CURLOPT_HTTPHEADER,array(
"Content-Type:application/json",
"Authorization: $secureapikeys"
)
);
curl_setopt($httpRequest,CURLOPT_RETURNTRANSFER,true);
//curl_setopt($httpRequest,CURLOPT_HEADER,1);
$response = curl_exec($httpRequest);
$status = curl_getinfo($httpRequest,CURLINFO_HTTP_CODE);
curl_close($httpRequest);
echo $status;
echo $response;
The above command returns JSON structured like this on success:
{
"message": "SMS successfully queued for sending. Total recipients 1",
"status": 200,
"transaction_id": 2295
}
On failure the following is returned, refere to status codes for error types
{
"status": 428,
"message": "error message"
}
File Upload
This API allows you to upload recipients in a file
API Endpoint
FORM POST /api/message/send/uploadFile
Simple SMS Content
Simple SMS allows you to send the same SMS to many users by upload a file of file numbers. This endpoint provides an interface to upload contacts in a file.
file format
You can only upload a CSV file The first row will in the file will be treated as headers.
basic format
The first column is expected to be the phone numbers example below
| msisdn |
|---|
| 07xxxxxxx0 |
| 07xxxxxxx1 |
| 07xxxxxxx2 |
| 07xxxxxxx3 |
| 07xxxxxxx4 |
Input Form Fields
The API expects a FORM POST with the following
| Key | Required | Data Type | Default | Description |
|---|---|---|---|---|
| message | yes | String | none | message ro send |
| country_code | no | String | ke | if this are not a kenya phone numbers, supply the country code |
| sender_id | no | String | SMS Africa | your registered sender ID |
| file | yes | File | File to be uploaded | |
| campaign_name | no | String | Name of Campaign, contact group | |
| schedule | no | Boolean | false | Is this SMS to be scheduled? |
| date | no | String | none | Date to send the SMS, date format YYYY-MM-DD |
| send_time | no | String | none | Time to send the SMS |
require "uri"
require "net/http"
url = URI("https://api.smsafrica.tech/api/message/send/uploadFile")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = "secureapikeys"
form_data = [
['message', 'test SMS to {msisdn}'],
['sender_id', 'SMSAfrica'],
['campaign_name', 'test'],
['callback_url', 'https://sms-savvy.com'],
['file', File.open('/Users/user1/Downloads/template (10).csv')]
]
request.set_form form_data, 'multipart/form-data'
response = https.request(request)
puts response.read_body
import requests
url = "https://api.smsafrica.tech/api/message/send/uploadFile"
payload={'message': 'test SMS to [msisdn]',
'sender_id': 'SMSAfrica',
'campaign_name': 'test',
'callback_url': 'https://sms-savvy.com'}
files=[
('file',('template (10).csv',open('/Users/user1/Downloads/template (10).csv','rb'),'text/csv'))
]
headers = {
'Authorization': 'secureapikeys'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
curl --location --request POST 'https://api.smsafrica.tech/api/message/send/uploadFile' \
--header 'Authorization: secureapikeys=' \
--form 'message="test SMS to [msisdn]"' \
--form 'sender_id="SMSAfrica"' \
--form 'campaign_name="test"' \
--form 'callback_url="https://sms-savvy.com"' \
--form 'file=@"/Users/user1/Downloads/template (10).csv"'
var data = new FormData();
data.append("message", "test SMS to [msisdn]");
data.append("sender_id", "SMSAfrica");
data.append("campaign_name", "test");
data.append("callback_url", "https://sms-savvy.com");
data.append("file", fileInput.files[0], "template (10).csv");
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api.smsafrica.tech/api/message/send/uploadFile");
xhr.setRequestHeader("Authorization", "secureapikeys");
xhr.send(data);
package main
import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
"log"
)
func main() {
endpoint := "https://api.smsafrica.tech/api/message/send/uploadFile"
method := "POST"
csvFileToUpload := "/full/path/of/the/file.extension"
// your form fields
formFields := map[string]string{
"message": "test SMS to [msisdn]",
"sender_id": "SMSAfrica",
"campaign_name": "Bulk SMS",
"callback_url": "https://callback.io/dlr",
}
// open file for reading
file, err := os.Open(csvFileToUpload)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", filepath.Base(csvFileToUpload))
if err != nil {
fmt.Println(err)
return
}
_, err = io.Copy(part, file)
for key, val := range formFields {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
fmt.Println(err)
return
}
req, err := http.NewRequest(method, endpoint, body)
if err != nil {
fmt.Println(err)
return
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", "secureapikeys")
client := &http.Client {}
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err = ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("message","test SMS to [msisdn]")
.addFormDataPart("sender_id","SMSAfrica")
.addFormDataPart("campaign_name","test")
.addFormDataPart("callback_url","https://sms-savvy.com")
.addFormDataPart("file","template (10).csv",
RequestBody.create(MediaType.parse("application/octet-stream"),
new File("/Users/user1/Downloads/template (10).csv")))
.build();
Request request = new Request.Builder()
.url("https://api.smsafrica.tech/api/message/send/uploadFile")
.method("POST", body)
.addHeader("Authorization", "secureapikeys")
.build();
Response response = client.newCall(request).execute();
}
}
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.smsafrica.tech/api/message/send/uploadFile',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array(
'message' => 'test SMS to [msisdn]',
'sender_id' => 'SMSAfrica',
'campaign_name' => 'test',
'callback_url' => 'https://sms-savvy.com',
'file'=> new CURLFILE('/Users/user1/Downloads/template (10).csv')
),
CURLOPT_HTTPHEADER => array(
'Authorization: secureapikeys'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
The above command returns JSON structured like this on success:
{
"message": "SMS successfully queued for sending. Total recipients 10000",
"status": 200,
"transaction_id": 2295
}
On failure the following is returned, refere to status codes for error types
{
"status": 428,
"message": "error message"
}
File Upload - SMS Customization
This API allows you to upload recipients in a file and further customize SMS per recipient
API Endpoint
FORM POST /api/message/send/uploadFile
This API allows you to send custom sms to a batch of contacts in a file e.g when sending school fees balance where you want to customize sms for every parent to pick the required fee balance.
1. step 1
When creating a file in this category, the 1st column remains to be phone number, the subsequent columns will be the replacement parameters. example you want to send sms to parents you want sms to go out with student name, fee balance and adminission number. Your file will have the below format. The 1st column will be treated as headers
| msisdn | name | admission | balance |
|---|---|---|---|
| 2547xxxxxxx0 | John Doe | adm/01 | 1000 |
| 2547xxxxxxx1 | Alice Bobby | adm/02 | 1000 |
| 2547xxxxxxx2 | Ruby Rose | adm/03 | 1000 |
| 2547xxxxxxx3 | George Nim | adm/04 | 1000 |
| 2547xxxxxxx4 | Lucas Madona | adm/05 | 1000 |
You can have as many columns and rows the only limit will be file size, your file should be below 100MB
2. step 2
Compose your sms to include column header name wrapped in square brackets [ and ] example to use name in SMS we use [name] back to our example above our sms will look like the following
Dear parent your student [name] has a fee balance of [balance]. Please pay your fees through paybill 89544 account [admission] thank you
The above will be your sms contents, the system will go through the file row by row replacing SMS parameters with values in the file in that column. Each recipient will receive a customized SMS
URL Parameters
This endpoint accepts form data with the below fields
| Key | Required | Data Type | Default | Description |
|---|---|---|---|---|
| message | yes | String | none | message to send |
| country_code | no | String | ke | if this are not a kenya phone numbers, supply the country code |
| sender_id | no | String | SMS Africa | your registered sender ID |
| file | yes | File | File to be uploaded | |
| campaign_name | no | String | Name of Campaign, contact group | |
| schedule | no | Boolean | false | Is this SMS to be scheduled? |
| date | no | String | none | Date to send the SMS, date format YYYY-MM-DD |
| send_time | no | String | none | Time to send the SMS |
require "uri"
require "net/http"
url = URI("https://api.smsafrica.tech/api/message/send/uploadFile")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = "secureapikeys"
form_data = [
['message', 'test SMS to {msisdn}'],
['sender_id', 'SMSAfrica'],
['campaign_name', 'test'],
['callback_url', 'https://sms-savvy.com'],
['file', File.open('/Users/user1/Downloads/template (10).csv')]
]
request.set_form form_data, 'multipart/form-data'
response = https.request(request)
puts response.read_body
import requests
url = "https://api.smsafrica.tech/api/message/send/uploadFile"
payload={'message': 'test SMS to [msisdn]',
'sender_id': 'SMSAfrica',
'campaign_name': 'test',
'callback_url': 'https://sms-savvy.com'}
files=[
('file',('template (10).csv',open('/Users/user1/Downloads/template (10).csv','rb'),'text/csv'))
]
headers = {
'Authorization': 'secureapikeys'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
curl --location --request POST 'https://api.smsafrica.tech/api/message/send/uploadFile' \
--header 'Authorization: secureapikeys=' \
--form 'message="test SMS to [msisdn]"' \
--form 'sender_id="SMSAfrica"' \
--form 'campaign_name="test"' \
--form 'callback_url="https://sms-savvy.com"' \
--form 'file=@"/Users/user1/Downloads/template (10).csv"'
var data = new FormData();
data.append("message", "test SMS to [msisdn]");
data.append("sender_id", "SMSAfrica");
data.append("campaign_name", "test");
data.append("callback_url", "https://sms-savvy.com");
data.append("file", fileInput.files[0], "template (10).csv");
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api.smsafrica.tech/api/message/send/uploadFile");
xhr.setRequestHeader("Authorization", "secureapikeys");
xhr.send(data);
package main
import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
"log"
)
func main() {
endpoint := "https://api.smsafrica.tech/api/message/send/uploadFile"
method := "POST"
csvFileToUpload := "/full/path/of/the/file.extension"
// your form fields
formFields := map[string]string{
"message": "test SMS to [msisdn]",
"sender_id": "SMSAfrica",
"campaign_name": "Bulk SMS",
"callback_url": "https://callback.io/dlr",
}
// open file for reading
file, err := os.Open(csvFileToUpload)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", filepath.Base(csvFileToUpload))
if err != nil {
fmt.Println(err)
return
}
_, err = io.Copy(part, file)
for key, val := range formFields {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
fmt.Println(err)
return
}
req, err := http.NewRequest(method, endpoint, body)
if err != nil {
fmt.Println(err)
return
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", "secureapikeys")
client := &http.Client {}
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err = ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("message","test SMS to [msisdn]")
.addFormDataPart("sender_id","SMSAfrica")
.addFormDataPart("campaign_name","test")
.addFormDataPart("callback_url","https://sms-savvy.com")
.addFormDataPart("file","template (10).csv",
RequestBody.create(MediaType.parse("application/octet-stream"),
new File("/Users/user1/Downloads/template (10).csv")))
.build();
Request request = new Request.Builder()
.url("https://api.smsafrica.tech/api/message/send/uploadFile")
.method("POST", body)
.addHeader("Authorization", "secureapikeys")
.build();
Response response = client.newCall(request).execute();
}
}
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.smsafrica.tech/api/message/send/uploadFile',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array(
'message' => 'test SMS to [msisdn]',
'sender_id' => 'SMSAfrica',
'campaign_name' => 'test',
'callback_url' => 'https://sms-savvy.com',
'file'=> new CURLFILE('/Users/user1/Downloads/template (10).csv')
),
CURLOPT_HTTPHEADER => array(
'Authorization: secureapikeys'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
The above command returns JSON structured like this on success:
{
"message": "SMS successfully queued for sending. Total recipients 10000",
"status": 200,
"transaction_id": 2295
}
On failure the following is returned, refere to status codes for error types
{
"status": 428,
"message": "error message"
}
SMS Delivery Report
When you send a Bulk SMS and add delivery callback_url, SMS Africa will send you SMS status when its done processing, SMS is considered done processing when it either fails or is successfully delivered to the recipient.
DLR fields
| Name | Data Type | Description |
|---|---|---|
| msisdn | string | Phone number |
| status | Integer | see DLR Status section |
| status_description | String | Description of the status field |
| country | String | Recipient Country |
| network | String | Recipient Telcom Network |
| transaction_id | String | Message Transaction ID |
Sample DLR JSON
{
"msisdn": "254710XXXXXX",
"status": 3,
"country": "ke",
"network": "Safaricom",
"status_description": "Delivered To Teminal",
"transaction_id": 2295
}
Payment APIs
Receiving A Payment
This APIs enables you to receive payment notification whenever a client makes your payment to your SMSAfrica wallet using Safaricom MPESA. You need to register payment notification URL, to do this send your URL and SMS Platform username to jkibii@infinitytechafrica.com. Once this is setup you are ready to receive payment notification.
Customer Initiated Payment
For your customers to make payment using Safaricom MPESA, they follow the below steps Step 1 - Go to MPESA Menu Step 2 - Select Lipa na MPESA Step 3 - Select PayBill Step 4 - Enter PayBill Number as 491919 Step 5 - Enter Account Number (This should be your assigned account number) Step 6 = Enter Amount Step 7 - Enter MPESA PIN Done
After the payment has been confirmed the system will send payment notification to the registered URL. This will come as POST request with JSON data fields
| Name | Data Type | Description |
|---|---|---|
| short_code | Integer | PayBill number used to make payment |
| msisdn | Integer | Customer Phone number used to make payment |
| amount | Integer | Description of the status field |
| reference | String | Payment reference number - unique for every payment |
| account | String | Payment account |
| first_name | String | Customer first name |
| middle_name | String | Customer middle name |
| last_name | String | Customer last name |
| transaction_id | String | Payment account |
Sample Payment JSON Data
{
"short_code": 491919,
"msisdn": 25470000001,
"amount": 1000,
"reference": "WERHIOQERT56",
"account": "ORDER1",
"first_name": "JOHN",
"middle_name": "DOE",
"last_name": "PETER",
"transaction_id": "ORDER1"
}
Merchant Initiated Payment - (STK Push)
You can initiate payment request from the API, the request will be send to the customers phone number and he will be prompted to complete payment. Once the Payment is successfully completed, you will receive payment notification via the callback URL
API Endpoint
POST /api/payment/request
JSON Input Parameters
The API expects a JSON payload with the following
| Key | Required | Data Type | Default | Description |
|---|---|---|---|---|
| amount | yes | Integer | none | Amount to request |
| msisdn | yes | Integer | none | Customers phone number |
| short_code | no | INteger | 491919 | Your assigned paybill number |
| transaction_id | no | String | none | Your transaction identifier e.g order number, this field will be send back on successful payment completion |
| callback_url | no | String | none | If you supplu callback URL, when the payment processing fails, the system will send the failure details on this callback, after successful payment, payment notification is send to the registered URL only |
This endpoint expects JSON in the below format:
{
"amount": 1000,
"msisdn": 254700000000,
"short_code": 491919,
"transaction_id": "order1",
"callback_url": "https://callback.io/123/dlr"
}
Sending money to your customer
You can send money directly to your customers mobile number, this works for ONLY Safaricom phone numbers. When you send money, the money is deducted from your SMSAfrica Wallet
API Endpoint
POST /api/payment/send
JSON Input Parameters
The API expects a JSON payload with the following
| Key | Required | Data Type | Default | Description |
|---|---|---|---|---|
| amount | yes | Integer | none | Amount to request |
| msisdn | yes | Integer | none | Customers phone number |
| transaction_id | no | String | none | Your transaction identifier e.g order number, this field will be send back on successful payment completion |
| callback_url | no | String | none | If you supply callback URL you get payment processing details |
This endpoint expects JSON in the below format:
{
"amount": 1000,
"msisdn": 254700000000,
"transaction_id": "request1",
"callback_url": "https://callback.io/123/dlr"
}
Outgoing payment notification payload
You will receive the following payment payload on the callback supplied with your payload
| Key | Required | Data Type | Description |
|---|---|---|---|
| amount | yes | Integer | Amount you send |
| status_code | Yes | Integer | Customers phone number |
| status_description | yes | String | Description of the status code |
| reference | yes | Integer | Customers phone number |
| customer_name | yes | Integer | Customers phone number |
| transaction_id | no | String | The transaction_id you supplied during payment request |
| callback_url | no | String | If you supply callback URL you get payment processing details |
This endpoint expects JSON in the below format:
{
"status_code": 3000,
"status_description": "",
"reference": "",
"customer_name": "",
"msisdn": 254700000000,
"transaction_id": "request1",
"callback_url": "https://callback.io/123/dlr"
}
Errors
The Titan SMS API uses the following error codes:
| Error Code | Meaning |
|---|---|
| 400 | Bad Request -- Your request is invalid. |
| 401 | Unauthorized -- Your API key is wrong. |
| 403 | Forbidden -- The data requested is hidden for administrators only. |
| 404 | Not Found -- The specified data could not be found. |
| 405 | Method Not Allowed -- You tried to access a data with an invalid method. |
| 406 | Not Acceptable -- You requested a format that isn't json. |
| 418 | Invalid Parameters supplied. |
| 421 | Invalid Parameters supplied. |
| 422 | Invalid Parameters supplied. |
| 428 | Invalid API Key or session expired. |
| 429 | Too Many Requests |
| 500 | Internal Server Error -- We had a problem with our server. Try again later. |
| 503 | Service Unavailable -- We're temporarily offline for maintenance. Please try again later. |
SMS Delivery Status
The Titan SMS API will the following DLR status:
| Status | Meaning |
|---|---|
| 0 | Failed, SMS was not send to Telco. This occurs due to billing issues |
| 1 | Failed, SMS was not send to Telco. This |
| 2 | Pending. SMS was send to Telco but Telco did not send back delivery status |
| 3 | Delivered. SMS Delivered to Phone |
Payment Status Codes
| Status Code | Description |
|---|---|
| 3011 | Payment is pending |
| 3012 | Payment processed successfully |
| 3010 | Payment failed, no further processing will be done |