SlideShare a Scribd company logo
Tawi Airtime Gateway
Developer Guide
A Product of Tawi Commercial Services Ltd
2015
www.tawi.mobi
http://airtimegw.tawi.mobi
info@tawi.mobi
July 2015
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 1
INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH TAWI COMMERCIAL
SERVICES’ PRODUCTS. NO INTELLECTUAL PROPERTY RIGHTS, LICENSE, EXPRESS OR
IMPLIED, BY ESTOPPEL OR OTHERWISE, IS GRANTED BY THIS DOCUMENT, EXCEPT AS
PROVIDED IN TAWI COMMERCIAL SERVICES’ TERMS AND CONDITIONS OF SALE FOR SUCH
PRODUCTS. TAWI COMMERCIAL SERVICES ASSUMES NO LIABILITY WHATSOEVER, AND TAWI
COMMERCIAL SERVICES DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO
SALE AND/OR USE OF TAWI COMMERCIAL SERVICES’ PRODUCTS INCLUDING LIABILITY OR
WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR
INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.
The Programs (which include both the software and documentation) contain proprietary information; they
are provided under a license agreement containing restrictions on use and disclosure and are also protected
by copyright, patent, and other intellectual and industrial property laws. Reverse engineering, disassembly,
or decompilation of the Programs, except to the extent required to obtain interoperability with other
independently created software or as specified by law, is prohibited.
The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently
dangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup,
redundancy and other measures to ensure the safe use of such applications if the Programs are used for
such purposes, and we disclaim liability for any damages caused by such use of the Programs.
Tawi Commercial Services may make changes to specifications and product descriptions at any time,
without notice.
No part of this publication may be reproduced, transmitted, transcribed, stored in a retrieval system, or
translated into any language or computer language, in any form or by any means, electronic mechanical,
magnetic, optical, chemical, manual, or otherwise, without the prior written permission of Tawi
Commercial Services Ltd.
Copyright © 2015 by Tawi Commercial Services Ltd. All rights reserved.
All other trademarks are property of their respective owners.
Tawi Commercial Services Ltd.
1st Floor, Corner View Centre
Naivasha Road, Nairobi CBD
P.O. Box 20222 – 00100
Nairobi, Kenya
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 2
Table of Contents
1. Document Information 3
1.1. Document History 3
2. Introduction 4
3. API Overview 5
4. API Commands 7
4.1. Send Airtime 7
4.2. Query Top-up Status 13
4.3. Query Balance 14
5. Message Status Codes 15
6. Appendices 18
A. Glossary 3
B. Sample Code 19
B1. Java 19
B2. PHP 25
C. References 27
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 3
1. Document Information
1.1. Document History
Release Date Author Comments
Revision 1 Jul 2015 Michael Wakahe 1st
Working Version
1.2. Document Conventions
N/A
1.3. Related Documents
None.
1.4. Glossary
API …………………………………………… Application Programmer Interface
CCK ………………………………………….. Communications Commission of Kenya
HTTP ………………………………………... Hyper Text Transfer Protocol
J2EE ……................................................... Java 2 Enterprise Edition
MO …………………………………………... Mobile Originated SMS
MSISDN …………………………………… A number uniquely identifying a subscription
in a GSM mobile network
MT …………………………………………… Mobile Terminated SMS
PRSP ………………………………………… Premium Rate Services Provider
SLA …………………………………………. Service Level Agreement
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 4
2. Introduction
Tawi Commercial Services Limited is a Kenyan based software development company
specializing in mobile technologies. These include short codes, bulk SMS, USSD, mobile
applications, and airtime.
Tawi Commercial Services is a Premium Rate Service Provider (PRSP) with Safaricom1
Kenya and Airtel2 Kenya. This implies that she offers SMS and USSD services through
these two network operators. The Tawi Airtime Gateway is software that allows for
electronic topups through a web based interface (API). This document serves to describe
to software integrators the various commands used to interact with the gateway.
Figure 2.1: Tawi Airtime Gateway Overview
1
http://www.safaricom.co.ke
2
http://africa.airtel.com/kenya
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 5
3. Portal and API Design Overview
The Tawi Airtime Gateway is a product that facilitates for topping up of airtime on both
Safaricom and Airtel. Connectivity is done via an HTTP API. This document details how
one can set up to top up airtime through the gateway API. The gateway is accessible
through the URL https://airtimegw.tawi.mobi.
Internally, the gateway has many features to guarantee that it works correctly, including
a continuous best effort approach to deliver instructions to the operator airtime systems
and security to prevent unwarranted topping up of airtime.
The communication between client and server is synchronous. There are a variety of
conditions to be determined before a topup transaction is completed. For example, the
recipient must be a valid mobile number. The server attempts to finish all of these within
a socket connection.
Communication between client and server always utilizes HTTPs. This is regardless of
whether the client or the server initiated the communication. HTTPs is widely adopted
for providing a secure tunnel for client-server communication over the Internet.
The web service API utilizes a RESTful approach. Specifically JSON is the means for
data interchange between client and server.
Session Ids are generated by the server in order for the client to transact. A Session Id is
a randomly generated text that is presented by the server in order for a client to execute
or query. It expires after a window period.
The Session Ids kept securely on the Tawi end and are never repeated. We advise the
client to keep them securely on his or her end to avoid a replay attack while the session is
still valid. One means can be to cache them in memory instead of writing them to
RDBMS or file where they are human readable.
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 6
A unique Transaction Id is generated for each request. Transactions into either success or
failure. Failure can be due to various reasons including a non-existent phone number and
a phone number in an unsupported network.
The web portal allows for integrators to view their account activity. Details include
account balance and topup activity. For security reasons, transaction records can neither
be created nor altered from the web portal. A developer must already have an account
with the Tawi Airtime Gateway before (s)he can attempt to send airtime through the
system.
Presently the default operator prefixes are as follows:
Safaricom prefixes: 070, 071 and 072;
Airtel prefixes: 073, 0785, 0788 and 0789.
A Kenyan GSM phone number specified without the country code is always 10 digits long.
As an example, the number 0701234567 has a valid length and by default would belong
to the Safaricom network.
Number portability exists in Kenya. This implies that any MSISDN may be associated
with any network operator. The other network operator in Kenya is Orange3. There is
currently no means to determine beforehand which operator a number belongs to.
Airtime top up can only terminate in Kenya.
3
http://www.orange.co.ke
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 7
4. API Commands
The following section details the commands used to interact with the system.
There is always a response for every command sent to the system. This is regardless of
whether or not the command was successful. In this manner, you can determine whether
or not the query has been received by the gateway.
Send Airtime, Query Client Reference Number, Query Balance
4.1. Get Session Id
A Session Id is a text that is used for identification. All other client requests must be
accompanied by a Session Id in order for the server to successfully process them. It is
temporal in nature, that is it expires after a predetermined amount of time. For
subsequent client requests, a new one must be requested for.
The Session Id is always unique. For security reasons it is recommended that the Client
application safeguards the Session Ids it receives as they can be used to carry out
legitimate transactions.
In order to receive a Session Id, the client application requests the server through the
instruction described in this section. Upon successful authentication, the Session Id is
sent to a preconfigured URL. This URL can only be altered with the assistance of the
server system administrator. The following sequence diagrams illustrate the process of
acquiring a Session Id.
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 8
Figure 4.1: Session Id Sequence Flow Diagram
Web Service Endpoint: https://airtimegw.tawi.mobi/sessionid
Client Request Parameters
Parameter Value Compulsory Description
api_username a username Yes A valid username that is
permitted to remit money. Should
be URL encoded using the UTF-8
scheme.
api_password a password Yes A valid password that is
permitted to remit money. Should
be URL encoded using the UTF-8
scheme.
Example JSON Request Body: {“api_username”:“demo”, “api_password”:“password” }
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 9
Server Response Parameters
The following are the parameters sent to the Client request:
Parameter Value Compulsory Description
command_status a status Yes A status indicating whether the
server accepted the request or
not.
For further details on various
status codes, see Chapter 5:
Status Codes.
Example JSON Response Body: {“command_status”:“Ok”}
If the Client successfully requests for a Session Id, the Server sends the following
parameters to the predetermined Client URL. The method used is HTTPS POST.
Parameter Value Compulsory Description
api_username a username Yes A valid username that is
permitted to send airtime. Will be
URL encoded using the UTF-8
scheme.
session_id session id text Yes Randomly generated text that
will be used by the Client for
identification
Example JSON POST Body: {“api_username”:“demo”, “session_id”:“1234567”}
The following are extra notes concerning a Session Id:
 A Client application can only have one valid Session Id at a time. If a Client initiates a
request for a new Session Id before a previously held one expires, then the older one
will be expired.
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 10
4.2. Send Airtime
This is the command to send airtime to single or multiple destinations through the
gateway. The following sequence diagram illustrates the process of sending airtime.
Figure 4.2: Send Airtime Sequence Flow Diagram
Web Service Endpoint: https://airtimegw.tawi.mobi/topup
Client Request Parameters
Name Value Compulsory Description
api_username a username Yes A valid username that is
permitted to perform topup.
Should be URL encoded using
the UTF-8 scheme.
session_id session id text Yes Randomly generated text that is
used by the Client for
identification.
msisdn A phone number Yes This is the phone number(s) that
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 11
is to receive airtime. No leading
zero to the number and no
special characters such as "+",
spaces or hyphens must be used.
For example, a number in the
Kenya being 0720123456 should
be changed to 254720123456.
Multiple destinations are not
supported in this version.
amount An integral
number value
Yes This is the amount in the local
currency that is to be sent to the
target mobile numbers. The
value should be in a whole
number.
reference_number A reference
number
Yes A reference number generated by
the client application. This can
be used to identify a topup
transaction from the client side.
Note that the client application
should strive to generate a
unique reference number for
each transaction.
network An MNO
mnemonic for
example
“Safaricom_KE”
Yes To indicate the network to direct
the airtime to. The network
should be indicated because
number portability allows
numbers to belong to any
network.
MNO mnemonics are listed in
Appendix A: Network Operator
Coverage.
Note that the networks available
are also dependent on your
account setup.
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 12
Example JSON Request Body (One Recipient):
{“api_username”:“demo”, “session_id”:“31245”, “msisdn”:“254123456”, “amount”:“100”,
“reference_number”:“abc123”, “network”:“Safaricom_KE”}
Server Response Parameters
The following are the parameters sent to the Client request:
Parameter Value Compulsory Description
command_status a status Yes A status indicating whether the
server accepted the request or
not.
For further details on various
status codes, see Chapter 5:
Status Codes.
transaction_id text No A Transaction Id is a unique
identifier for a transaction. It is
generated by the server and can
be referenced in future.
topup_status a status No The status of the attempt to top
up the phone number.
For further details on various
status codes, see Chapter 5:
Status Codes.
datetime a date and time No A date-time of the server when it
received the instruction. It is in
the form:
YYYY-MM-DDThh:mm:ss±hh:mm
For example:
2014-06-11T13:54:27+03:00
This follows the ISO 86014
recommendations.
Example JSON Response Body (single recipient):
{“api_username”:“demo”, “transaction_id”:“47123e90-f1a6”, “command_status”:“Ok”,
“topup_status”:”SUCCESS”, “datetime”:“2014-06-11T13:54:27+03:00”}
4
http://en.wikipedia.org/wiki/ISO_8601
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 13
4.3. Query Top-up Status
The following are the parameters used to query the most recent status of a top-up
attempt.
Web Service Endpoint http://airtimegw.tawi.mobi/status
Client Request Parameters
Name Value Compulsory Description
api_username a username Yes A valid username that is permitted to
perform topup. Should be URL
encoded using the UTF-8 scheme.
session_id session id text Yes Randomly generated text that is used
by the Client for identification.
transactionId
or
clientRefNumber
a unique
alphanumeric
string
Yes A valid transaction Id that was
provided by the server in a previous
top-up attempt.
Alternatively the reference_number
that was given in the Send Airtime
command can be used.
iii. Example Status Query
http://airtimegw.tawi.mobi/status?username=tawi&password=info&transactionId=47b85
9b7-4e3e-4363-83d9-77c66c120bd6
iv. Response Parameters
The format of a valid Query Status command is as follows: status code:timestamp
The time stamp is in the ISO 8601 format, for example: 2013-11-18T10:38:28.385+03:00
The format of an invalid Query Status command is as follows: INVALID_PARAMETERS
This also includes providing an invalid transaction Id. For further details on various
status codes, see Chapter 5: Message Status Codes.
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 14
4.4. Query Balance
This API functionality allows for one to query the balance of airtime. The balance is
returned in Kenya Shillings.
i. Target URL: http://aritimegw.tawi.mobi/balance
ii. Query Parameters
Name Value Compulsory Description
username a username or
email
Yes A valid username or email that is
permitted to top up airtime.
Should be URL encoded using the
UTF-8 scheme.
password a password Yes A valid password corresponding to
the username above. Should be
URL encoded using the UTF-8
scheme.
network “safaricom”, “airtel”
or “orange”
Yes The mobile network that the user
wishes to query the balance.
iii. Example Query Balance
This is an example of a Query Balance.
http://airtimegw.tawi.mobi/balance?username=tawi&password=info&network=orange
iv. Response Parameters
The format of a valid Query Balance command is as follows: amount
The format of an invalid Query Balance command is as follows: status code
For further details on various status codes, see Chapter 5: Message Status Codes.
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 15
v. Example Responses
Example of a valid Query Balance command response: 5000
Example of an invalid Query Balance command response: UNKNOWN_USERNAME
5. Status Codes
A status code is generated in response to an attempt to send airtime, query balance or
check the status of a transaction. Below is a list of them with their description.
Status codes are divided into two categories:
 Command Status Codes: these are to give feedback on the Client conformity to the
API command structure;
 Airtime Transfer Status Codes: these are to give information on the state of
remittance to a mobile subscriber.
i. Command Status Codes
These have the keyword “command_status”. Below is a listing with explanations:
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 16
Value Interpretation
OK The server has accepted the command for further processing.
INVALID_SESSIONID The Session Id provided has either expired or was never issued.
ii. Airtime Transfer Status Codes
These have the keyword “remit_status”. Below is a listing with explanations:
Value Interpretation
SUCCESS The airtime has successfully been transferred.
INSUFFICIENT_FUNDS There are insufficient funds in your account.
STATUS_NOT_PERMITTED Your current account status is not permitted to remit
airtime. For example, the account may have been
Suspended.
LOW_AMOUNT The topup amount specified is below the network
minimum allowed amount in 1 transaction. Adjust by
sending a higher amount.
HIGH_AMOUNT The topup amount specified exceeds the network
maximum allowed amount in 1 transaction. Adjust by
sending lower amounts for multiple instances.
UNKNOWN_ERROR The airtime has not been successfully transferred due
to an unknown error.
A status code is generated in response to an attempt to send airtime, query balance or
check the status of a transaction. Below is a list of them with their description.
Value Description
ACCEPTED_FOR_DELIVERY The top-up request has been accepted by the gateway
for delivery.
SUBMITTED_TO_OPERATOR The message has been submitted to the operator
airtime server.
TOPUP_SUCESS The top-up attempt is successful.
TOPUP_FAILURE The top-up attempt is not successful.
UNKNOWN_USERNAME The username or email used to authenticate is not
registered with the gateway.
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 17
WRONG_PASSWORD The password supplied does not match the username.
ACCOUNT_SUSPENDED The account from which the top-up attempt has been
made is not active, it may be in a suspended or deleted
state.
INVALID_PARAMETERS Not enough or invalid parameters have been provided
when submitting a request to send a message. This
also includes invalid amounts for top-up.
INSUFFICIENT_FUNDS The user has exhausted the airtime allowed for top-
up.
SERVER_ERROR The gateway has experienced an internal error.
Value Description
ACCEPTED_FOR_DELIVERY The top-up request has been accepted by the gateway
for delivery.
SUBMITTED_TO_OPERATOR The message has been submitted to the operator
airtime server.
TOPUP_SUCESS The top-up attempt is successful.
TOPUP_FAILURE The top-up attempt is not successful.
UNKNOWN_USERNAME The username or email used to authenticate is not
registered with the gateway.
WRONG_PASSWORD The password supplied does not match the username.
ACCOUNT_SUSPENDED The account from which the top-up attempt has been
made is not active, it may be in a suspended or deleted
state.
INVALID_PARAMETERS Not enough or invalid parameters have been provided
when submitting a request to send a message. This
also includes invalid amounts for top-up.
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 18
INSUFFICIENT_FUNDS The user has exhausted the airtime allowed for top-
up.
SERVER_ERROR The gateway has experienced an internal error.
6. Appendices
A. Network Operator Coverage
Country MNO / SMS Aggregator Network Mnemonic
Kenya Safaricom Safaricom_KE
Kenya Airtel Kenya Airtel_KE
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 19
B. Sample Code
Below are examples of sending and receiving messages to the gateway.
B1. Java
1. Send SMS
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.MalformedURLException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* This Java program is a client that sends requests to the Tawi SMS Gateway
* HTTP API.
* <p>
* This has been tested on JDK 1.7.
* <p>
* Copyright (c) Tawi Commercial Services Ltd., May 2012
*
*/
public class SMSSender {
/**
* @param args
*/
public static void main(String[ ] args) {
String apiUrl = "http://sms.tawi.mobi/sendsms";
try {
System.out.println("Response for a sendsms request: " +
getResponse(apiUrl + "?" +
"username=" + URLEncoder.encode("michael@hotmail.com", "UTF-8") +
"&password=" + URLEncoder.encode("mypassword", "UTF-8") +
"&account=live" +
"&source=1987" +
"&destination=254728123456" +
"&message=" + URLEncoder.encode("Hello Test SMS!", "UTF-8") +
"&network=safaricom"));
} catch(UnsupportedEncodingException e) {
System.err.println("UnsupportedEncodingException while trying to send SMS.");
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 20
e.printStackTrace( );
}
}
/**
*
* @param urlStr
* @return String
*/
private static String getResponse(String urlStr) {
URLConnection conn;
URL url;
BufferedReader reader;
String response = "";
try {
url = new URL(urlStr);
conn = url.openConnection( );
conn.setDoInput(true);
conn.setDoOutput(true);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = reader.readLine();
reader.close( );
} catch(MalformedURLException e) {
System.err.println("MalformedURLException exception");
e.printStackTrace( );
} catch(IOException e) {
System.err.println("IOException exception");
e.printStackTrace( );
}
return response;
}
}
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 21
2. Receive SMS
a. Receive without using Java Application Server
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* This Java program is a socket server that receives messages sent from the SMS Gateway
* callback mechanism.
* <p>
* This has been tested on JDK 1.7.
* <p>
* Copyright (c) Tawi Commercial Services Ltd., June 2012
*
*/
public class ServerSocketListener {
final static int SERVERSOCKET_PORT = 7777;
/**
* @param args
*/
public static void main(String[ ] args) {
System.out.println("Have started socket listener");
ServerSocket serverSocket;
Socket socket = null;
InputStream is = null;
BufferedInputStream bufferedInputStream = null;
byte[ ] buffer = new byte[1024];
try {
serverSocket = new ServerSocket(SERVERSOCKET_PORT);
while (true) {
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 22
socket = serverSocket.accept( );
System.out.println("Have received text");
is = socket.getInputStream( );
bufferedInputStream = new BufferedInputStream(is);
int bytesRead = 0;
// Keep reading till we reach the end of the stream.
// When the end of the stream has been reached, -1 is returned
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
// Construct a String from the bytes read
String received = new String(buffer, 0, bytesRead);
System.out.print("This is the string received: " + received);
}
}
} catch (IOException ex) {
System.err.println("IOException while listening on server socket.");
ex.printStackTrace( );
} finally {
// Close the stream and socket
try {
if (bufferedInputStream != null)
bufferedInputStream.close( );
if (socket != null) socket.close( );
} catch (IOException ex) {
ex.printStackTrace( );
}
}
}
}
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 23
b. Receive using Java Application Server (J2EE)
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This Java program is a servlet that receives messages sent from the SMS Gateway
* callback mechanism.
* <p>
* This has been tested on JDK 1.7. and Oracle Glassfish 3.1.
* <p>
* Copyright (c) Tawi Commercial Services Ltd., June 2012
*
*/
public class CallbackListener2 extends HttpServlet {
/**
*
* @param config
* @throws ServletException
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
/**
*
* @param servletRequest
* @param servletResponse
* @throws ServletException, IOException
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Have received callback.");
String callbackType = request.getParameter("callbackType");
if(callbackType.equals("incomingSms")) {
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 24
System.out.println("source is: " + request.getParameter("source"));
System.out.println("destination is: " + request.getParameter("destination"));
System.out.println("message is: " + request.getParameter("message"));
System.out.println("messageId is: " + request.getParameter("messageId"));
System.out.println("network is: " + request.getParameter("network"));
}
}
/**
*
* @param servletRequest
* @param servletResponse
* @throws ServletException, IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 25
B2. PHP
1. Send SMS
<?php
/**
* This PHP script is a client that sends requests to the Tawi SMS
* Gateway HTTP API.
*
* This has been tested on Apache2 with PHP5 and cURL library installed.
*
* Copyright (c) Tawi Commercial Services Ltd., May 2012
*/
// Open connection
$ch = curl_init( );
// Set the URL and POST key-value pairs.
curl_setopt($ch, CURLOPT_URL, "http://sms.tawi.mobi/sendsms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'username' => 'michael@hotmail.com',
'password' => 'mypassword',
'account' => 'live',
'source' => '2024',
'destination' => '254731234567',
'message' => 'Hello Test SMS!',
'network' => 'airtelkenya'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Execute POST. The variable $result will contain the response of the SMS Gateway.
$result = curl_exec($ch);
// Be sure to close your connections.
curl_close($ch);
echo ($result);
?>
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 26
2. Receive SMS
<?php
/**
* This is a PHP program that can receive callback data from the Tawi SMS Gateway
* when the gateway triggers the callback mechanism.
*
* Copyright (c) Tawi Commercial Services Ltd., June 2012
*
*/
?>
<?php
$myFile = "/tmp/callback.txt";
extract($_REQUEST);
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "callbackType: $callbackTypensource: $sourcendestination:
$destinationnmessage: $message nmessageId: $messageIdnnetwork: $network";
fwrite($fh, $stringData);
fclose($fh);
?>
Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 27
C. References
1. Safaricom Kenya
2. Airtel Kenya
3. Communications Commission of Kenya
Tawi Airtime Gateway Developer Guide

More Related Content

PDF
Tawi SMS Gateway Developer Guide
PPTX
Is authorization always needed for sms messages in ringcentral-api
PPTX
Codestrong 2012 breakout session at&t api platform and trends
PDF
TeleCloudDNA Overview
PDF
Collaboration between developers and operators via open api platform
PDF
IETF meeting - SIP OAuth use cases
ODP
Joomla virtuemart otp verification system
PPTX
JATIN RELAN (11BEC0532) TRAINING PPT
Tawi SMS Gateway Developer Guide
Is authorization always needed for sms messages in ringcentral-api
Codestrong 2012 breakout session at&t api platform and trends
TeleCloudDNA Overview
Collaboration between developers and operators via open api platform
IETF meeting - SIP OAuth use cases
Joomla virtuemart otp verification system
JATIN RELAN (11BEC0532) TRAINING PPT

What's hot (20)

PPTX
Long code service by cloudshope technologies
PPTX
Comparative study between e pay company
PPTX
Aria Telecom Profile
PPTX
Your Top Messaging Questions Answered
PPT
Sms country profile 1
PPTX
Password Replacement Technology : Removing Limitations of Current Passwords
PPTX
Accepting Late payments By Phone
PDF
Esendex Solutions
PPT
Company Profile For Per
PPTX
Guidelines for using Ericsson's exposed charging APIs
PDF
Shufti Pro| Digital Identity Verification Solution
PDF
Success Stories - Transportation Series
PPS
Swift Mail Communications Ltd. Franchisee Opportunity
PPSX
Smart Solutions Profile
PDF
Introducing safexpay smart NBFC solution
PDF
InReceipts Plug N Play Client & REST APIs for billing softwares v1.0
PDF
Telebu talk 7pager (2)
PDF
WhatsApp Business Solution Compared
PPTX
Parth for ip pbx- office communication
PDF
What Is SMS Gateway
Long code service by cloudshope technologies
Comparative study between e pay company
Aria Telecom Profile
Your Top Messaging Questions Answered
Sms country profile 1
Password Replacement Technology : Removing Limitations of Current Passwords
Accepting Late payments By Phone
Esendex Solutions
Company Profile For Per
Guidelines for using Ericsson's exposed charging APIs
Shufti Pro| Digital Identity Verification Solution
Success Stories - Transportation Series
Swift Mail Communications Ltd. Franchisee Opportunity
Smart Solutions Profile
Introducing safexpay smart NBFC solution
InReceipts Plug N Play Client & REST APIs for billing softwares v1.0
Telebu talk 7pager (2)
WhatsApp Business Solution Compared
Parth for ip pbx- office communication
What Is SMS Gateway
Ad

Viewers also liked (14)

PPTX
מסע לאתיופיה - צביה שמע
PDF
Imani Poster Final
DOCX
Spk mc prsnt 2
PDF
ымвк5р
PDF
KingNeed Q6 Mini Magnet Voice Recorder
PDF
La didattica della neoscrittura
PDF
Tawi SMS Application Form - SMS Short Code
PDF
Tawi SMS Application Form - Sender Id
PPTX
Ecology PowerPoint Review Game, Quiz, Symbiosis, Plants and Animals, Exotic S...
PDF
іфміу
PDF
Top 10 discussion starters for children
PPTX
Konsep profesi keguruan
מסע לאתיופיה - צביה שמע
Imani Poster Final
Spk mc prsnt 2
ымвк5р
KingNeed Q6 Mini Magnet Voice Recorder
La didattica della neoscrittura
Tawi SMS Application Form - SMS Short Code
Tawi SMS Application Form - Sender Id
Ecology PowerPoint Review Game, Quiz, Symbiosis, Plants and Animals, Exotic S...
іфміу
Top 10 discussion starters for children
Konsep profesi keguruan
Ad

Similar to Tawi Airtime Gateway Developer Guide (20)

PDF
Lessons Learned From Four Years of API Management Implementation Success at Unum
PPTX
Building an API Monetization Stack
PPTX
How to monitor Network Traffic
PPTX
TechM Ritter Solution Case Study - V1.5
PDF
Introduction to WebRTC on the Force.com Platform
PPTX
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
PDF
Creating an Omnichannel Experience for Your Customers
PDF
Authentication with OAuth and Connected Apps
PPTX
What is NFV and Why is it Significant to the Networking Industry?
PDF
Case Study: Rogers Communications Integrates CA API Management and CA Service...
PDF
APIdays Paris 2019 - What are protected and secured by security requirements ...
PDF
APIdays Paris 2019 : Financial-grade API (FAPI) Security Profile
PDF
Aavenir webinar - making legal contracts work for everyone - 28 april 2020
PPTX
How to manage Broadband Traffic Intelligently?
PPTX
Get RTO Mobile Number Update API at best Price.pptx
PPT
Enterprise API deployment best practice
PDF
BabbleSMS Product Guide
PPTX
apidays Helsinki & North 2025 - Vero APIs - Experiences of API development in...
PPTX
Affordable RTO Detail API Service Provider Company.pptx
PDF
Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...
Lessons Learned From Four Years of API Management Implementation Success at Unum
Building an API Monetization Stack
How to monitor Network Traffic
TechM Ritter Solution Case Study - V1.5
Introduction to WebRTC on the Force.com Platform
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Creating an Omnichannel Experience for Your Customers
Authentication with OAuth and Connected Apps
What is NFV and Why is it Significant to the Networking Industry?
Case Study: Rogers Communications Integrates CA API Management and CA Service...
APIdays Paris 2019 - What are protected and secured by security requirements ...
APIdays Paris 2019 : Financial-grade API (FAPI) Security Profile
Aavenir webinar - making legal contracts work for everyone - 28 april 2020
How to manage Broadband Traffic Intelligently?
Get RTO Mobile Number Update API at best Price.pptx
Enterprise API deployment best practice
BabbleSMS Product Guide
apidays Helsinki & North 2025 - Vero APIs - Experiences of API development in...
Affordable RTO Detail API Service Provider Company.pptx
Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...

More from tawi123 (20)

PDF
Tax Compliance Certificate, May 2016 - May 2017
PPTX
XHTML and CSS
PPTX
Survey of WML
PPT
Server Side Technologies
PPTX
Software Tools Overview
PPTX
Overview of Java
PPTX
Mobile Internet Standards
PPTX
Mobile Internet Best Practices
PPT
Introduction to SMS, MMS, Modems & Gateways
PPTX
Introduction to Mobile Internet
PPTX
Mobile Website Development
PPTX
Brief on Device Awareness and Content Adaptation
DOCX
Linux, PHP, SMS - USSD Examination
PDF
Workstation Exercises
PDF
Work Injury Benefits Act 2007
PDF
The Kenya Information and Communications Consumer Protection Regulations 2010
PDF
Tax KRA Compliance Certificate
PDF
Tawi Staff Handbook 2015
PDF
Tawi SMS-USSD Customer Agreement
PDF
Tawi Product Overview
Tax Compliance Certificate, May 2016 - May 2017
XHTML and CSS
Survey of WML
Server Side Technologies
Software Tools Overview
Overview of Java
Mobile Internet Standards
Mobile Internet Best Practices
Introduction to SMS, MMS, Modems & Gateways
Introduction to Mobile Internet
Mobile Website Development
Brief on Device Awareness and Content Adaptation
Linux, PHP, SMS - USSD Examination
Workstation Exercises
Work Injury Benefits Act 2007
The Kenya Information and Communications Consumer Protection Regulations 2010
Tax KRA Compliance Certificate
Tawi Staff Handbook 2015
Tawi SMS-USSD Customer Agreement
Tawi Product Overview

Recently uploaded (20)

PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
PDF
STKI Israel Market Study 2025 version august
PPTX
The various Industrial Revolutions .pptx
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
August Patch Tuesday
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
Hybrid model detection and classification of lung cancer
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
observCloud-Native Containerability and monitoring.pptx
PPTX
Tartificialntelligence_presentation.pptx
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
WOOl fibre morphology and structure.pdf for textiles
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Group 1 Presentation -Planning and Decision Making .pptx
OMC Textile Division Presentation 2021.pptx
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
STKI Israel Market Study 2025 version august
The various Industrial Revolutions .pptx
Getting started with AI Agents and Multi-Agent Systems
August Patch Tuesday
A contest of sentiment analysis: k-nearest neighbor versus neural network
A novel scalable deep ensemble learning framework for big data classification...
Developing a website for English-speaking practice to English as a foreign la...
NewMind AI Weekly Chronicles - August'25-Week II
cloud_computing_Infrastucture_as_cloud_p
Enhancing emotion recognition model for a student engagement use case through...
Hybrid model detection and classification of lung cancer
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
observCloud-Native Containerability and monitoring.pptx
Tartificialntelligence_presentation.pptx
DP Operators-handbook-extract for the Mautical Institute
WOOl fibre morphology and structure.pdf for textiles

Tawi Airtime Gateway Developer Guide

  • 1. Tawi Airtime Gateway Developer Guide A Product of Tawi Commercial Services Ltd 2015 www.tawi.mobi http://airtimegw.tawi.mobi info@tawi.mobi July 2015
  • 2. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 1 INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH TAWI COMMERCIAL SERVICES’ PRODUCTS. NO INTELLECTUAL PROPERTY RIGHTS, LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, IS GRANTED BY THIS DOCUMENT, EXCEPT AS PROVIDED IN TAWI COMMERCIAL SERVICES’ TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS. TAWI COMMERCIAL SERVICES ASSUMES NO LIABILITY WHATSOEVER, AND TAWI COMMERCIAL SERVICES DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF TAWI COMMERCIAL SERVICES’ PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT. The Programs (which include both the software and documentation) contain proprietary information; they are provided under a license agreement containing restrictions on use and disclosure and are also protected by copyright, patent, and other intellectual and industrial property laws. Reverse engineering, disassembly, or decompilation of the Programs, except to the extent required to obtain interoperability with other independently created software or as specified by law, is prohibited. The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently dangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup, redundancy and other measures to ensure the safe use of such applications if the Programs are used for such purposes, and we disclaim liability for any damages caused by such use of the Programs. Tawi Commercial Services may make changes to specifications and product descriptions at any time, without notice. No part of this publication may be reproduced, transmitted, transcribed, stored in a retrieval system, or translated into any language or computer language, in any form or by any means, electronic mechanical, magnetic, optical, chemical, manual, or otherwise, without the prior written permission of Tawi Commercial Services Ltd. Copyright © 2015 by Tawi Commercial Services Ltd. All rights reserved. All other trademarks are property of their respective owners. Tawi Commercial Services Ltd. 1st Floor, Corner View Centre Naivasha Road, Nairobi CBD P.O. Box 20222 – 00100 Nairobi, Kenya
  • 3. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 2 Table of Contents 1. Document Information 3 1.1. Document History 3 2. Introduction 4 3. API Overview 5 4. API Commands 7 4.1. Send Airtime 7 4.2. Query Top-up Status 13 4.3. Query Balance 14 5. Message Status Codes 15 6. Appendices 18 A. Glossary 3 B. Sample Code 19 B1. Java 19 B2. PHP 25 C. References 27
  • 4. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 3 1. Document Information 1.1. Document History Release Date Author Comments Revision 1 Jul 2015 Michael Wakahe 1st Working Version 1.2. Document Conventions N/A 1.3. Related Documents None. 1.4. Glossary API …………………………………………… Application Programmer Interface CCK ………………………………………….. Communications Commission of Kenya HTTP ………………………………………... Hyper Text Transfer Protocol J2EE ……................................................... Java 2 Enterprise Edition MO …………………………………………... Mobile Originated SMS MSISDN …………………………………… A number uniquely identifying a subscription in a GSM mobile network MT …………………………………………… Mobile Terminated SMS PRSP ………………………………………… Premium Rate Services Provider SLA …………………………………………. Service Level Agreement
  • 5. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 4 2. Introduction Tawi Commercial Services Limited is a Kenyan based software development company specializing in mobile technologies. These include short codes, bulk SMS, USSD, mobile applications, and airtime. Tawi Commercial Services is a Premium Rate Service Provider (PRSP) with Safaricom1 Kenya and Airtel2 Kenya. This implies that she offers SMS and USSD services through these two network operators. The Tawi Airtime Gateway is software that allows for electronic topups through a web based interface (API). This document serves to describe to software integrators the various commands used to interact with the gateway. Figure 2.1: Tawi Airtime Gateway Overview 1 http://www.safaricom.co.ke 2 http://africa.airtel.com/kenya
  • 6. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 5 3. Portal and API Design Overview The Tawi Airtime Gateway is a product that facilitates for topping up of airtime on both Safaricom and Airtel. Connectivity is done via an HTTP API. This document details how one can set up to top up airtime through the gateway API. The gateway is accessible through the URL https://airtimegw.tawi.mobi. Internally, the gateway has many features to guarantee that it works correctly, including a continuous best effort approach to deliver instructions to the operator airtime systems and security to prevent unwarranted topping up of airtime. The communication between client and server is synchronous. There are a variety of conditions to be determined before a topup transaction is completed. For example, the recipient must be a valid mobile number. The server attempts to finish all of these within a socket connection. Communication between client and server always utilizes HTTPs. This is regardless of whether the client or the server initiated the communication. HTTPs is widely adopted for providing a secure tunnel for client-server communication over the Internet. The web service API utilizes a RESTful approach. Specifically JSON is the means for data interchange between client and server. Session Ids are generated by the server in order for the client to transact. A Session Id is a randomly generated text that is presented by the server in order for a client to execute or query. It expires after a window period. The Session Ids kept securely on the Tawi end and are never repeated. We advise the client to keep them securely on his or her end to avoid a replay attack while the session is still valid. One means can be to cache them in memory instead of writing them to RDBMS or file where they are human readable.
  • 7. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 6 A unique Transaction Id is generated for each request. Transactions into either success or failure. Failure can be due to various reasons including a non-existent phone number and a phone number in an unsupported network. The web portal allows for integrators to view their account activity. Details include account balance and topup activity. For security reasons, transaction records can neither be created nor altered from the web portal. A developer must already have an account with the Tawi Airtime Gateway before (s)he can attempt to send airtime through the system. Presently the default operator prefixes are as follows: Safaricom prefixes: 070, 071 and 072; Airtel prefixes: 073, 0785, 0788 and 0789. A Kenyan GSM phone number specified without the country code is always 10 digits long. As an example, the number 0701234567 has a valid length and by default would belong to the Safaricom network. Number portability exists in Kenya. This implies that any MSISDN may be associated with any network operator. The other network operator in Kenya is Orange3. There is currently no means to determine beforehand which operator a number belongs to. Airtime top up can only terminate in Kenya. 3 http://www.orange.co.ke
  • 8. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 7 4. API Commands The following section details the commands used to interact with the system. There is always a response for every command sent to the system. This is regardless of whether or not the command was successful. In this manner, you can determine whether or not the query has been received by the gateway. Send Airtime, Query Client Reference Number, Query Balance 4.1. Get Session Id A Session Id is a text that is used for identification. All other client requests must be accompanied by a Session Id in order for the server to successfully process them. It is temporal in nature, that is it expires after a predetermined amount of time. For subsequent client requests, a new one must be requested for. The Session Id is always unique. For security reasons it is recommended that the Client application safeguards the Session Ids it receives as they can be used to carry out legitimate transactions. In order to receive a Session Id, the client application requests the server through the instruction described in this section. Upon successful authentication, the Session Id is sent to a preconfigured URL. This URL can only be altered with the assistance of the server system administrator. The following sequence diagrams illustrate the process of acquiring a Session Id.
  • 9. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 8 Figure 4.1: Session Id Sequence Flow Diagram Web Service Endpoint: https://airtimegw.tawi.mobi/sessionid Client Request Parameters Parameter Value Compulsory Description api_username a username Yes A valid username that is permitted to remit money. Should be URL encoded using the UTF-8 scheme. api_password a password Yes A valid password that is permitted to remit money. Should be URL encoded using the UTF-8 scheme. Example JSON Request Body: {“api_username”:“demo”, “api_password”:“password” }
  • 10. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 9 Server Response Parameters The following are the parameters sent to the Client request: Parameter Value Compulsory Description command_status a status Yes A status indicating whether the server accepted the request or not. For further details on various status codes, see Chapter 5: Status Codes. Example JSON Response Body: {“command_status”:“Ok”} If the Client successfully requests for a Session Id, the Server sends the following parameters to the predetermined Client URL. The method used is HTTPS POST. Parameter Value Compulsory Description api_username a username Yes A valid username that is permitted to send airtime. Will be URL encoded using the UTF-8 scheme. session_id session id text Yes Randomly generated text that will be used by the Client for identification Example JSON POST Body: {“api_username”:“demo”, “session_id”:“1234567”} The following are extra notes concerning a Session Id:  A Client application can only have one valid Session Id at a time. If a Client initiates a request for a new Session Id before a previously held one expires, then the older one will be expired.
  • 11. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 10 4.2. Send Airtime This is the command to send airtime to single or multiple destinations through the gateway. The following sequence diagram illustrates the process of sending airtime. Figure 4.2: Send Airtime Sequence Flow Diagram Web Service Endpoint: https://airtimegw.tawi.mobi/topup Client Request Parameters Name Value Compulsory Description api_username a username Yes A valid username that is permitted to perform topup. Should be URL encoded using the UTF-8 scheme. session_id session id text Yes Randomly generated text that is used by the Client for identification. msisdn A phone number Yes This is the phone number(s) that
  • 12. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 11 is to receive airtime. No leading zero to the number and no special characters such as "+", spaces or hyphens must be used. For example, a number in the Kenya being 0720123456 should be changed to 254720123456. Multiple destinations are not supported in this version. amount An integral number value Yes This is the amount in the local currency that is to be sent to the target mobile numbers. The value should be in a whole number. reference_number A reference number Yes A reference number generated by the client application. This can be used to identify a topup transaction from the client side. Note that the client application should strive to generate a unique reference number for each transaction. network An MNO mnemonic for example “Safaricom_KE” Yes To indicate the network to direct the airtime to. The network should be indicated because number portability allows numbers to belong to any network. MNO mnemonics are listed in Appendix A: Network Operator Coverage. Note that the networks available are also dependent on your account setup.
  • 13. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 12 Example JSON Request Body (One Recipient): {“api_username”:“demo”, “session_id”:“31245”, “msisdn”:“254123456”, “amount”:“100”, “reference_number”:“abc123”, “network”:“Safaricom_KE”} Server Response Parameters The following are the parameters sent to the Client request: Parameter Value Compulsory Description command_status a status Yes A status indicating whether the server accepted the request or not. For further details on various status codes, see Chapter 5: Status Codes. transaction_id text No A Transaction Id is a unique identifier for a transaction. It is generated by the server and can be referenced in future. topup_status a status No The status of the attempt to top up the phone number. For further details on various status codes, see Chapter 5: Status Codes. datetime a date and time No A date-time of the server when it received the instruction. It is in the form: YYYY-MM-DDThh:mm:ss±hh:mm For example: 2014-06-11T13:54:27+03:00 This follows the ISO 86014 recommendations. Example JSON Response Body (single recipient): {“api_username”:“demo”, “transaction_id”:“47123e90-f1a6”, “command_status”:“Ok”, “topup_status”:”SUCCESS”, “datetime”:“2014-06-11T13:54:27+03:00”} 4 http://en.wikipedia.org/wiki/ISO_8601
  • 14. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 13 4.3. Query Top-up Status The following are the parameters used to query the most recent status of a top-up attempt. Web Service Endpoint http://airtimegw.tawi.mobi/status Client Request Parameters Name Value Compulsory Description api_username a username Yes A valid username that is permitted to perform topup. Should be URL encoded using the UTF-8 scheme. session_id session id text Yes Randomly generated text that is used by the Client for identification. transactionId or clientRefNumber a unique alphanumeric string Yes A valid transaction Id that was provided by the server in a previous top-up attempt. Alternatively the reference_number that was given in the Send Airtime command can be used. iii. Example Status Query http://airtimegw.tawi.mobi/status?username=tawi&password=info&transactionId=47b85 9b7-4e3e-4363-83d9-77c66c120bd6 iv. Response Parameters The format of a valid Query Status command is as follows: status code:timestamp The time stamp is in the ISO 8601 format, for example: 2013-11-18T10:38:28.385+03:00 The format of an invalid Query Status command is as follows: INVALID_PARAMETERS This also includes providing an invalid transaction Id. For further details on various status codes, see Chapter 5: Message Status Codes.
  • 15. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 14 4.4. Query Balance This API functionality allows for one to query the balance of airtime. The balance is returned in Kenya Shillings. i. Target URL: http://aritimegw.tawi.mobi/balance ii. Query Parameters Name Value Compulsory Description username a username or email Yes A valid username or email that is permitted to top up airtime. Should be URL encoded using the UTF-8 scheme. password a password Yes A valid password corresponding to the username above. Should be URL encoded using the UTF-8 scheme. network “safaricom”, “airtel” or “orange” Yes The mobile network that the user wishes to query the balance. iii. Example Query Balance This is an example of a Query Balance. http://airtimegw.tawi.mobi/balance?username=tawi&password=info&network=orange iv. Response Parameters The format of a valid Query Balance command is as follows: amount The format of an invalid Query Balance command is as follows: status code For further details on various status codes, see Chapter 5: Message Status Codes.
  • 16. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 15 v. Example Responses Example of a valid Query Balance command response: 5000 Example of an invalid Query Balance command response: UNKNOWN_USERNAME 5. Status Codes A status code is generated in response to an attempt to send airtime, query balance or check the status of a transaction. Below is a list of them with their description. Status codes are divided into two categories:  Command Status Codes: these are to give feedback on the Client conformity to the API command structure;  Airtime Transfer Status Codes: these are to give information on the state of remittance to a mobile subscriber. i. Command Status Codes These have the keyword “command_status”. Below is a listing with explanations:
  • 17. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 16 Value Interpretation OK The server has accepted the command for further processing. INVALID_SESSIONID The Session Id provided has either expired or was never issued. ii. Airtime Transfer Status Codes These have the keyword “remit_status”. Below is a listing with explanations: Value Interpretation SUCCESS The airtime has successfully been transferred. INSUFFICIENT_FUNDS There are insufficient funds in your account. STATUS_NOT_PERMITTED Your current account status is not permitted to remit airtime. For example, the account may have been Suspended. LOW_AMOUNT The topup amount specified is below the network minimum allowed amount in 1 transaction. Adjust by sending a higher amount. HIGH_AMOUNT The topup amount specified exceeds the network maximum allowed amount in 1 transaction. Adjust by sending lower amounts for multiple instances. UNKNOWN_ERROR The airtime has not been successfully transferred due to an unknown error. A status code is generated in response to an attempt to send airtime, query balance or check the status of a transaction. Below is a list of them with their description. Value Description ACCEPTED_FOR_DELIVERY The top-up request has been accepted by the gateway for delivery. SUBMITTED_TO_OPERATOR The message has been submitted to the operator airtime server. TOPUP_SUCESS The top-up attempt is successful. TOPUP_FAILURE The top-up attempt is not successful. UNKNOWN_USERNAME The username or email used to authenticate is not registered with the gateway.
  • 18. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 17 WRONG_PASSWORD The password supplied does not match the username. ACCOUNT_SUSPENDED The account from which the top-up attempt has been made is not active, it may be in a suspended or deleted state. INVALID_PARAMETERS Not enough or invalid parameters have been provided when submitting a request to send a message. This also includes invalid amounts for top-up. INSUFFICIENT_FUNDS The user has exhausted the airtime allowed for top- up. SERVER_ERROR The gateway has experienced an internal error. Value Description ACCEPTED_FOR_DELIVERY The top-up request has been accepted by the gateway for delivery. SUBMITTED_TO_OPERATOR The message has been submitted to the operator airtime server. TOPUP_SUCESS The top-up attempt is successful. TOPUP_FAILURE The top-up attempt is not successful. UNKNOWN_USERNAME The username or email used to authenticate is not registered with the gateway. WRONG_PASSWORD The password supplied does not match the username. ACCOUNT_SUSPENDED The account from which the top-up attempt has been made is not active, it may be in a suspended or deleted state. INVALID_PARAMETERS Not enough or invalid parameters have been provided when submitting a request to send a message. This also includes invalid amounts for top-up.
  • 19. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 18 INSUFFICIENT_FUNDS The user has exhausted the airtime allowed for top- up. SERVER_ERROR The gateway has experienced an internal error. 6. Appendices A. Network Operator Coverage Country MNO / SMS Aggregator Network Mnemonic Kenya Safaricom Safaricom_KE Kenya Airtel Kenya Airtel_KE
  • 20. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 19 B. Sample Code Below are examples of sending and receiving messages to the gateway. B1. Java 1. Send SMS import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.net.MalformedURLException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; /** * This Java program is a client that sends requests to the Tawi SMS Gateway * HTTP API. * <p> * This has been tested on JDK 1.7. * <p> * Copyright (c) Tawi Commercial Services Ltd., May 2012 * */ public class SMSSender { /** * @param args */ public static void main(String[ ] args) { String apiUrl = "http://sms.tawi.mobi/sendsms"; try { System.out.println("Response for a sendsms request: " + getResponse(apiUrl + "?" + "username=" + URLEncoder.encode("michael@hotmail.com", "UTF-8") + "&password=" + URLEncoder.encode("mypassword", "UTF-8") + "&account=live" + "&source=1987" + "&destination=254728123456" + "&message=" + URLEncoder.encode("Hello Test SMS!", "UTF-8") + "&network=safaricom")); } catch(UnsupportedEncodingException e) { System.err.println("UnsupportedEncodingException while trying to send SMS.");
  • 21. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 20 e.printStackTrace( ); } } /** * * @param urlStr * @return String */ private static String getResponse(String urlStr) { URLConnection conn; URL url; BufferedReader reader; String response = ""; try { url = new URL(urlStr); conn = url.openConnection( ); conn.setDoInput(true); conn.setDoOutput(true); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); response = reader.readLine(); reader.close( ); } catch(MalformedURLException e) { System.err.println("MalformedURLException exception"); e.printStackTrace( ); } catch(IOException e) { System.err.println("IOException exception"); e.printStackTrace( ); } return response; } }
  • 22. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 21 2. Receive SMS a. Receive without using Java Application Server import java.io.BufferedInputStream; import java.io.InputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * This Java program is a socket server that receives messages sent from the SMS Gateway * callback mechanism. * <p> * This has been tested on JDK 1.7. * <p> * Copyright (c) Tawi Commercial Services Ltd., June 2012 * */ public class ServerSocketListener { final static int SERVERSOCKET_PORT = 7777; /** * @param args */ public static void main(String[ ] args) { System.out.println("Have started socket listener"); ServerSocket serverSocket; Socket socket = null; InputStream is = null; BufferedInputStream bufferedInputStream = null; byte[ ] buffer = new byte[1024]; try { serverSocket = new ServerSocket(SERVERSOCKET_PORT); while (true) {
  • 23. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 22 socket = serverSocket.accept( ); System.out.println("Have received text"); is = socket.getInputStream( ); bufferedInputStream = new BufferedInputStream(is); int bytesRead = 0; // Keep reading till we reach the end of the stream. // When the end of the stream has been reached, -1 is returned while ((bytesRead = bufferedInputStream.read(buffer)) != -1) { // Construct a String from the bytes read String received = new String(buffer, 0, bytesRead); System.out.print("This is the string received: " + received); } } } catch (IOException ex) { System.err.println("IOException while listening on server socket."); ex.printStackTrace( ); } finally { // Close the stream and socket try { if (bufferedInputStream != null) bufferedInputStream.close( ); if (socket != null) socket.close( ); } catch (IOException ex) { ex.printStackTrace( ); } } } }
  • 24. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 23 b. Receive using Java Application Server (J2EE) import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This Java program is a servlet that receives messages sent from the SMS Gateway * callback mechanism. * <p> * This has been tested on JDK 1.7. and Oracle Glassfish 3.1. * <p> * Copyright (c) Tawi Commercial Services Ltd., June 2012 * */ public class CallbackListener2 extends HttpServlet { /** * * @param config * @throws ServletException */ public void init(ServletConfig config) throws ServletException { super.init(config); } /** * * @param servletRequest * @param servletResponse * @throws ServletException, IOException */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Have received callback."); String callbackType = request.getParameter("callbackType"); if(callbackType.equals("incomingSms")) {
  • 25. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 24 System.out.println("source is: " + request.getParameter("source")); System.out.println("destination is: " + request.getParameter("destination")); System.out.println("message is: " + request.getParameter("message")); System.out.println("messageId is: " + request.getParameter("messageId")); System.out.println("network is: " + request.getParameter("network")); } } /** * * @param servletRequest * @param servletResponse * @throws ServletException, IOException */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
  • 26. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 25 B2. PHP 1. Send SMS <?php /** * This PHP script is a client that sends requests to the Tawi SMS * Gateway HTTP API. * * This has been tested on Apache2 with PHP5 and cURL library installed. * * Copyright (c) Tawi Commercial Services Ltd., May 2012 */ // Open connection $ch = curl_init( ); // Set the URL and POST key-value pairs. curl_setopt($ch, CURLOPT_URL, "http://sms.tawi.mobi/sendsms"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, true); $data = array( 'username' => 'michael@hotmail.com', 'password' => 'mypassword', 'account' => 'live', 'source' => '2024', 'destination' => '254731234567', 'message' => 'Hello Test SMS!', 'network' => 'airtelkenya' ); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Execute POST. The variable $result will contain the response of the SMS Gateway. $result = curl_exec($ch); // Be sure to close your connections. curl_close($ch); echo ($result); ?>
  • 27. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 26 2. Receive SMS <?php /** * This is a PHP program that can receive callback data from the Tawi SMS Gateway * when the gateway triggers the callback mechanism. * * Copyright (c) Tawi Commercial Services Ltd., June 2012 * */ ?> <?php $myFile = "/tmp/callback.txt"; extract($_REQUEST); $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "callbackType: $callbackTypensource: $sourcendestination: $destinationnmessage: $message nmessageId: $messageIdnnetwork: $network"; fwrite($fh, $stringData); fclose($fh); ?>
  • 28. Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 27 C. References 1. Safaricom Kenya 2. Airtel Kenya 3. Communications Commission of Kenya