Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Tawi SMS Gateway
Developer Guide
A Product of Tawi Commercial Services Ltd
2015
www.tawi.mobi
info@tawi.mobi
July 2014
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 1
INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTI...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 2
Table of Contents
1. Document Information 3
1.1. Doc...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 3
1. Document Information
1.1. Document History
Releas...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 4
1.4. Glossary
API …………………………………………… Application Prog...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 5
2. Introduction
Tawi Commercial Services Limited is ...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 6
3. API Overview
The Tawi SMS Gateway is a product th...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 7
Safaricom prefixes: 070, 071 and 072;
Airtel prefixe...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 8
4. API Commands
The following section details the co...
Fig 4.1.1. Send SMS Sequence
Web Service Endpoint: http://sms.tawi.mobi/sendsms
Client Request Parameters
Name Value Compulsory Description
username a ...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 1
destinations, ensure that all
target phone numbers a...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 2
http://sms.tawi.mobi/sendsms?username=tawi&password=...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 3
4.1.2. Query Message Status
This API functionality i...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 4
Server Response Parameters
Parameter Value Compulsor...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 5
4.1.3. Query Balance
This gives an opportunity for a...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 6
Example Server Responses
Example of a successful Que...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 7
Fig 4.2.1: Receive SMS Sequence
Using the gateway ca...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 8
form: YYYY-MM-DDThh:mm:ss±hh:mm
For example: 2014-06...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 9
5. Status Codes
5.1. Query Status Codes
These are us...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 10
Query Message Status Codes
These are codes that are...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 11
6. Supported Alphanumeric Characters
The following ...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 12
7. Appendices
A. Network Operator Coverage
Country ...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 13
"username=" + URLEncoder.encode("michael", "UTF-8")...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 14
2. Receive SMS
a. Receive without using Java Applic...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 15
int bytesRead = 0;
// Keep reading till we reach th...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 16
b. Receive using Java Application Server (J2EE)
imp...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 17
}
/**
*
* @param servletRequest
* @param servletRes...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 18
B2. PHP
1. Send SMS
<?php
/**
* This PHP script is ...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 19
2. Receive SMS
<?php
/**
* This is a PHP program th...
Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 20
C. References
1. Safaricom Kenya
2. Airtel Kenya
3....
Tawi SMS Gateway Developer Guide
Upcoming SlideShare
Loading in …5
×

Tawi SMS Gateway Developer Guide

405 views

Published on

Tawi SMS Gateway Developer Guide

Published in: Technology
  • D0WNL0AD FULL ▶ ▶ ▶ ▶ http://1lite.top/ZRDrV5 ◀ ◀ ◀ ◀
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • D0WNL0AD FULL ▶ ▶ ▶ ▶ http://1lite.top/ZRDrV5 ◀ ◀ ◀ ◀
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

Tawi SMS Gateway Developer Guide

  1. 1. Tawi SMS Gateway Developer Guide A Product of Tawi Commercial Services Ltd 2015 www.tawi.mobi info@tawi.mobi July 2014
  2. 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. 2nd Floor, Twiga Towers Murang’a Road, Nairobi CBD P.O. Box 20222 – 00100 Nairobi, Kenya
  3. 3. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 2 Table of Contents 1. 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
  4. 4. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 3 1. Document Information 1.1. Document History Release Date Author Comments Revision 1 Jun 2014 Michael Wakahe 1st Working Version 1.2. Document Conventions N/A 1.3. Related Documents The following are other documents pertaining to SMS services offered by Tawi Commercial Services Ltd:  Tawi SMS Gateway Overview  SMS Application Form  Information Confidentiality Agreement  Terms and Conditions
  5. 5. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 4 1.4. Glossary API …………………………………………… Application Programmer Interface CAK ………………………………………….. Communications Authority of Kenya HTTP ………………………………………... Hyper Text Transfer Protocol MNO ……................................................... Mobile Network Operator e.g. Safaricom 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
  6. 6. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 5 2. Introduction Tawi Commercial Services Limited is a Kenyan based software development company specializing in mobile technologies. These include short codes, bulk SMS, USSD and electronic airtime. Tawi offers Premium Rate Services with Safaricom1 Kenya and Airtel2 Kenya. This implies 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 SMS interactivity 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 SMS Gateway Overview 1 http://www.safaricom.co.ke 2 http://africa.airtel.com/kenya
  7. 7. 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 parties to 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 the sending and receiving of SMS remotely. The gateway is accessible through the URL http://sms.tawi.mobi. Internally, the gateway has many features to guarantee that it works correctly, including no messages lost in transit, a continuous best effort approach to deliver the messages to the operator SMS centres and security to prevent unwarranted sending of SMS. It allows businesses and other institutions to remotely monitor their individual accounts. In this manner, an institution can be concerned only with creating and maintaining its own business logic in software and using the gateway to send and receive SMS which abstract the underlying network complexities in the interaction with bulk SMS and short codes. The API utilizes HTTP GETs and POSTs with key-value pairs. POSTs are preferred over GETs due to their higher security as well as ability to transmit more data. Security such as HTTP over a secure socket layer (HTTPS) and data encryption using asymmetric keys will 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:
  8. 8. 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 belong to the Safaricom network. Number portability has now been introduced in Kenya. This implies that any MSISDN may be associated with any network operator. The other network operators in Kenya are Orange3 and Yu (Essar)4. Presently there is no means to determine beforehand which operator a number belongs to. Bulk and premium SMS can only terminate on Kenyan telco issued SIM cards. 3 http://www.orange.co.ke 4 http://www.yu.co.ke
  9. 9. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 8 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. 4.1. Client Initiated These are commands which are launched by the client application. 4.1.1. Send SMS This is the command to send a single or multiple SMS through the gateway.
  10. 10. Fig 4.1.1. Send SMS Sequence
  11. 11. Web Service Endpoint: http://sms.tawi.mobi/sendsms Client Request Parameters Name Value Compulsory Description username a username Yes A valid username that is permitted to send SMS. 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. source short code number or mask Yes The short code or mask which will be used as the origin of this SMS. The source address (from), also known as the Sender Id, can be either a valid short code (for example 20240), or an alphanumeric string. These must be registered within your online account and approved by Tawi before they may be used. destination MSISDN Yes Destination of this SMS. 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 can be specified by separating them with a semicolon. For example, setting destination as “254720123456; 254721123456;254722123456” will have the message sent to these three destinations. When sending to multiple
  12. 12. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 1 destinations, ensure that all target phone numbers are on the same network. message an SMS message Yes The text to be sent to the target phone number. Message should be URL encoded using the UTF-8 scheme. Messages longer than 160 characters are concatenated. However the recipient may be billed more than once if the source is a short code. Bulk SMS credits are deducted if they are used, the count will be in multiples of 160 characters. The message cannot be empty. network an MNO mnemonic for example “Safaricom_KE” Yes To indicate the network to direct the SMS 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. Example Request The first example below sends the SMS to a single destination whereas the second sends to multiple destinations. http://sms.tawi.mobi/sendsms?username=tawi&password=info&source=20240&destinatio n=254728123456&message=This%20is%20a%20test.&network=safaricom_ke
  13. 13. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 2 http://sms.tawi.mobi/sendsms?username=tawi&password=info&source=20240&destinatio n=254721123456;254722123456;254723123456&message=This%20is%20a%20test.&netw ork=safaricom_ke Server Response Parameters Parameter Value Compulsory Description requestStatus a status Yes A status indicating whether the server accepted the request or not. messageIds text No A Message Id is a unique identifier for a send SMS request. It is generated by the server and can be referenced in future. The value here will be a list of MSISDNs and the corresponding Message Id. The MSISDN(s) are the ones supplied in the destination 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;2547287654 32:Tgfu1334593572;254722543210: rGatF1325073545 Example of an unsuccessful Send SMS response: requestStatus=INSUFFICIENT_CREDIT
  14. 14. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 3 4.1.2. Query Message Status This API functionality is provided for one to be able to determine the status of an Outgoing SMS. The SMS changes state as it goes through the network to its final destination. This command is not applicable to Incoming SMS. The status returned is the current one only. The past statuses of the message are not included in this particular command. The information retrieved also includes the time of status change. For more information on a particular message, refer to the Outgoing SMS table on the web interface. The API can be called any time after a message has been successfully accepted for delivery. Below are instructions on how to use this functionality. Web Service Endpoint: http://sms.tawi.mobi/querystatus Client Request Parameters Name Value Compulsory Description username a username Yes A valid username that is permitted to send SMS. Should be URL encoded using the UTF-8 scheme. password a password Yes A valid password that matches the username above. Should be URL encoded using the UTF-8 scheme. messageId a valid Message Id Yes This is the Message Id that is produced when the SMS gateway successfully accepts a message for delivery. Example Request This is an example of a Query Status. http://sms.tawi.mobi/querystatus?username=tawi&password=info&messageId=TeImE13 34595755
  15. 15. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 4 Server Response Parameters Parameter Value Compulsory Description requestStatus a status Yes A status indicating whether the server accepted the request or not. messageStatus text No A message status code as indicated in section 5.2: Message Status Codes. datetime a date and time No A date-time of when the message changed to this status. 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 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
  16. 16. 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 that are available in the gateway. These are listed against the MNOs that are configured in the 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 Description username a username Yes A valid username that is permitted to send SMS. Should be URL encoded using the UTF-8 scheme. password a password Yes A valid password that matches the username above. Should be URL encoded using the UTF-8 scheme. 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 Description requestStatus 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 with corresponding balances in integer values. The MNO mnemonics are listed in Appendix A: Network Operator Coverage.
  17. 17. 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 and Airtel Kenya networks. The account also has an SMS Mask Info on the Safaricom network. Example of an unsuccessful Query Status: requestStatus=INVALID_PASSWORD 4.2. Server Initiated This section highlights instructions that are server originated. The account holder can configure the client URL to be used using the SMS Gateway portal. 4.2.1. Receive SMS
  18. 18. 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 terminal equipment on incoming SMS. The callback is simply a URL that is called upon as soon as incoming message arrives on a short code. The callback is modifiable from the account holder’s web interface. The means used to transfer data on the callback is HTTP POST. If an account holder wishes 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 Description callbackType incomingSms This is used to indicate that the gateway is sending data to the callback because an incoming SMS has arrived destined for the associated short code. Callbacks can also be used to transmit other types of alerts. destination A short code number This is the short code number which has received an incoming SMS. source A valid MSISDN This is the phone number that has sent the message. Only one source can be present. The URL is called every time an SMS is received and presently there is no option for sending a callback after a certain number 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 unique alphanumeric string This is the code used to uniquely identify an SMS in the gateway. network The originating network This is the network operator through which the message was sent. The network mnemonics used are listed in Appendix A: Network Operator Coverage datetime a date and time A date-time of when the message arrived in the SMS Gateway from the MNO. It should will in the
  19. 19. 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=25 4721123456&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 this notification. The SMS Gateway retries 6 http://en.wikipedia.org/wiki/ISO_8601
  20. 20. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 9 5. Status Codes 5.1. Query Status Codes These are used to communicate the gateway’s perspective of a client initiated instruction or query. General Status Codes These are status codes that may be reported during any client initiated instruction. Value Description UNKNOWN_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 a suspended or deleted state. INVALID_PARAMETERS Not enough or invalid parameters have been provided when submitting a request to the SMS Gateway. INTERNAL_SERVER_ERROR An internal problem with the gateway has occurred after initiating a query. ACCEPTED The server has validated the request parameters and will attempt to deliver the message to its destination(s). Send SMS Status Codes These are codes that are specific to a Send SMS instruction. Value Description INVALID_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.
  21. 21. 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 Description UNKNOWN_MESSAGEID The Message Id provided is not recognized by the system or is not associated with that account. 5.2. Message Status Codes These represent the various states of a message destined for a mobile phone. Value Description ACCEPTED_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.
  22. 22. 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 Airtel 1. ! (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)  
  23. 23. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 12 7. Appendices A. Network Operator Coverage Country MNO / SMS Aggregator Network Mnemonic Kenya Safaricom Safaricom_KE Kenya Airtel Kenya Airtel_KE 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., 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 + "?" +
  24. 24. 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; } }
  25. 25. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 14 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) { socket = serverSocket.accept( ); System.out.println("Have received text"); is = socket.getInputStream( ); bufferedInputStream = new BufferedInputStream(is);
  26. 26. 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 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( ); } } } }
  27. 27. 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")); }
  28. 28. 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); } }
  29. 29. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 18 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); ?>
  30. 30. 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: $callbackTypensource: $sourcendestination: $destinationnmessage: $message nmessageId: $messageIdnnetwork: $network"; fwrite($fh, $stringData); fclose($fh); ?>
  31. 31. Copyright © Tawi Commercial Services Ltd 2015. All rights reserved. 20 C. References 1. Safaricom Kenya 2. Airtel Kenya 3. Communications Commission of Kenya

×