SlideShare a Scribd company logo
1 of 29
Download to read offline
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

What's hot

Comparative study between e pay company
Comparative study between e pay companyComparative study between e pay company
Comparative study between e pay companyPawanSharma207780
 
Aria Telecom Profile
Aria Telecom ProfileAria Telecom Profile
Aria Telecom Profilersaini12
 
Your Top Messaging Questions Answered
Your Top Messaging Questions AnsweredYour Top Messaging Questions Answered
Your Top Messaging Questions AnsweredAerialink
 
Sms country profile 1
Sms country profile 1Sms country profile 1
Sms country profile 1Manish Dubey
 
Password Replacement Technology : Removing Limitations of Current Passwords
Password Replacement Technology : Removing Limitations of Current PasswordsPassword Replacement Technology : Removing Limitations of Current Passwords
Password Replacement Technology : Removing Limitations of Current PasswordsDavid Kim
 
Accepting Late payments By Phone
Accepting Late payments By PhoneAccepting Late payments By Phone
Accepting Late payments By PhoneWayne Akey
 
Company Profile For Per
Company Profile For PerCompany Profile For Per
Company Profile For PerPerceptio
 
Guidelines for using Ericsson's exposed charging APIs
Guidelines for using Ericsson's exposed charging APIsGuidelines for using Ericsson's exposed charging APIs
Guidelines for using Ericsson's exposed charging APIsAlan Quayle
 
Shufti Pro| Digital Identity Verification Solution
Shufti Pro| Digital Identity Verification SolutionShufti Pro| Digital Identity Verification Solution
Shufti Pro| Digital Identity Verification SolutionJoshuaVictor10
 
Success Stories - Transportation Series
Success Stories - Transportation SeriesSuccess Stories - Transportation Series
Success Stories - Transportation Serieskevlzx
 
Swift Mail Communications Ltd. Franchisee Opportunity
Swift Mail Communications Ltd. Franchisee OpportunitySwift Mail Communications Ltd. Franchisee Opportunity
Swift Mail Communications Ltd. Franchisee OpportunityShailendra Yadav
 
Smart Solutions Profile
Smart Solutions ProfileSmart Solutions Profile
Smart Solutions Profileemetani
 
Introducing safexpay smart NBFC solution
Introducing safexpay smart NBFC solutionIntroducing safexpay smart NBFC solution
Introducing safexpay smart NBFC solutionNeha Sahay
 
InReceipts Plug N Play Client & REST APIs for billing softwares v1.0
InReceipts Plug N Play Client & REST APIs for billing softwares v1.0InReceipts Plug N Play Client & REST APIs for billing softwares v1.0
InReceipts Plug N Play Client & REST APIs for billing softwares v1.0InReceipts
 
WhatsApp Business Solution Compared
WhatsApp Business Solution ComparedWhatsApp Business Solution Compared
WhatsApp Business Solution ComparedREJI S
 
Parth for ip pbx- office communication
Parth for ip pbx- office communicationParth for ip pbx- office communication
Parth for ip pbx- office communicationAria Telecom
 

What's hot (20)

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

Viewers also liked

מסע לאתיופיה - צביה שמע
מסע לאתיופיה - צביה שמעמסע לאתיופיה - צביה שמע
מסע לאתיופיה - צביה שמעצביה שמע
 
KingNeed Q6 Mini Magnet Voice Recorder
KingNeed Q6 Mini Magnet Voice RecorderKingNeed Q6 Mini Magnet Voice Recorder
KingNeed Q6 Mini Magnet Voice Recordergpspro
 
La didattica della neoscrittura
La didattica della neoscrittura La didattica della neoscrittura
La didattica della neoscrittura USR Lazio
 
Tawi SMS Application Form - SMS Short Code
Tawi SMS Application Form - SMS Short CodeTawi SMS Application Form - SMS Short Code
Tawi SMS Application Form - SMS Short Codetawi123
 
Tawi SMS Application Form - Sender Id
Tawi SMS Application Form - Sender IdTawi SMS Application Form - Sender Id
Tawi SMS Application Form - Sender Idtawi123
 
Ecology PowerPoint Review Game, Quiz, Symbiosis, Plants and Animals, Exotic S...
Ecology PowerPoint Review Game, Quiz, Symbiosis, Plants and Animals, Exotic S...Ecology PowerPoint Review Game, Quiz, Symbiosis, Plants and Animals, Exotic S...
Ecology PowerPoint Review Game, Quiz, Symbiosis, Plants and Animals, Exotic S...www.sciencepowerpoint.com
 
Top 10 discussion starters for children
Top 10 discussion starters for childrenTop 10 discussion starters for children
Top 10 discussion starters for childrenJackie Bolen
 
Konsep profesi keguruan
Konsep profesi keguruanKonsep profesi keguruan
Konsep profesi keguruanSigitpga
 

Viewers also liked (14)

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

Similar to Tawi Airtime Gateway Developer Guide

Lessons Learned From Four Years of API Management Implementation Success at Unum
Lessons Learned From Four Years of API Management Implementation Success at UnumLessons Learned From Four Years of API Management Implementation Success at Unum
Lessons Learned From Four Years of API Management Implementation Success at UnumCA Technologies
 
Building an API Monetization Stack
Building an API Monetization StackBuilding an API Monetization Stack
Building an API Monetization StackNordic APIs
 
How to monitor Network Traffic
How to monitor Network TrafficHow to monitor Network Traffic
How to monitor Network TrafficMahindra Comviva
 
TechM Ritter Solution Case Study - V1.5
TechM Ritter Solution Case Study - V1.5TechM Ritter Solution Case Study - V1.5
TechM Ritter Solution Case Study - V1.5Shobhit Srivastava
 
Introduction to WebRTC on the Force.com Platform
Introduction to WebRTC on the Force.com PlatformIntroduction to WebRTC on the Force.com Platform
Introduction to WebRTC on the Force.com PlatformSalesforce Developers
 
Creating an Omnichannel Experience for Your Customers
Creating an Omnichannel Experience for Your CustomersCreating an Omnichannel Experience for Your Customers
Creating an Omnichannel Experience for Your CustomersCA Technologies
 
Authentication with OAuth and Connected Apps
Authentication with OAuth and Connected AppsAuthentication with OAuth and Connected Apps
Authentication with OAuth and Connected AppsSalesforce Developers
 
What is NFV and Why is it Significant to the Networking Industry?
 What is NFV and Why is it Significant to the Networking Industry? What is NFV and Why is it Significant to the Networking Industry?
What is NFV and Why is it Significant to the Networking Industry?Mahindra Comviva
 
Case Study: Rogers Communications Integrates CA API Management and CA Service...
Case Study: Rogers Communications Integrates CA API Management and CA Service...Case Study: Rogers Communications Integrates CA API Management and CA Service...
Case Study: Rogers Communications Integrates CA API Management and CA Service...CA Technologies
 
APIdays Paris 2019 : Financial-grade API (FAPI) Security Profile
APIdays Paris 2019 : Financial-grade API (FAPI) Security ProfileAPIdays Paris 2019 : Financial-grade API (FAPI) Security Profile
APIdays Paris 2019 : Financial-grade API (FAPI) Security ProfileHitachi, Ltd. OSS Solution Center.
 
APIdays Paris 2019 - What are protected and secured by security requirements ...
APIdays Paris 2019 - What are protected and secured by security requirements ...APIdays Paris 2019 - What are protected and secured by security requirements ...
APIdays Paris 2019 - What are protected and secured by security requirements ...apidays
 
Aavenir webinar - making legal contracts work for everyone - 28 april 2020
Aavenir webinar - making legal contracts work for everyone - 28 april 2020Aavenir webinar - making legal contracts work for everyone - 28 april 2020
Aavenir webinar - making legal contracts work for everyone - 28 april 2020Aavenir
 
How to manage Broadband Traffic Intelligently?
How to manage Broadband Traffic Intelligently?How to manage Broadband Traffic Intelligently?
How to manage Broadband Traffic Intelligently?Mahindra Comviva
 
Get RTO Mobile Number Update API at best Price.pptx
Get RTO Mobile Number Update API at best Price.pptxGet RTO Mobile Number Update API at best Price.pptx
Get RTO Mobile Number Update API at best Price.pptxsoftpayindia pvt. ltd
 
Enterprise API deployment best practice
Enterprise API deployment best practiceEnterprise API deployment best practice
Enterprise API deployment best practiceSanjay Roy
 
BabbleSMS Product Guide
BabbleSMS Product GuideBabbleSMS Product Guide
BabbleSMS Product Guidetawi123
 
Affordable RTO Detail API Service Provider Company.pptx
Affordable RTO Detail API Service Provider Company.pptxAffordable RTO Detail API Service Provider Company.pptx
Affordable RTO Detail API Service Provider Company.pptxSoftcare Infotech
 
Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...
Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...
Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...CA Technologies
 
apidays LIVE Jakarta - Leveraging Business Growth with Telco API by Iwan Pujo...
apidays LIVE Jakarta - Leveraging Business Growth with Telco API by Iwan Pujo...apidays LIVE Jakarta - Leveraging Business Growth with Telco API by Iwan Pujo...
apidays LIVE Jakarta - Leveraging Business Growth with Telco API by Iwan Pujo...apidays
 
Softpay Mobile operator Verification API Company.pptx
Softpay  Mobile operator Verification API Company.pptxSoftpay  Mobile operator Verification API Company.pptx
Softpay Mobile operator Verification API Company.pptxsoftpayindia pvt. ltd
 

Similar to Tawi Airtime Gateway Developer Guide (20)

Lessons Learned From Four Years of API Management Implementation Success at Unum
Lessons Learned From Four Years of API Management Implementation Success at UnumLessons Learned From Four Years of API Management Implementation Success at Unum
Lessons Learned From Four Years of API Management Implementation Success at Unum
 
Building an API Monetization Stack
Building an API Monetization StackBuilding an API Monetization Stack
Building an API Monetization Stack
 
How to monitor Network Traffic
How to monitor Network TrafficHow to monitor Network Traffic
How to monitor Network Traffic
 
TechM Ritter Solution Case Study - V1.5
TechM Ritter Solution Case Study - V1.5TechM Ritter Solution Case Study - V1.5
TechM Ritter Solution Case Study - V1.5
 
Introduction to WebRTC on the Force.com Platform
Introduction to WebRTC on the Force.com PlatformIntroduction to WebRTC on the Force.com Platform
Introduction to WebRTC on the Force.com Platform
 
Creating an Omnichannel Experience for Your Customers
Creating an Omnichannel Experience for Your CustomersCreating an Omnichannel Experience for Your Customers
Creating an Omnichannel Experience for Your Customers
 
Authentication with OAuth and Connected Apps
Authentication with OAuth and Connected AppsAuthentication with OAuth and Connected Apps
Authentication with OAuth and Connected Apps
 
What is NFV and Why is it Significant to the Networking Industry?
 What is NFV and Why is it Significant to the Networking Industry? What is NFV and Why is it Significant to the Networking Industry?
What is NFV and Why is it Significant to the Networking Industry?
 
Case Study: Rogers Communications Integrates CA API Management and CA Service...
Case Study: Rogers Communications Integrates CA API Management and CA Service...Case Study: Rogers Communications Integrates CA API Management and CA Service...
Case Study: Rogers Communications Integrates CA API Management and CA Service...
 
APIdays Paris 2019 : Financial-grade API (FAPI) Security Profile
APIdays Paris 2019 : Financial-grade API (FAPI) Security ProfileAPIdays Paris 2019 : Financial-grade API (FAPI) Security Profile
APIdays Paris 2019 : Financial-grade API (FAPI) Security Profile
 
APIdays Paris 2019 - What are protected and secured by security requirements ...
APIdays Paris 2019 - What are protected and secured by security requirements ...APIdays Paris 2019 - What are protected and secured by security requirements ...
APIdays Paris 2019 - What are protected and secured by security requirements ...
 
Aavenir webinar - making legal contracts work for everyone - 28 april 2020
Aavenir webinar - making legal contracts work for everyone - 28 april 2020Aavenir webinar - making legal contracts work for everyone - 28 april 2020
Aavenir webinar - making legal contracts work for everyone - 28 april 2020
 
How to manage Broadband Traffic Intelligently?
How to manage Broadband Traffic Intelligently?How to manage Broadband Traffic Intelligently?
How to manage Broadband Traffic Intelligently?
 
Get RTO Mobile Number Update API at best Price.pptx
Get RTO Mobile Number Update API at best Price.pptxGet RTO Mobile Number Update API at best Price.pptx
Get RTO Mobile Number Update API at best Price.pptx
 
Enterprise API deployment best practice
Enterprise API deployment best practiceEnterprise API deployment best practice
Enterprise API deployment best practice
 
BabbleSMS Product Guide
BabbleSMS Product GuideBabbleSMS Product Guide
BabbleSMS Product Guide
 
Affordable RTO Detail API Service Provider Company.pptx
Affordable RTO Detail API Service Provider Company.pptxAffordable RTO Detail API Service Provider Company.pptx
Affordable RTO Detail API Service Provider Company.pptx
 
Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...
Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...
Case Study: Gala Coral Improves the Odds in Retail Gaming and Entertainment w...
 
apidays LIVE Jakarta - Leveraging Business Growth with Telco API by Iwan Pujo...
apidays LIVE Jakarta - Leveraging Business Growth with Telco API by Iwan Pujo...apidays LIVE Jakarta - Leveraging Business Growth with Telco API by Iwan Pujo...
apidays LIVE Jakarta - Leveraging Business Growth with Telco API by Iwan Pujo...
 
Softpay Mobile operator Verification API Company.pptx
Softpay  Mobile operator Verification API Company.pptxSoftpay  Mobile operator Verification API Company.pptx
Softpay Mobile operator Verification API Company.pptx
 

More from tawi123

Tax Compliance Certificate, May 2016 - May 2017
Tax Compliance Certificate, May 2016 -  May 2017Tax Compliance Certificate, May 2016 -  May 2017
Tax Compliance Certificate, May 2016 - May 2017tawi123
 
XHTML and CSS
XHTML and CSSXHTML and CSS
XHTML and CSStawi123
 
Survey of WML
Survey of  WMLSurvey of  WML
Survey of WMLtawi123
 
Server Side Technologies
Server Side TechnologiesServer Side Technologies
Server Side Technologiestawi123
 
Software Tools Overview
Software Tools OverviewSoftware Tools Overview
Software Tools Overviewtawi123
 
Overview of Java
Overview of JavaOverview of Java
Overview of Javatawi123
 
Mobile Internet Standards
Mobile Internet StandardsMobile Internet Standards
Mobile Internet Standardstawi123
 
Mobile Internet Best Practices
Mobile Internet Best PracticesMobile Internet Best Practices
Mobile Internet Best Practicestawi123
 
Introduction to SMS, MMS, Modems & Gateways
Introduction to SMS, MMS, Modems & GatewaysIntroduction to SMS, MMS, Modems & Gateways
Introduction to SMS, MMS, Modems & Gatewaystawi123
 
Introduction to Mobile Internet
Introduction to Mobile InternetIntroduction to Mobile Internet
Introduction to Mobile Internettawi123
 
Mobile Website Development
Mobile Website DevelopmentMobile Website Development
Mobile Website Developmenttawi123
 
Brief on Device Awareness and Content Adaptation
Brief on Device Awareness and Content AdaptationBrief on Device Awareness and Content Adaptation
Brief on Device Awareness and Content Adaptationtawi123
 
Linux, PHP, SMS - USSD Examination
Linux, PHP,  SMS - USSD ExaminationLinux, PHP,  SMS - USSD Examination
Linux, PHP, SMS - USSD Examinationtawi123
 
Workstation Exercises
Workstation ExercisesWorkstation Exercises
Workstation Exercisestawi123
 
Work Injury Benefits Act 2007
Work Injury Benefits Act 2007Work Injury Benefits Act 2007
Work Injury Benefits Act 2007tawi123
 
The Kenya Information and Communications Consumer Protection Regulations 2010
The Kenya Information and Communications Consumer Protection Regulations 2010The Kenya Information and Communications Consumer Protection Regulations 2010
The Kenya Information and Communications Consumer Protection Regulations 2010tawi123
 
Tax KRA Compliance Certificate
Tax KRA Compliance CertificateTax KRA Compliance Certificate
Tax KRA Compliance Certificatetawi123
 
Tawi Staff Handbook 2015
Tawi Staff Handbook 2015Tawi Staff Handbook 2015
Tawi Staff Handbook 2015tawi123
 
Tawi SMS-USSD Customer Agreement
Tawi SMS-USSD Customer AgreementTawi SMS-USSD Customer Agreement
Tawi SMS-USSD Customer Agreementtawi123
 
Tawi Product Overview
Tawi Product OverviewTawi Product Overview
Tawi Product Overviewtawi123
 

More from tawi123 (20)

Tax Compliance Certificate, May 2016 - May 2017
Tax Compliance Certificate, May 2016 -  May 2017Tax Compliance Certificate, May 2016 -  May 2017
Tax Compliance Certificate, May 2016 - May 2017
 
XHTML and CSS
XHTML and CSSXHTML and CSS
XHTML and CSS
 
Survey of WML
Survey of  WMLSurvey of  WML
Survey of WML
 
Server Side Technologies
Server Side TechnologiesServer Side Technologies
Server Side Technologies
 
Software Tools Overview
Software Tools OverviewSoftware Tools Overview
Software Tools Overview
 
Overview of Java
Overview of JavaOverview of Java
Overview of Java
 
Mobile Internet Standards
Mobile Internet StandardsMobile Internet Standards
Mobile Internet Standards
 
Mobile Internet Best Practices
Mobile Internet Best PracticesMobile Internet Best Practices
Mobile Internet Best Practices
 
Introduction to SMS, MMS, Modems & Gateways
Introduction to SMS, MMS, Modems & GatewaysIntroduction to SMS, MMS, Modems & Gateways
Introduction to SMS, MMS, Modems & Gateways
 
Introduction to Mobile Internet
Introduction to Mobile InternetIntroduction to Mobile Internet
Introduction to Mobile Internet
 
Mobile Website Development
Mobile Website DevelopmentMobile Website Development
Mobile Website Development
 
Brief on Device Awareness and Content Adaptation
Brief on Device Awareness and Content AdaptationBrief on Device Awareness and Content Adaptation
Brief on Device Awareness and Content Adaptation
 
Linux, PHP, SMS - USSD Examination
Linux, PHP,  SMS - USSD ExaminationLinux, PHP,  SMS - USSD Examination
Linux, PHP, SMS - USSD Examination
 
Workstation Exercises
Workstation ExercisesWorkstation Exercises
Workstation Exercises
 
Work Injury Benefits Act 2007
Work Injury Benefits Act 2007Work Injury Benefits Act 2007
Work Injury Benefits Act 2007
 
The Kenya Information and Communications Consumer Protection Regulations 2010
The Kenya Information and Communications Consumer Protection Regulations 2010The Kenya Information and Communications Consumer Protection Regulations 2010
The Kenya Information and Communications Consumer Protection Regulations 2010
 
Tax KRA Compliance Certificate
Tax KRA Compliance CertificateTax KRA Compliance Certificate
Tax KRA Compliance Certificate
 
Tawi Staff Handbook 2015
Tawi Staff Handbook 2015Tawi Staff Handbook 2015
Tawi Staff Handbook 2015
 
Tawi SMS-USSD Customer Agreement
Tawi SMS-USSD Customer AgreementTawi SMS-USSD Customer Agreement
Tawi SMS-USSD Customer Agreement
 
Tawi Product Overview
Tawi Product OverviewTawi Product Overview
Tawi Product Overview
 

Recently uploaded

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

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