29
Tawi Airtime Gateway Developer Guide A Product of Tawi Commercial Services Ltd 2015 www.tawi.mobi http://airtimegw.tawi.mobi [email protected] July 2015

Tawi Airtime Gateway Developer Guide

  • Upload
    tawi123

  • View
    258

  • Download
    5

Embed Size (px)

Citation preview

Page 1: Tawi Airtime Gateway Developer Guide

Tawi Airtime GatewayDeveloper GuideA Product of Tawi Commercial Services Ltd

2015

www.tawi.mobihttp://[email protected] 2015

Page 2: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 1

INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH TAWI COMMERCIALSERVICES’ PRODUCTS. NO INTELLECTUAL PROPERTY RIGHTS, LICENSE, EXPRESS ORIMPLIED, BY ESTOPPEL OR OTHERWISE, IS GRANTED BY THIS DOCUMENT, EXCEPT ASPROVIDED IN TAWI COMMERCIAL SERVICES’ TERMS AND CONDITIONS OF SALE FOR SUCHPRODUCTS. TAWI COMMERCIAL SERVICES ASSUMES NO LIABILITY WHATSOEVER, AND TAWICOMMERCIAL SERVICES DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TOSALE AND/OR USE OF TAWI COMMERCIAL SERVICES’ PRODUCTS INCLUDING LIABILITY ORWARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, ORINFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.

The Programs (which include both the software and documentation) contain proprietary information; theyare provided under a license agreement containing restrictions on use and disclosure and are also protectedby 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 otherindependently 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 inherentlydangerous 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 forsuch 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, ortranslated 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 TawiCommercial 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 CentreNaivasha Road, Nairobi CBDP.O. Box 20222 – 00100Nairobi, Kenya

Page 3: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 2

Table of Contents1. 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

Page 4: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 3

1. Document Information

1.1. Document History

Release Date Author CommentsRevision 1 Jul 2015 Michael Wakahe 1st Working Version

1.2. Document ConventionsN/A1.3. Related DocumentsNone.1.4. GlossaryAPI …………………………………………… Application Programmer InterfaceCCK ………………………………………….. Communications Commission of KenyaHTTP ………………………………………... Hyper Text Transfer ProtocolJ2EE ……................................................... Java 2 Enterprise EditionMO …………………………………………... Mobile Originated SMSMSISDN …………………………………… A number uniquely identifying a subscription

in a GSM mobile networkMT …………………………………………… Mobile Terminated SMSPRSP ………………………………………… Premium Rate Services ProviderSLA …………………………………………. Service Level Agreement

Page 5: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 4

2. Introduction

Tawi Commercial Services Limited is a Kenyan based software development companyspecializing in mobile technologies. These include short codes, bulk SMS, USSD, mobileapplications, 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 throughthese two network operators. The Tawi Airtime Gateway is software that allows forelectronic topups through a web based interface (API). This document serves to describeto software integrators the various commands used to interact with the gateway.

Figure 2.1: Tawi Airtime Gateway Overview

1 http://www.safaricom.co.ke2 http://africa.airtel.com/kenya

Page 6: Tawi Airtime Gateway Developer Guide

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 bothSafaricom and Airtel. Connectivity is done via an HTTP API. This document details howone can set up to top up airtime through the gateway API. The gateway is accessiblethrough the URL https://airtimegw.tawi.mobi.

Internally, the gateway has many features to guarantee that it works correctly, includinga continuous best effort approach to deliver instructions to the operator airtime systemsand security to prevent unwarranted topping up of airtime.

The communication between client and server is synchronous. There are a variety ofconditions to be determined before a topup transaction is completed. For example, therecipient must be a valid mobile number. The server attempts to finish all of these withina socket connection.

Communication between client and server always utilizes HTTPs. This is regardless ofwhether the client or the server initiated the communication. HTTPs is widely adoptedfor providing a secure tunnel for client-server communication over the Internet.

The web service API utilizes a RESTful approach. Specifically JSON is the means fordata interchange between client and server.

Session Ids are generated by the server in order for the client to transact. A Session Id isa randomly generated text that is presented by the server in order for a client to executeor query. It expires after a window period.

The Session Ids kept securely on the Tawi end and are never repeated. We advise theclient to keep them securely on his or her end to avoid a replay attack while the session isstill valid. One means can be to cache them in memory instead of writing them toRDBMS or file where they are human readable.

Page 7: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 6

A unique Transaction Id is generated for each request. Transactions into either success orfailure. Failure can be due to various reasons including a non-existent phone number anda phone number in an unsupported network.

The web portal allows for integrators to view their account activity. Details includeaccount balance and topup activity. For security reasons, transaction records can neitherbe created nor altered from the web portal. A developer must already have an accountwith the Tawi Airtime Gateway before (s)he can attempt to send airtime through thesystem.

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 belongto the Safaricom network.

Number portability exists in Kenya. This implies that any MSISDN may be associatedwith any network operator. The other network operator in Kenya is Orange3. There iscurrently 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

Page 8: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 7

4. API CommandsThe 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 ofwhether or not the command was successful. In this manner, you can determine whetheror not the query has been received by the gateway.

Send Airtime, Query Client Reference Number, Query Balance

4.1. Get Session IdA Session Id is a text that is used for identification. All other client requests must beaccompanied by a Session Id in order for the server to successfully process them. It istemporal in nature, that is it expires after a predetermined amount of time. Forsubsequent client requests, a new one must be requested for.

The Session Id is always unique. For security reasons it is recommended that the Clientapplication safeguards the Session Ids it receives as they can be used to carry outlegitimate transactions.

In order to receive a Session Id, the client application requests the server through theinstruction described in this section. Upon successful authentication, the Session Id issent to a preconfigured URL. This URL can only be altered with the assistance of theserver system administrator. The following sequence diagrams illustrate the process ofacquiring a Session Id.

Page 9: Tawi Airtime Gateway Developer Guide

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 Descriptionapi_username a username Yes A valid username that is

permitted to remit money. Shouldbe URL encoded using the UTF-8scheme.

api_password a password Yes A valid password that ispermitted to remit money. Shouldbe URL encoded using the UTF-8scheme.

Example JSON Request Body: {“api_username”:“demo”, “api_password”:“password” }

Page 10: Tawi Airtime Gateway Developer Guide

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 Descriptioncommand_status a status Yes A status indicating whether the

server accepted the request ornot.

For further details on variousstatus 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 followingparameters to the predetermined Client URL. The method used is HTTPS POST.

Parameter Value Compulsory Descriptionapi_username a username Yes A valid username that is

permitted to send airtime. Will beURL encoded using the UTF-8scheme.

session_id session id text Yes Randomly generated text thatwill be used by the Client foridentification

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 arequest for a new Session Id before a previously held one expires, then the older onewill be expired.

Page 11: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 10

4.2. Send AirtimeThis is the command to send airtime to single or multiple destinations through thegateway. 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 Descriptionapi_username a username Yes A valid username that is

permitted to perform topup.Should be URL encoded usingthe UTF-8 scheme.

session_id session id text Yes Randomly generated text that isused by the Client foridentification.

msisdn A phone number Yes This is the phone number(s) that

Page 12: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 11

is to receive airtime. No leadingzero to the number and nospecial characters such as "+",spaces or hyphens must be used.For example, a number in theKenya being 0720123456 shouldbe changed to 254720123456.

Multiple destinations are notsupported in this version.

amount An integralnumber value

Yes This is the amount in the localcurrency that is to be sent to thetarget mobile numbers. Thevalue should be in a wholenumber.

reference_number A referencenumber

Yes A reference number generated bythe client application. This canbe used to identify a topuptransaction from the client side.

Note that the client applicationshould strive to generate aunique reference number foreach transaction.

network An MNOmnemonic forexample“Safaricom_KE”

Yes To indicate the network to directthe airtime to. The networkshould be indicated becausenumber portability allowsnumbers to belong to anynetwork.

MNO mnemonics are listed inAppendix A: Network OperatorCoverage.

Note that the networks availableare also dependent on youraccount setup.

Page 13: Tawi Airtime Gateway Developer Guide

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 Descriptioncommand_status a status Yes A status indicating whether the

server accepted the request ornot.

For further details on variousstatus codes, see Chapter 5:Status Codes.

transaction_id text No A Transaction Id is a uniqueidentifier for a transaction. It isgenerated by the server and canbe referenced in future.

topup_status a status No The status of the attempt to topup the phone number.

For further details on variousstatus codes, see Chapter 5:Status Codes.

datetime a date and time No A date-time of the server when itreceived the instruction. It is inthe form:YYYY-MM-DDThh:mm:ss±hh:mmFor 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

Page 14: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 13

4.3. Query Top-up StatusThe following are the parameters used to query the most recent status of a top-upattempt.

Web Service Endpoint http://airtimegw.tawi.mobi/status

Client Request Parameters

Name Value Compulsory Descriptionapi_username a username Yes A valid username that is permitted to

perform topup. Should be URLencoded using the UTF-8 scheme.

session_id session id text Yes Randomly generated text that is usedby the Client for identification.

transactionIdor

clientRefNumber

a uniquealphanumericstring

Yes A valid transaction Id that wasprovided by the server in a previoustop-up attempt.

Alternatively the reference_numberthat was given in the Send Airtimecommand can be used.

iii. Example Status Query

http://airtimegw.tawi.mobi/status?username=tawi&password=info&transactionId=47b859b7-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 variousstatus codes, see Chapter 5: Message Status Codes.

Page 15: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 14

4.4. Query BalanceThis API functionality allows for one to query the balance of airtime. The balance isreturned in Kenya Shillings.

i. Target URL: http://aritimegw.tawi.mobi/balance

ii. Query Parameters

Name Value Compulsory Descriptionusername a username or

emailYes A valid username or email that is

permitted to top up airtime.Should be URL encoded using theUTF-8 scheme.

password a password Yes A valid password corresponding tothe username above. Should beURL encoded using the UTF-8scheme.

network “safaricom”, “airtel”or “orange”

Yes The mobile network that the userwishes 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.

Page 16: Tawi Airtime Gateway Developer Guide

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 CodesA status code is generated in response to an attempt to send airtime, query balance orcheck 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 theAPI command structure;

Airtime Transfer Status Codes: these are to give information on the state ofremittance to a mobile subscriber.

i. Command Status CodesThese have the keyword “command_status”. Below is a listing with explanations:

Page 17: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 16

Value InterpretationOK 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 InterpretationSUCCESS 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 beenSuspended.

LOW_AMOUNT The topup amount specified is below the networkminimum allowed amount in 1 transaction. Adjust bysending a higher amount.

HIGH_AMOUNT The topup amount specified exceeds the networkmaximum allowed amount in 1 transaction. Adjust bysending lower amounts for multiple instances.

UNKNOWN_ERROR The airtime has not been successfully transferred dueto an unknown error.

A status code is generated in response to an attempt to send airtime, query balance orcheck the status of a transaction. Below is a list of them with their description.

Value DescriptionACCEPTED_FOR_DELIVERY The top-up request has been accepted by the gateway

for delivery.

SUBMITTED_TO_OPERATOR The message has been submitted to the operatorairtime 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 notregistered with the gateway.

Page 18: Tawi Airtime Gateway Developer Guide

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 beenmade is not active, it may be in a suspended or deletedstate.

INVALID_PARAMETERS Not enough or invalid parameters have been providedwhen submitting a request to send a message. Thisalso 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 DescriptionACCEPTED_FOR_DELIVERY The top-up request has been accepted by the gateway

for delivery.

SUBMITTED_TO_OPERATOR The message has been submitted to the operatorairtime 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 notregistered with the gateway.

WRONG_PASSWORD The password supplied does not match the username.

ACCOUNT_SUSPENDED The account from which the top-up attempt has beenmade is not active, it may be in a suspended or deletedstate.

INVALID_PARAMETERS Not enough or invalid parameters have been providedwhen submitting a request to send a message. Thisalso includes invalid amounts for top-up.

Page 19: Tawi Airtime Gateway Developer Guide

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 MnemonicKenya Safaricom Safaricom_KEKenya Airtel Kenya Airtel_KE

Page 20: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 19

B. Sample CodeBelow are examples of sending and receiving messages to the gateway.

B1. Java1. 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("[email protected]", "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.");

Page 21: Tawi Airtime Gateway Developer Guide

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;}

}

Page 22: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 21

2. Receive SMSa. 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) {

Page 23: Tawi Airtime Gateway Developer Guide

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 returnedwhile ((bytesRead = bufferedInputStream.read(buffer)) != -1) {

// Construct a String from the bytes readString 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 sockettry {

if (bufferedInputStream != null)bufferedInputStream.close( );

if (socket != null) socket.close( );

} catch (IOException ex) {ex.printStackTrace( );

}}

}}

Page 24: Tawi Airtime Gateway Developer Guide

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")) {

Page 25: Tawi Airtime Gateway Developer Guide

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);}

}

Page 26: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 25

B2. PHP1. 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' => '[email protected]','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);?>

Page 27: Tawi Airtime Gateway Developer Guide

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: $callbackType\nsource: $source\ndestination:$destination\nmessage: $message \nmessageId: $messageId\nnetwork: $network";

fwrite($fh, $stringData);fclose($fh);

?>

Page 28: Tawi Airtime Gateway Developer Guide

Copyright © Tawi Commercial Services Ltd. 2015. All rights reserved. 27

C. References1. Safaricom Kenya

2. Airtel Kenya

3. Communications Commission of Kenya

Page 29: Tawi Airtime Gateway Developer Guide