Code Examples

Here you can copy & paste code examples for our API to get started instantly!

Send SMS API

Below is a selection of code examples you can copy and modify to your own purpose. If you need any help, please feel free to contact us.

This example uses the cURL library, please ensure it is enabled on your server.

<?php
// Authorisation details
$uname = "youremailaddress";
$pword = "yourpassword";

// Configuration variables
$info = "1";
$test = "0";

// Data for text message
$from = "Jims Autos";
$selectednums = "440000000000";
$message = "Test with an ampersand (&) and a £5 note";
$message = urlencode($message);

// Prepare data for POST request
$data = "uname=".$uname."&pword=".$pword."&message=".$message."&from=". $from."&selectednums=".$selectednums."&info=".$info."&test=".$test;

// Send the POST request with cURL
$ch = curl_init('http://www.txtlocal.com/sendsmspost.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch); //This is the result from Txtlocal
curl_close($ch);
?>

If you cannot use cURL, you can connect to the API using Sockets.
Replace the last section of code with:

// Send the POST request with Sockets
$url = 'http://www.txtlocal.com/sendsmspost.php';
$params = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $data));
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
$response = stream_get_contents($fp);
echo $response;
<%
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 = "440000000000"
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
%>
<%@ 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=email@domain.com&pword=yourpass&message=hello&from=SMITHS" + "&selectednums=440000000000&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 = Encoding.UTF8.GetByteCount(strPost);
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>
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 TransportUserNameAs String ="me@myemail.com"
    Const TransportPasswordAs String ="mypassword"
    Const TransportVerboseAs 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 responseFromServerAs String = reader.ReadToEnd()
    ' Clean upthe 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", "440000000000", "")
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: Upto 612 characters
Number(s): Comma separated list of numbers in international format (44) followed by the mobile number, without the leading zero
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Class to help send SMS messages
* @author chris
*/
public class SmsHelper {
private static final Log logger = LogFactory.getLog( SmsHelper.class );

private static final String PARAM_USER = "uname";
private static final String PARAM_PASSWORD = "pword";
private static final String PARAM_MESSAGE = "message";
private static final String PARAM_SENDER = "from";
private static final String PARAM_PHONE_NO = "selectednums";
private static final String PARAM_INFO = "info";

/**
* Send an SMS message via the gateway.
* Returns whether or not the message could be successfully sent.
* @param sender
* @param phoneNumber
* @param smsText
* @return
*/
public static boolean sendSMS(final String sender, final String phoneNumber, final String smsText) {
try {
final HttpClient client = new HttpClient();

final HttpMethod method = new GetMethod("https://www.txtlocal.com/sendsmspost.php");

method.setQueryString(new NameValuePair[]{
new NameValuePair(PARAM_USER, "myUsername"),
new NameValuePair(PARAM_PASSWORD, "myPassword"),
new NameValuePair(PARAM_MESSAGE, smsText),
new NameValuePair(PARAM_SENDER, sender),
new NameValuePair(PARAM_PHONE_NO, phoneNumber),
new NameValuePair(PARAM_INFO, "1"),
});

final int statusCode = client.executeMethod(method);
logger.debug("SmsHelper: QueryString>>> "+method.getQueryString());
logger.info("SmsHelper: Status Text>>>"+HttpStatus.getStatusText(statusCode));
return true;
} catch (final Exception e) {
logger.error("Exception sending SMS: "+e.toString());
return false;
}
}

public static void main(final String[] args) {
sendSMS(args[0]/*sender*/, args[1]/*mobileNo*/, args[2]/*message*/);
}
}

We also offer a bulk XML interface for sending different message text to multiple numbers in bulk (great for bulk appointment reminders where each message contains different text):

  • Post to: http://www.txtlocal.co.uk/xmlapi.php
  • 1 SMS tag per submission (1 FROM per submission)
  • Multiple Msg tags
  • ID = a custom ID (if required)
  • rcpurl = a custom receipt URL (if different to control panel default)

In PHP:

<?
$xmlData = '<?xml version="1.0" encoding="ISO-8859-1"?>
<SMS>
<Account Name="yourusername" Password="yourpassword">
<Sender From="Site 3">
<Messages>
<Msg ID="15" Number="440000000000">
<Text>Please come for you appointment tomorrow morning at 12:45</Text>
</Msg>
<Msg ID="16" Number="440000000000">
<Text>Please come for you appointment tomorrow morning at 14:00</Text>
</Msg>
</Messages>
</Sender>
</Account>
</SMS>';
$post = 'data='. urlencode($xmlData);
$url = "http://www.txtlocal.co.uk/xmlapi.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST ,1);
curl_setopt($ch, CURLOPT_POSTFIELDS ,$post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
?>

We do basic checks to ensure that username and password are correct, and calculate if there are sufficient message credits for the job. If either is false we simply return:
echo "Error=Invalid login";
or
echo "Error - insufficient credits. You need: " . $totalcost;

If your FROM is too long (>11) or too short (<3) it will default to whatever is your primary FROM address on your account.

Python

We have a Python script that you can download and configure to send messages through your Txtlocal account.

Download now (sendsms.py - 4KB)
Note: you may need to right-click on the link, and save it to your computer.

ColdFusion

Visit a project page on RIAForge to view a CFC that interacts with our API.
http://txtlocalcfc.riaforge.org/.

Perl

A user has written an excellent Perl library to connect with our API, and released it for free.

View the library on github.

You may also want to read the full documentation to understand how to use this API.

Receive SMS

When configured, we POST the message data to your specified URL. You can pick this up in the following way, using PHP:

<?php
$sender = $_REQUEST['sender'];
$content = $_REQUEST['content'];
$inNumber = $_REQUEST['inNumber'];
$email = $_REQUEST['email'];
$credits = $_REQUEST['credits'];
?>

If you have a Location based Service package, we POST these additional parameters:

<?php
$lat = $_REQUEST['lat'];
$long = $_REQUEST['long'];
$rad = $_REQUEST['rad'];
$lbscredits = $_REQUEST['lbscredits'];
?>

You may also want to read the full documentation to understand how to use this API.

Receipt SMS

We can send a delivery receipt to your server, if you set this option in your control panel. We POST this data to your script, and using PHP you can pick up this data in the following way:

<?php
$number = $_REQUEST['number'];
$status = $_REQUEST['status'];
$customID = $_REQUEST['customID'];
?>

You may also want to read the full documentation to understand how to use this API.

Check Credit Balance

You can check your credit balance by POSTing to us in the following way:

<?php
// Authorisation details
$uname = "youremailaddress";
$pword = "yourpassword";

// Prepare data for POST request
$data = "uname=".$uname."&pword=".$pword; // Send the POST request with cURL
$ch = curl_init('http://www.txtlocal.com/getcredits.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$credits = curl_exec($ch); //This is the number of credits you have left
curl_close($ch);
?>

You may also want to read the full documentation to understand how to use this API.

Inject Numbers

You can inject contact details directly to a group on your Txtlocal account by POSTing to us in the following way:

<?php
// Authorisation details
$uname = "youremailaddress";
$pword = "yourpassword";

// Contact details
$group = "5";
$numbers = "44777000000";

// Prepare data for POST request
$data = "uname=".$uname."&pword=".$pword."&group=".$group."&numbers=".$numbers; // Send the POST request with cURL
$ch = curl_init('http://www.txtlocal.com/tl_inject.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch); //Our API reply
curl_close($ch);
?>

You may also want to read the full documentation to understand how to use this API.