January 2015 SMS REST API

Transcription

January 2015SMS REST API Copyright Clickatell Pty. Ltd.

Contents1.Overview . 32.Using the SMS REST API . 32.1 Send your first message. 42.2 HTTP headers explained . 42.3 Security . 42.4 Authenticating . 53.Send message. 53.1 JSON . 53.2 XML . 63.3 Sample code . 74.Stop message . 84.1 JSON . 84.2 XML . 94.3 Sample code . 95.Retrieve balance . 105.1 JSON . 115.2 XML . 115.3 Sample code . 116.Get coverage command . 126.1 JSON . 136.2 XML . 136.3 Sample code . 147.Message status command . 158.Overview of the REST API features . 159.Response status codes . 1710.API Error Codes . 17 Copyright Clickatell Pty. Ltd.

1. OverviewThis real-time SMS API is built to the very best practice architecture guidelines for RESTful API design. Idealfor developers anticipating a deeper and more extensive integration solution, you can send batches of upto 500 destination numbers per submission in real-time through our international SMS messaging gateway.Interact with Clickatell using JSON or XML.Why use this API? Extremely reliable and convenient to use, with an intuitive, hierarchical, and consistent structure,supported by embedded resource links. Version control mechanisms to allow for future upgrades. Allows for the sending of multi-language Unicode message. Simplified token-based authentication on all API commands. Embedded resource links to our online technical documents. Schedule a message to be sent at a specific time, of up to 7 days ahead. Full two-way messaging capabilities. Delivery acknowledgment and Sender ID can be set up. Supports extended length messages. Provides the ability to receive real-time message status notifications to your system.When to use this APIThe REST API is ideal for improving customer service and delighting your customers by using informationfrom your existing CRM system.2. Using the SMS REST APISMS messages are sent by making HTTP or HTTPS calls to the API. You can loop through your list of mobilenumbers and make HTTP/S requests to send SMS messages to them. Generally, this API should allow youto submit up to about 100 messages per second to our platform on average (or faster if required).It’s quick to get started and there is no need to understand the additional or advanced features unless youwant to use them. Supports JSON and XML data formats. Supports HTTP (port 80) and HTTPS (port 443). You can send to multiple handsets in one single HTTP/S request (up to 200) – this is useful if youare sending the same message text to all handsets. Supports persistent connections (keep-alive) and the use of multiple concurrent connections. Various HTTP status codes are used. Click here to view the list. Copyright Clickatell Pty. Ltd.

2.1 Send your first message Step 1: Replace the example authentication token below with your token. Step 2: Replace the example mobile numbers below with your number, using the correctinternational format. This means:oThe mobile number needs to start with the correct country code.oThere must be no spaces or other non-numeric characters.oIf the mobile number starts with zero, remove the zero before typing the rest of thenumber. Step 3: Type your message text. Please note that until you make a purchase, your messages willcontain pre-defined content.curl -X POST \-H "X-Version: 1" \-H "Content-Type: application/json" \-H "Accept: application/json" \-H "Authorization: Bearer YourAuthorizationTokenHere" \-d '{"text":"My message","to":["2799900001","2799900002"]}' \https://api.clickatell.com/rest/message2.2 HTTP headers uired to authenticate your API requests.The authentication token for this header isdisplayed in your Developers’ Centralaccount.Authorization: Bearer4ZnXsl.LcQrDl4ZHWBt6 pecifies which version of the API to use.X-Version:1Content-TypeAcceptUsed to indicate whether you are submittingdata in JSON or XML format.Supports application/json and application/xml. There is currently no support for x-wwwform-urlencoded.Used to indicate if you want a JSON or XMLresponse format. Defaults to JSON if notspecified. If specified, the API expectsapplication/json,application/xml or */*.2.3 SecurityFor added security, you can opt to: Use HTTPS for all API requests.Enable IP lockdown on your API connection. Copyright Clickatell Pty. Ltd.Content-Type: application/jsonAccept: application/json

2.4 AuthenticatingAll authentication is done using an authentication token (generated within Developers’ Central account).This token needs to be passed onto every REST API call. The header used for this is explained in the sectioncalled ‘HTTP Headers Explained’.3. Send messageThis command allows you to send one or more SMS messages. To send messages to your database ofmobile numbers, you can call this command in a loop.The server will respond with a unique identifier for each message (referred to as an API message ID). ThisAPI message ID can be used to track and monitor the status of your message (see Message status commandsection). You can also send to multiple handsets in one single HTTP/S request (up to 600 messages). This isuseful if you are sending the same message text to all handsets.For high volume messaging, we encourage the use of persistent (keep-alive) HTTP/S connections. Multipleconcurrent HTTP/S connections may also be used for additional performance.POST https://api.clickatell.com/rest/messageNote: the REST API may respond with various HTTP status codes. See the full list in the Response statuscodes section.3.1 JSONRequestPOST /rest/message HTTP/1.1HOST: api.clickatell.comX-Version: 1Content-Type: application/jsonAuthorization: Bearer [Your Authorization Token]Accept: application/json{"text":"Test Message","to":["2799900001", "2799900002"]}ResponseHTTP/1.1 202 AcceptedContent-Type: application/json{"data":{"message":[{ Copyright Clickatell Pty. Ltd.

1f3b7d2aaca2aaf362"}]}}3.2 XMLRequest1 POST /rest/message HTTP/1.12 HOST: api.clickatell.com3 X-Version: 14 Content-Type: application/xml5 Authorization: Bearer [Your Authorization Token]6 Accept: application/xml7 ?xml version "1.0"? 8 request 9 data 10 text Test Message /text to 2799900001 /to 1112 /data 13 /request Response1 HTTP/1.1 202 Accepted2 Content-Type: application/xml3 ?xml version "1.0"? 4 response data 5 message 6 accepted 1 /accepted 7 to 2799900001 /to 8 apiMessageId 93f924cad9664cfbb0c6ab03a3032ef0 /apiMessageId 9 /message 10 /data 1112 /response Copyright Clickatell Pty. Ltd.

3.3 Sample codecURLto "[\" mobile number \"]"message "Test Message"authToken " place auth token here "curl -X POST \-H "X-Version: 1" \-H "Content-Type: application/json" \-H "Accept: application/json" \-H "Authorization: Bearer authToken" \-d "{\"text\":\" message\",\"to\": to}" \https://api.clickatell.com/rest/messagePython1 import httplib2, json23 to ["mobile number"]4 message "Test Message"5 authToken ""67 resp, content m/rest/message",8"POST",9body rs {14"X-Version" : "1",15'Content-Type':'application/json',16"Accept" : "application/json",1718"Authorization" : "Bearer " authToken19}20 )PHP12345678 ?php to "[\" mobile number \"]"; message "Test Message"; authToken " place auth token here "; ch curl init(); Copyright Clickatell Pty. Ltd.

9 curl setopt( ch,CURLOPT URL,"https://api.clickatell.com/rest/message");10 curl setopt( ch, CURLOPT RETURNTRANSFER, 1);11 curl setopt( ch, CURLOPT POST, 1);12 curl setopt( ch, CURLOPT POSTFIELDS, "{\"text\":\" message\",\"to\": to}");13 curl setopt( ch, CURLOPT HTTPHEADER, array("X-Version: 1",14"Content-Type: application/json",15"Accept: application/json",16"Authorization: Bearer authToken"17));181920 result curl exec ( ch);21 ? 4. Stop messageThis command will attempt to stop the delivery of a particular message. This command can only stopmessages that have been scheduled for delivery in the future or may be queued within our router. It cannotstop messages that have already been delivered to an SMSC.DELETE https://api.clickatell.com/rest/message/[message ID]Note: the REST API may respond with various HTTP status codes. See the full list in the Response statuscodes section.4.1 JSONRequestDELETE /rest/message/360586640fe9846954897dffe6c13dfc HTTP/1.1HOST: api.clickatell.comX-Version: 1Authorization: Bearer [Your Authorization Token]Accept: application/jsonResponseHTTP/1.1 200 OKContent-Type: application/json{"data" : {"messageStatus" : "006","description" : "User cancelled message delivery","apiMessageId" : "360586640fe9846954897dffe6c13dfc"}} Copyright Clickatell Pty. Ltd.

4.2 XMLRequest1 DELETE /rest/message/360586640fe9846954897dffe6c13dfc HTTP/1.12 HOST: api.clickatell.com3 X-Version: 14 Authorization: Bearer [Your Authorization Token]5 Accept: application/xmlResponse1 HTTP/1.1 200 OK2 Content-Type: application/xml34 ?xml version "1.0"? 5 response data 6 messageStatus 006 /messageStatus 7 description User cancelled message delivery /description 8 apiMessageId b09e1b1bdb5a070c978f03b6836b955c /apiMessageId 9 /data 1011 /response 4.3 Sample codecURLmsgId ""authToken ""curl -X DELETE \-H "X-Version: 1" \-H "Accept: application/json" \-H "Authorization: Bearer authToken" \https://api.clickatell.com/rest/message/ msgIdPython1 import httplib2, json23 msgId ""45 authToken ""6 Copyright Clickatell Pty. Ltd.

7 resp, content om/rest/message/" msgId,9"DELETE",10headers {11"X-Version" : "1",12"Accept" : "application/json",13"Authorization" : "Bearer " authToken14}15 )PHP1 ?php23 msgId " api message ID ";45 authToken " place auth token here ";67 ch curl init();89 curl setopt( ch, CURLOPT URL, "https://api.clickatell.com/rest/message/ msgId");10 curl setopt( ch, CURLOPT RETURNTRANSFER, 1);11 curl setopt( ch, CURLOPT CUSTOMREQUEST, "DELETE");12 curl setopt( ch, CURLOPT HTTPHEADER, array(13"X-Version: 1",14"Accept: application/json",15"Authorization: Bearer authToken"16 ));1718 result curl exec ( ch);1920 ? 5. Retrieve balanceThis will show the number of credits available on your account.GET e: the REST API may respond with various HTTP status codes. See the full list in the Response statuscodes section. Copyright Clickatell Pty. Ltd.

5.1 JSONRequestGET /rest/account/balance HTTP/1.1HOST: api.clickatell.comX-Version: 1Authorization: Bearer [Your Authorization Token]Accept: application/jsonResponseHTTP/1.1 200 OKContent-Type: application/json{"data":{"balance":"300.50"}}5.2 XMLRequestGET /rest/account/balance HTTP/1.1HOST: api.clickatell.comX-Version: 1Authorization: Bearer [Your Authorization Token]Accept: application/xmlResponse1 HTTP/1.1 200 OK2 Content-Type: application/xml34 ?xml version "1.0"? 5 response data 67 balance 300.50 /balance 8 /data 9 /response 5.3 Sample codecURLauthToken ""curl -X GET \-H "X-Version: 1" \-H "Accept: application/json" \ Copyright Clickatell Pty. Ltd.

-H "Authorization: Bearer authToken" thon1 import httplib2, json23 authToken "place auth token here"45 resp, content m/rest/account/balance",6"GET",7headers {89"X-Version" : "1",10"Accept" : "application/json",11"Authorization" : "Bearer " authToken12}13 )PHP1 ?php23 authToken " place auth token here ";45 ch curl init();67 curl setopt( ch,CURLOPT URL, ;8 curl setopt( ch, CURLOPT RETURNTRANSFER, 1);array(9 curl setopt( ch, CURLOPT HTTPHEADER,10"X-Version: 1",11"Accept: application/json",12"Authorization: Bearer authToken"13 ));1415 result curl exec ( ch);1617 ? 6. Get coverage commandThis command allows you to check our coverage of a network or mobile number without sending a messageto that handset. This command should NOT be used before sending each message.The returned credit charge value indicates the lowest possible credit charge at that point in time for a singleplain-text message. Credit charges may fluctuate based on the availability of delivery routes and features,and there is no guarantee that all your messages will be charged this value.GET ote: the REST API may respond with various HTTP status codes. See the full list here. Copyright Clickatell Pty. Ltd.

6.1 JSONRequestGET /rest/coverage/27999123456 HTTP/1.1HOST: api.clickatell.comX-Version: 1Authorization: Bearer [Your Authorization Token]Accept: application/jsonResponseHTTP/1.1 200 OKContent-Type: application/json{"data": {"routable" : true,"destination" : "27999123456","minimumCharge" : 0.8}}6.2 XMLRequest1 GET /rest/coverage/27999123456 HTTP/1.12 HOST: api.clickatell.com3 X-Version: 14 Authorization: Bearer [Your Authorization Token]5 Accept: application/xmlResponse1 HTTP/1.1 200 OK2 Content-Type: application/xml34 ?xml version "1.0"? 5 response 6 data 7 routable 1 /routable 8 destination 27999123456 /destination 9 minimumCharge 0.8 /minimumCharge 10 /data 11 /response Copyright Clickatell Pty. Ltd.

6.3 Sample codecURLnumber ""authToken ""curl -X GET \-H "X-Version: 1" \-H "Accept: application/json" \-H "Authorization: Bearer authToken" \https://api.clickatell.com/rest/coverage/ numberPython1 import httplib2, json23 to ""45 authToken ""67 resp, content m/rest/coverage/" to,8"GET",9headers {10"X-Version" : "1",1112"Accept" : "application/json",13"Authorization" : "Bearer " authToken14}15 )PHP1 ?php23 mobileNumber " mobile number ";45 authToken " place auth token here ";67 ch curl init();89 curl setopt( ch,CURLOPT URL, "https://api.clickatell.com/rest/coverage/ mobileNumber");10 curl setopt( ch, CURLOPT RETURNTRANSFER, 1);11 curl setopt( ch, CURLOPT HTTPHEADER, array("X-Version: 1",12"Accept: application/json",1314"Authorization: Bearer authToken"15 ));1617 result curl exec ( ch);1819 ? Copyright Clickatell Pty. Ltd.

7. Message status commandThere are multiple ways to track your message delivery status and charges: View reports in your Developers’ Central account (these can also be exported to a CSV file); Enable the Callback system, which will automatically push HTTP requests to your server wheneverthe status of a message changes. The HTTP request will contain information about the messagestatus and charge. This is triggered in near real-time. Use the Query Message API command to query the status of a single message.The Callback system is the most efficient (and preferred) option, as it does not require you to poll oursystem to track the progress of a message.8. Overview of the REST API featuresA variety of messaging and SMS features are supported by the gateway and can be activated by includingadditional parameters. These parameters include the ones stated in the table below:FeatureBinaryClient MessageIDConcatenationDelivery QueueDestinationAddressEnable CallbackGatewayEscalationDescriptionForce the message contentto be sent as binary (8-bit)data.Client message ID defined byuser for message tracking.Specifies the maximumnumber of message partsavailable for the message.Delivers the messagethrough one of three queuesassigned to each clientaccount. Messages in thehighest priority queue will bedelivered first.The mobile number of thehandset to which themessage must be delivered(MSISDN). The number mustbe in international formatwith no leading zeros or symbol.Enables you to receivemessage delivery statusupdates via an HTTP requestmade to your server.Prompts an escalation to analternative (more expensive)route, if messages arequeued or delayed on theleast-cost route. Copyright Clickatell Pty. Ltd.ValuesDefaultParameter0, 10binary2993b6b548noneclientMessageId1, 2, 3Defaults tosetting onyour APIconnectionmaxMessageParts1, 2, 33userPriorityQueue27831234567(South 3,4,5,6,70callback0, 10escalate

MaximumCreditsMessage TextMessage ender IDUnicodeMessageUser DataHeaderValidity PeriodBypass DNCCheckOverrides the maximumcharge specified online in“routing profiles”.The content of your SMSmessage.Send other types ofmessages such as flashmessages.This is only applicable toclients that have subscribedto a two-way messagingservice. We route via predefined carriers to enablethe ability for a reply to bereceived back.Some parameters andfeatures are not set as“required” by default andmay be dropped if the leastcost route does not supportthem. Set this parameter toensure that the features setwhen an SMS is sent aresupported by the gatewayused.Specify when a messageshould get delivered inGMT 0.The source/sender addressthat the message will appearto come from (also known asthe “Sender ID”). These mustbe registered within youronline account and approvedby us before they may beused. Two-way numbersrented from us do notrequire approval.Two-digit language code.Convert your text to Unicode[UCS-2 encoding].See http://www.Unicode.org/.Set the UDH content of amessage.The validity period inminutes relative to the timeat which the SMS wasreceived by our gateway.The message will not bedelivered if it is still queuedon our gateway after thistime period.Feature to bypass the DNClookup. Default behavior isto do a lookup unlessoverridden by this Copyright Clickatell Pty. Ltd.0.8,1,1.5,2,2.5,3nonemaxCreditsHello WorldtextRefer todescriptiontype0, 10moRefer 0ZnonescheduledDeliveryTimenonefrom0unicode0, 1udh2524 hoursvalidityPeriod0, 1nonebypassDNCCheck

parameter. A value of “0”will still force a lookup; avalue of “1” will force alookup bypass.9. Response status codesThe REST API may respond with any of the following HTTP status codes:StatuscodeDescriptionDetail200OKThe request was successfully completed.202AcceptedThe message(s) will be processed.207Multi-status400Bad request401Unauthorized402Payment requiredYou do not have enough credits to send messages.404Not foundThe action was performed on a resource that does not exist.405Method not allowedHTTP method is not supported on the resource.410GoneThe mobile number is blocked, delisted, or cannot be routed.429Too many requestsGeneric rate-limiting error.503Service unavailableA temporary error has occurred on our platform – pleaseretry.More than one message was submitted to the API, however,not all messages have the same status.Validation failure (such as missing/invalid parameters orheaders).Authentication failure. This can also be caused by IPlockdown settings.10. API Error CodesErrorCodeDescriptionDetailed Description001AuthenticationfailedAuthentication details areincorrect.IP lockdownviolationYou have locked down the APIinstance to a specific IP addressbut attempted to send from anIP address different to the oneyou have set.007 Copyright Clickatell Pty. Ltd.SolutionYou can edit the setting toinclude your new server’s IPaddress or remove the IPlockdown completely withinDevelopers’ Central’s APIsettings.

ErrorCodeDescriptionDetailed DescriptionSolution100DatamalformedThe JSON/XML data submitted isinvalid.Check that the syntax of yourrequest has been formulatedcorrectly and resubmit.101Invalid ormissingparametersOne or more parameters aremissing or invalid.102Invalid userdata headerThe format of the user dataheader is incorrect.Ensure valid UDH data is beingpassed to the API.The destination address you areattempting to send to is invalid.Check that the number of thehandset that you areattempting to send a messageto is valid. The number shouldbe in an international format,without a ‘00’ prefix or leading‘ ’ symbol OR begin with a ‘0’ ifthe default country prefix isenabled on your API.Invalid sourceaddressThe specified sender address isincorrect.The address that the message issent ‘from’ has been specifiedincorrectly. If you are using aSender ID as your sourceaddress, ensure that it has beenregistered within your onlineDevelopers’ Central account.108Invalid ormissing API IDThe API ID is either incorrect orhas not been included in the APIcall.Include the correct API productID in your query. You can checkthe ID that is associated withyour API by logging into yourDevelopers’ Central account.109Missingmessage IDThis may refer to either a clientmessage ID or API message ID –for example, when using the‘stop message’ command.Maximummessage partsexceededThe text component of themessage is greater than thepermitted 160 characters (70Unicode characters). Viewthe concatenation page for helpin resolving this issue.Cannot routemessageThis implies that the gateway isnot currently routing messagesto this network prefix. Pleaseemail support@clickatell.com withthe mobile number in question.105106113114Invaliddestinationaddress Copyright Clickatell Pty. Ltd.Set concat equal to 1,2,3-N toovercome this by splitting thecontent across multiplemessages.View concatenation information.

ErrorCodeDescriptionDetailed DescriptionSolution116Invalid unicodedataThe format of the Unicode dataentered is incorrect.Ensure that the Unicode formatis correct and resubmit yourquery.120clientMessageIdcontainsspace(s)Your specified client message IDcontains a space. Spacecharacters in client message IDsare not currently supported.The delivery time must beentered in minutes up to amaximum of 7 days.121Destinationmobile numberblockedThis number is not allowed toreceive messages from us andhas been put on our blocked list.122Destinationmobile optedoutThe user has opted out and is nolonger subscribed to yourservice.123Invalid SenderIDThe sender ID is not valid or hasnot been approved.128NumberdelistedThis number has been delistedand cannot receive ourmessages.130Maximum MTlimit exceededuntil UNIXTIMESTAMP This error is returned when anaccount has exceeded themaximum number of MTmessages that can be sent dailyor monthly. You can sendmessages again on the dateindicated by the UNIXTIMESTAMP.160HTTP method isnot supportedon this resourceAn unsupported HTTP methodhas been performed on theresource. Example: HTTP POSTon the Coverage resource.161Resource doesnot existYou are attempting to access aREST API resource that does notexist.165Invalid or noversion headerspecifiedThe expected header thatspecifies version was either notfound or is invalid. Copyright Clickatell Pty. Ltd.A sender ID needs to beregistered and approved beforeit can be successfully used inmessage sending.The response MUST include aContent-Type header thatcontains a valid method for therequested resource.Before continuing, make surethat the correct version isincluded in the submittedheader. The header to use is XVersion: 1

ErrorCodeDescriptionDetailed Description166Invalid acceptheaderspecifiedThe optional header thatspecifies acceptable contentdoes not contain an allowedvalue.Solution167Invalid or nocontent-typespecifiedThe expected header thatspecifies content-type contentwas either not found or did notcontain an allowed value.Before continuing, make surethat an allowed value isincluded in the submittedcontent-type header. Theallowable content-type headervalues are ‘application/json’ orapplication/xml’.250Destinationaddress is onDNC list – Donot contactreceiverDNC lookup for the destinationaddress result shows that thereceiver should not becontacted.Use the “bypass dnc check”(this name varies for APIs)request parameter to bypassthe DNC check.301No credit leftInsufficient credits.Log in to your Developers’Central account and purchaseadditional credits.901Internal error –please retryAn error occurred on ourplatforms.Please retry submitting themessage. This should beexceptionally rare. Copyright Clickatell Pty. Ltd.

2. Using the SMS REST API SMS messages are sent by making HTTP or HTTPS calls to the API. You can loop through your list of mobile numbers and make HTTP/S requests to send SMS messages to them. Generally, this API should allow you to submit up to about 100 messages per second to our platform on average (or faster if required).