Tawi SMS Gateway Developer Guide

32
Tawi SMS Gateway Developer Guide A Product of Tawi Commercial Services Ltd 2015 www.tawi.mobi [email protected] July 2014

Transcript of Tawi SMS Gateway Developer Guide

Page 1: Tawi SMS Gateway Developer Guide

Tawi SMS GatewayDeveloper GuideA Product of Tawi Commercial Services Ltd

2015

[email protected]

July 2014

Page 2: Tawi SMS 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.2nd Floor, Twiga TowersMurang’a Road, Nairobi CBDP.O. Box 20222 – 00100Nairobi, Kenya

Page 3: Tawi SMS Gateway Developer Guide

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

Table of Contents1. Document Information 3

1.1. Document History 3

1.2. Document Conventions 3

1.3. Related Documents 3

1.4. Glossary 4

2. Introduction 5

3. API Overview 6

4. API Commands 8

4.1. Client Initiated 8

4.1.1. Send SMS 8

4.1.2. Query Message Status 3

4.1.3. Query Balance 5

4.2. Server Initiated 6

4.2.1. Receive SMS 6

5. Status Codes 9

5.1. Query Status Codes 9

5.2. Message Status Codes 10

6. Supported Alphanumeric Characters 11

7. Appendices 12

A. Network Operator Coverage 12

B. Sample Code 12

B1. Java 12

B2. PHP 18

C. References 20

Page 4: Tawi SMS 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 Jun 2014 Michael Wakahe 1st Working Version

1.2. Document ConventionsN/A

1.3. Related DocumentsThe following are other documents pertaining to SMS services offered by TawiCommercial Services Ltd:

Tawi SMS Gateway Overview SMS Application Form Information Confidentiality Agreement Terms and Conditions

Page 5: Tawi SMS Gateway Developer Guide

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

1.4. GlossaryAPI …………………………………………… Application Programmer InterfaceCAK ………………………………………….. Communications Authority of KenyaHTTP ………………………………………... Hyper Text Transfer ProtocolMNO ……................................................... Mobile Network Operator e.g. SafaricomMO …………………………………………... 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 6: Tawi SMS Gateway Developer Guide

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

2. Introduction

Tawi Commercial Services Limited is a Kenyan based software development companyspecializing in mobile technologies. These include short codes, bulk SMS, USSD andelectronic airtime.

Tawi offers Premium Rate Services with Safaricom1 Kenya and Airtel2 Kenya. Thisimplies that she offers SMS and USSD services through these two network operators.The Tawi SMS Gateway is software that allows for remote short code and bulk SMSinteractivity through a web based interface (API). This document serves to describe tosoftware integrators the various commands used to interact with the gateway.

Figure 2.1: Tawi SMS Gateway Overview

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

Page 7: Tawi SMS Gateway Developer Guide

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

3. API Overview

The Tawi SMS Gateway is a product that facilitates sending of SMS by multiple partiesto both Safaricom and Airtel. It also allows for receiving of the messages by the parties.Connectivity is done via an HTTP API. This document details how one can set up thesending and receiving of SMS remotely. The gateway is accessible through the URLhttp://sms.tawi.mobi.

Internally, the gateway has many features to guarantee that it works correctly, includingno messages lost in transit, a continuous best effort approach to deliver the messages tothe operator SMS centres and security to prevent unwarranted sending of SMS. It allowsbusinesses and other institutions to remotely monitor their individual accounts.

In this manner, an institution can be concerned only with creating and maintaining itsown business logic in software and using the gateway to send and receive SMS whichabstract the underlying network complexities in the interaction with bulk SMS and shortcodes.

The API utilizes HTTP GETs and POSTs with key-value pairs. POSTs are preferred overGETs due to their higher security as well as ability to transmit more data. Security suchas HTTP over a secure socket layer (HTTPS) and data encryption using asymmetric keyswill also be supported.

An SMS developer must already have an account with the Tawi SMS Gateway before(s)he can attempt to send SMS through the system.

Presently the default Kenyan operator prefixes are as follows:

Page 8: Tawi SMS Gateway Developer Guide

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

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 has now been introduced in Kenya. This implies that any MSISDNmay be associated with any network operator. The other network operators in Kenya areOrange3 and Yu (Essar)4. Presently there is no means to determine beforehand whichoperator a number belongs to. Bulk and premium SMS can only terminate on Kenyantelco issued SIM cards.

3 http://www.orange.co.ke4 http://www.yu.co.ke

Page 9: Tawi SMS Gateway Developer Guide

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

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.

4.1. Client InitiatedThese are commands which are launched by the client application.

4.1.1. Send SMSThis is the command to send a single or multiple SMS through the gateway.

Page 10: Tawi SMS Gateway Developer Guide

Fig 4.1.1. Send SMS Sequence

Page 11: Tawi SMS Gateway Developer Guide

Web Service Endpoint: http://sms.tawi.mobi/sendsms

Client Request Parameters

Name Value Compulsory Descriptionusername a username Yes A valid username that is

permitted to send SMS. Should beURL encoded using the UTF-8scheme.

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

source short code numberor mask

Yes The short code or mask which willbe used as the origin of this SMS.The source address (from), alsoknown as the Sender Id, can beeither a valid short code (forexample 20240), or analphanumeric string. These mustbe registered within your onlineaccount and approved by Tawibefore they may be used.

destination MSISDN Yes Destination of this SMS. Noleading zero 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 can bespecified by separating them witha semicolon. For example, settingdestination as “254720123456;254721123456;254722123456”will have the message sent tothese three destinations.

When sending to multiple

Page 12: Tawi SMS Gateway Developer Guide

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

destinations, ensure that alltarget phone numbers are on thesame network.

message an SMS message Yes The text to be sent to the targetphone number. Message should beURL encoded using the UTF-8scheme. Messages longer than 160characters are concatenated.However the recipient may bebilled more than once if the sourceis a short code.

Bulk SMS credits are deducted ifthey are used, the count will be inmultiples of 160 characters. Themessage cannot be empty.

network an MNO mnemonicfor example“Safaricom_KE”

Yes To indicate the network to directthe SMS to. The network shouldbe indicated because numberportability allows numbers tobelong to any network.

MNO mnemonics are listed inAppendix A: Network OperatorCoverage.

Note that the networks availableare also dependent on youraccount setup.

Example Request

The first example below sends the SMS to a single destination whereas the second sendsto multiple destinations.

http://sms.tawi.mobi/sendsms?username=tawi&password=info&source=20240&destination=254728123456&message=This%20is%20a%20test.&network=safaricom_ke

Page 13: Tawi SMS Gateway Developer Guide

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

http://sms.tawi.mobi/sendsms?username=tawi&password=info&source=20240&destination=254721123456;254722123456;254723123456&message=This%20is%20a%20test.&network=safaricom_ke

Server Response Parameters

Parameter Value Compulsory DescriptionrequestStatus a status Yes A status indicating whether the

server accepted the request ornot.

messageIds text No A Message Id is a uniqueidentifier for a send SMS request.It is generated by the server andcan be referenced in future. Thevalue here will be a list ofMSISDNs and the correspondingMessage Id. The MSISDN(s) arethe ones supplied in thedestination request parameter.

Example Server Responses

Example of a successful Send SMS response where there is only 1 destination:requestStatus=ACCEPTED&messageIds=254721234567:rGatF1325073545

Example of a successful Send SMS response where there are multiple destinations:requestStatus=ACCEPTED&messageIds=254721234567:TeImE1334595755;254728765432:Tgfu1334593572;254722543210: rGatF1325073545

Example of an unsuccessful Send SMS response:requestStatus=INSUFFICIENT_CREDIT

Page 14: Tawi SMS Gateway Developer Guide

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

4.1.2. Query Message StatusThis API functionality is provided for one to be able to determine the status of anOutgoing SMS. The SMS changes state as it goes through the network to its finaldestination. This command is not applicable to Incoming SMS.

The status returned is the current one only. The past statuses of the message are notincluded in this particular command. The information retrieved also includes the time ofstatus change. For more information on a particular message, refer to the Outgoing SMStable on the web interface.

The API can be called any time after a message has been successfully accepted fordelivery. Below are instructions on how to use this functionality.

Web Service Endpoint: http://sms.tawi.mobi/querystatus

Client Request Parameters

Name Value Compulsory Descriptionusername a username Yes A valid username that is

permitted to send SMS. Should beURL encoded using the UTF-8scheme.

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

messageId a valid Message Id Yes This is the Message Id that isproduced when the SMS gatewaysuccessfully accepts a message fordelivery.

Example Request

This is an example of a Query Status.

http://sms.tawi.mobi/querystatus?username=tawi&password=info&messageId=TeImE1334595755

Page 15: Tawi SMS Gateway Developer Guide

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

Server Response Parameters

Parameter Value Compulsory DescriptionrequestStatus a status Yes A status indicating whether the

server accepted the request ornot.

messageStatus text No A message status code asindicated in section 5.2: MessageStatus Codes.

datetime a date and time No A date-time of when the messagechanged to this status. It is in theform:YYYY-MM-DDThh:mm:ss±hh:mmFor example:2014-06-11T13:54:27+03:00This follows the ISO 86015

recommendations.

Example Server Responses

Example of a successful Query Status:requestStatus=ACCEPTED& messageStatus=DELIVERY_SUCCESS&datetime=2014-06-11T13:54:27+03:00

Example of an unsuccessful Query Status:requestStatus=UNKNOWN_MESSAGEID

5 http://en.wikipedia.org/wiki/ISO_8601

Page 16: Tawi SMS Gateway Developer Guide

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

4.1.3. Query Balance

This gives an opportunity for a client application to query the number of SMS credits thatare available in the gateway. These are listed against the MNOs that are configured inthe client account. The balance is valid as of the time of the query.

Web Service Endpoint: http://sms.tawi.mobi/querybalance

Client Request Parameters

Name Value Compulsory Descriptionusername a username Yes A valid username that is

permitted to send SMS. Should beURL encoded using the UTF-8scheme.

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

Example Request

This is an example of a Query Status.

http://sms.tawi.mobi/querybalance?username=tawi&password=info

Server Response Parameters

Parameter Value Compulsory DescriptionrequestStatus a status Yes A status indicating whether the

server accepted the request or not.balance text No Pairs of short codes / masks and

MNO mnemonics withcorresponding balances in integervalues. The MNO mnemonics arelisted in Appendix A: NetworkOperator Coverage.

Page 17: Tawi SMS Gateway Developer Guide

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

Example Server Responses

Example of a successful Query Status:requestStatus=ACCEPTED&balance=22500-Safaricom_KE:9950;22500-Airtel_KE:2345;Info-Safaricom_KE:693

In this example, the account has the short code 22500 on both Safaricom Kenya andAirtel Kenya networks. The account also has an SMS Mask Info on the Safaricomnetwork.

Example of an unsuccessful Query Status:requestStatus=INVALID_PASSWORD

4.2. Server InitiatedThis section highlights instructions that are server originated. The account holder canconfigure the client URL to be used using the SMS Gateway portal.

4.2.1. Receive SMS

Page 18: Tawi SMS Gateway Developer Guide

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

Fig 4.2.1: Receive SMS Sequence

Using the gateway callback mechanism, the gateway is able to notify client terminalequipment on incoming SMS. The callback is simply a URL that is called upon as soon asincoming message arrives on a short code. The callback is modifiable from the accountholder’s web interface.

The means used to transfer data on the callback is HTTP POST. If an account holderwishes to disable the callback mechanism, the callback is to be left blank.

Below is a table with the parameters that are passed during an incoming SMS event.

Server Parameters

Name Value DescriptioncallbackType incomingSms This is used to indicate that the gateway is

sending data to the callback because an incomingSMS has arrived destined for the associated shortcode. Callbacks can also be used to transmit othertypes of alerts.

destination A short code number This is the short code number which has receivedan incoming SMS.

source A valid MSISDN This is the phone number that has sent themessage.

Only one source can be present. The URL is calledevery time an SMS is received and presently thereis no option for sending a callback after a certainnumber of incoming SMS have been aggregated.

message A text message This is the text message sent to the short code.Note that it may be blank.

messageId A uniquealphanumeric string

This is the code used to uniquely identify an SMSin the gateway.

network The originatingnetwork

This is the network operator through which themessage was sent. The network mnemonics usedare listed in Appendix A: Network OperatorCoverage

datetime a date and time A date-time of when the message arrived in theSMS Gateway from the MNO. It should will in the

Page 19: Tawi SMS Gateway Developer Guide

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

form: YYYY-MM-DDThh:mm:ss±hh:mm

For example: 2014-06-11T13:54:27+03:00

This follows the ISO 86016 recommendations.

Server Example

http://client.application.com?callbackType=incomingSms&destination=20500&source=254721123456&message=This%20is%20a%20test%20sms&messageId=TeImE1334595755&network=Safaricom_KE&datetime=2014-06-11T13:54:27+03:00

Client Response Parameters

The SMS Gateway does not require any particular response from the Client for thisnotification. The SMS Gateway retries

6 http://en.wikipedia.org/wiki/ISO_8601

Page 20: Tawi SMS Gateway Developer Guide

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

5. Status Codes

5.1. Query Status CodesThese are used to communicate the gateway’s perspective of a client initiated instructionor query.

General Status Codes

These are status codes that may be reported during any client initiated instruction.

Value DescriptionUNKNOWN_USERNAME The username or email used to authenticate is not

registered with the gateway.INVALID_PASSWORD The password supplied does not match the

username.INACTIVE_ACCOUNT The account from which the send or query attempt

has been made is not active. It may be in asuspended or deleted state.

INVALID_PARAMETERS Not enough or invalid parameters have beenprovided when submitting a request to the SMSGateway.

INTERNAL_SERVER_ERROR An internal problem with the gateway has occurredafter initiating a query.

ACCEPTED The server has validated the request parametersand will attempt to deliver the message to itsdestination(s).

Send SMS Status Codes

These are codes that are specific to a Send SMS instruction.

Value DescriptionINVALID_SOURCE The source address is not allowed to be used by the

particular account.INSUFFICIENT_CREDIT The user has exhausted the credits allowed for

sending SMS.INVALID_MESSAGE The message format is invalid, for example there is

no content in the message.

Page 21: Tawi SMS Gateway Developer Guide

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

Query Message Status Codes

These are codes that are specific to a Send SMS instruction.

Value DescriptionUNKNOWN_MESSAGEID The Message Id provided is not recognized by the

system or is not associated with that account.

5.2. Message Status CodesThese represent the various states of a message destined for a mobile phone.

Value DescriptionACCEPTED_FOR_DELIVERY The message has been accepted by the gateway

for delivery.DELIVERY_SUCCESS The delivery to the destination address is

successful.DELIVERY_FAILURE The delivery to the destination address has not

been successful.SMSC_SUBMIT The message has been submitted to the MNO

SMS equipment.SMSC_REJECT The message has been rejected by the MNO SMS

equipment.

Page 22: Tawi SMS Gateway Developer Guide

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

6. Supported Alphanumeric Characters

The following table details whether an alphanumeric character is accepted () or rejected() by the different SMSC operators supported by the Tawi SMS Gateway.

Alphanumeric Character Safaricom Airtel1. ! (exclamation mark)

2. “ (neutral double quotation mark)

3. # (number or pound sign)

4. $ (dollar sign)

5. % (percent sign)

6. & (ampersand)

7. ‘ (apostrophe)

8. ( (left parenthesis)

9. ) (right parenthesis)

10. * (asterisk)

11. + (plus, add sign)

12. , (comma)

13. - (hyphen, minus)

14. . (period)

15. / (slash, solidus)

16. : (colon)

17. ; (semicolon)

18. < (less than sign)

19. = (equal sign)

20. > (greater than sign)

21. ? (question mark)

22. @ (commercial at sign)

23. [ (left bracket)

24. \ (back slash)

25. ] (right bracket)

26. ^ (up arrow)

27. _ (under score)

28. ` (grave accent)

29. { (left curly bracket)

30. |(vertical bar)

31. } (right curly bracket)

32. ~ (tilde)

Page 23: Tawi SMS Gateway Developer Guide

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

7. Appendices

A. Network Operator Coverage

Country MNO / SMS Aggregator Network MnemonicKenya Safaricom Safaricom_KEKenya Airtel Kenya Airtel_KE

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., July 2014**/

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 + "?" +

Page 24: Tawi SMS Gateway Developer Guide

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

"username=" + URLEncoder.encode("michael", "UTF-8") +"&password=" + URLEncoder.encode("mypassword", "UTF-8") +"&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.");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 25: Tawi SMS Gateway Developer Guide

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

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) {socket = serverSocket.accept( );System.out.println("Have received text");is = socket.getInputStream( );

bufferedInputStream = new BufferedInputStream(is);

Page 26: Tawi SMS Gateway Developer Guide

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

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 27: Tawi SMS Gateway Developer Guide

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

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

}

Page 28: Tawi SMS Gateway Developer Guide

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

}

/**** @param servletRequest* @param servletResponse* @throws ServletException, IOException*/

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

doPost(request, response);}

}

Page 29: Tawi SMS Gateway Developer Guide

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

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 30: Tawi SMS Gateway Developer Guide

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

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 31: Tawi SMS Gateway Developer Guide

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

C. References1. Safaricom Kenya

2. Airtel Kenya

3. Communications Commission of Kenya

Page 32: Tawi SMS Gateway Developer Guide