SMS API for Programmers - Code

HTTP POST can be used in all modern programming languages including ASP, ASP.NET, c++, c#, php, VB, VB.NET, command lines, SSH & cURL. The following section outlines how to send messages using either php, ASP, .NET and JAVA. We can provide examples in other languages on request, simply Contact Us at support@txtlocal.com.

- View programming Code To Send SMS Text Messages & WAP Push

- View programming Code To Receive SMS Text Messages

- View programming Code To Receipt SMS Text Messages

Send SMS Text Messages

Meet the simple SMS API variables

info

A flag to switch on/off debug information. The following info is returned when info is set to 1:

Responses:
TestMode= 0 for live, 1 for testing (messages don't go to handset and credits not deducted)
MessageReceived= The received message

URLReceived= The received WAP PUSH URL (not required)

ScheduledDate= The received scheduled SMS time (not required)

Custom= The received custom ID to be passed back in receipt (not required)

From= The received SMS originator. Uses account default if blank

CreditsAvailable= Number of credits at start. You can also call http://www.txtlocal.com/getcredits.php, passing uname and pword to get a credit total.

MessageLength= Length of the message in characters

MessageCount= Number of messages (break at 160, 306, 459, 612)

NumberContacts= The number of comma separted numbers

CreditsRequired= Credits required for job (MessageCount * NumberContacts)

CreditsRemaining= Credits remaining after the job

Errors:
Error=No credit
Error=Not enough credit for send
Error=Invalid login
Error=Message Too Long (>612 characters)
Error=Message not sent. Please check your data - especially the numbers. Are they all in INTERNATIONAL format?

json
If you would prefer to use a more structured response than the line-by-line of info=1, then set info=0,json=1. This will return all the above information is JSON format. This can then be parsed in most modern languages.

test
This is the test mode. If test=1 then messages will not be sent and credits will not be deducted.

address
The url on the Txtlocal server where we receive your messages. This is static and can not be changed. Always use: www.txtlocal.com/sendsmspost.php - preferably using HTTP(s) for your own security.

message
The text message body. This can be up to 612 characters in length. A single message is 160 characters, longer messages are 153 each (2=306,3=459,4=612). You can insert any merge data into this message from your database before submitting to txtlocal. To insert a newline character use %n.

from
The "From Address" that is displayed when the message arrives on handset. Can only be alpha numeric or space. Min 3 chars, max 11 chars.

uname
Your txtlocal.com username

pword
Your txtlocal.com password

selectednums
A comma separated list of international mobile numbers. Each number must be PURELY numeric, no + symbols or hyphens or spaces. The numbers must start with the international prefix. In UK this would be 447xxxxxxxxx. For more prefixes click here.

url
This is not mandatory. If set, you can send a WAP PUSH (mobile internet bookmark) to a mobile phone. Simply set to a valid url (eg, http://www.google.com).

custom
This is not mandetory. If set, you can record a custom ID against the the message batch, which will be passed back in the delivery receipt.

rcpurl
This is not mandetory. Alternate receipt URL. Instead of using the receipt URL in the Txtlocal Account Settings, receipts will be sent to this URL.

shed
This is not mandetory. The scheduled message date/time. In the format YYYY-MM-DD-HH-MM-SS (e.g 2008-03-28-14-56-00). Scheduled messages can be viewed and deleted via your Txtlocal online account.

Send Using PHP

This example uses the cURL library. Please ensure it is enabled on your server. If you can't use cURL then use sockets. See here.

<?php
//set up variables
$info = "1";
$test = "0";
$address = "www.txtlocal.com/sendsmspost.php";
$message = "Hello this is a test with an ampersand (&) and a £5 note";
$message = urlencode($message); //encode special characters (e.g. £,& etc)
$from = "Jims Autos";
$uname = "youremailaddress";
$pword = "yourpassword";
$selectednums = "447740101098";
//build url
$data = "uname=" . $uname . "&pword=" . $pword . "&message=" . $message . "&from=" . $from . "&selectednums=" . $selectednums . "&info=" . $info . "&test=" . $test;
//send messages
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://$address");
//curl_setopt($ch, CURLOPT_URL,"https://$address"); //secure connection
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //use this to suppress output
$result = curl_exec ($ch); //This is the result from Txtlocal - store as required
curl_close ($ch);
?>


Send Using ASP

<%
info = 1
test = 0
message = "Hello this is a test with a £5 note and an ampersand (&) symbol"
message = Server.urlencode(message) 'encode special characters (e.g. £,& etc)
from = "Jims Autos"
address = "https://www.txtlocal.com/sendsmspost.php"
uname = "youremailaddress"
pword = "yourpassword"
selectednums = "447740101098"
url = address & "?uname=" & uname & "&pword=" & pword & "&message=" & message & "&from=" & from & "&selectednums=" & selectednums & "&info=" & info & "&test=" & test

set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "POST", url, false
xmlhttp.send ""
msg = xmlhttp.responseText
response.write(msg)
set xmlhttp = nothing
%>

Send Using C# .NET

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<script language="C#" runat="server">

void Page_Load(Object Src, EventArgs E) {
myPage.Text = readHtmlPage("http://www.txtlocal.com/sendsmspost.php");
}
private String readHtmlPage(string url)
{
String result = "";
String strPost =
"uname=youremail@domain.com&pword=yourpass&message=hello&from=SMITHS"+
"&selectednums=447740101097&info=1";
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);

//add Proxy info if required
//objRequest.Proxy = WebProxy.GetDefaultProxy();
//objRequest.Proxy.Credentials = CredentialCache.DefaultCredentials; //uses logged on user
//objRequest.Proxy.Credentials = new System.Net.NetworkCredential("UserName", "Password"); // Alternative - specify the user and password to use
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally {
myWriter.Close();
}

HttpWebResponse objResponse =
(HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()) )
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
</script>

Send Using ASP .NET

Private Function SendSMS_txtLocal(ByVal Test As Boolean, _
ByVal From As String, _
ByVal Message As String, _
ByVal SendTo As String, _
ByVal URL As String) As String

' Send a message using the txtLocal transport
Const TransportURL As String = "http://www.txtlocal.com/sendsmspost.php"
Const TransportUserName As String = "me@myemail.com"

Const TransportPassword As String = "mypassword"
Const TransportVerbose As Boolean = True
Dim strPost As String
' Build POST String
strPost = "uname=" + TransportUserName _
+ "&pword=" + TransportPassword _
+ "&message=" + Message _
+ "&from=" + From _
+ "&selectednums=" + SendTo
If URL <> "" Then
strPost += "&url=" + URL
End If
If Test = True Then
strPost += "&test=1"
End If
If TransportVerbose = True Then
strPost += "&info=1"
End If
' Create POST
Dim request As WebRequest = WebRequest.Create(TransportURL)
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(strPost)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
' Return result to calling function
If responseFromServer.Length > 0 Then
Return responseFromServer
Else
Return CType(response, HttpWebResponse).StatusDescription
End If
End Function
------
To send a message:
SendSMS_txtLocal(False, "From", "Message", "447nnnnnnnnn", "")
Where the parameters are used as follows:
Test: True if this is a test only (no message is sent)
From: 11 Alpha-numeric characters
Message: Up to 612 characters
Number(s): Comma separated list of numbers in international format (44) followed by the mobile number, without the leading zero
URL: URL to use for WAP PUSH (if required)

Send Using JAVA

import java.io.*;
import java.net.*;
public class HTTPAdaptor {
private static final String domain = "https://www.txtlocal.com/sendsmspost.php";
private static final String userName = "yourusername";
private static final String userPwd = "yourpassword";
private static final String from = "yourfromname";
public void sendSMS(String phoneNumber, String smsText) {
PrintWriter out = null;
try {
StringBuffer postParams = new StringBuffer();
postParams.append("uname=").append(userName).append("&");
postParams.append("pword=").append(userPwd).append("&");
postParams.append("message=").append(smsText.replaceAll(" ", "%20")).append("&");
postParams.append("from=").append(from).append("&");
postParams.append("selectednums=").append(phoneNumber).append("&");
postParams.append("info=1");
System.out.println("SMSGateway - Sending Message [msg:" + smsText + "] [ph:" + phoneNumber + "]");
System.out.println("Post == [" + postParams.toString() + "]");
URL url = new URL(domain + "?" + postParams.toString());
URLConnection conn = url.openConnection();
// conn.setDoOutput(true);

System.out.println("Connected to SMS Gateway");

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();

// conn.setRequestProperty("charset", "UTF-8");
// out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
//
//
// out.write(postParams.toString());

// out.flush();
// out.close();
conn = null;

System.out.println("All Done");

} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
// if (out != null)
// out.close();
} catch (Exception e) {
}
}
System.out.println("Now we're really all done.");
}
}

Receive SMS

To receive an SMS message to your platform, simply add the URL address of the script on your webserver using the Txtlocal account settings page. We will POST the following variables to you:

Sender
The mobile number of the handset

Content
The message content

inNumber
The number the message was sent to (your inbound number)

For Example: In PHP

$content = $_REQUEST["content"];
$sender = $_REQUEST["sender"];
$inNumber = $_REQUEST["inNumber"];

For Example: In ASP
content = Request.Form("content")
sender = Request.Form("sender")
inNumber = Request.Form("inNumber")

Receipt SMS

To receive an SMS message receipt to your platform, simply add the URL address of the script on your webserver using the Txtlocal account settings page. We will POST the following variables to you. Note: you can include *#* within the URL and it will be replaced by the custom field.

number
The mobile number of the handset

status
The message status. Either D for delivered, I for invalid or U for undelivered after 72 hours.

customID
The custom value passed during message send (if used).

For Example: In PHP

$number = $_REQUEST["number"];
$status = $_REQUEST["status"];
$customID = $_REQUEST["custom"];

For Example: In ASP
number = Request.Form("number")
status = Request.Form("status")
customID = Request.Form("custom")