API Helper Libraries and Plugins Introduction

The World Text REST API is language agnostic, designed for use from any software or language capable of making HTTP calls.

The World Text REST API is able to query a selection of resources, make groups, add and remove numbers from groups, and send SMS text messages to individual or groups of numbers.

In creating these libraries we have encapsulated the API calls such that you don't need to be concerned directly with URLs, resources, the API calls themselves, or processing the raw JSON responses.

Depending on the calls used, responses can still be in a JSON-like format, but pre-processed where it is sensible to do so.

Design Ethos

We've deliberately kept the classes fairly strongly tied to the HTTP REST API. All classes, except the exception class, are instantiated via a static factory pattern method in the appropriate class.

The API libraries make it easier for you to use the World Text REST API from the language of your choice.

All libraries are open source, BSD licensed, hosted on Github, so if you want to extend, encapsulate the API differently, fix a bug, or even refactor the code a little, we'd be delighted to have you contribute to the project.

C# Helper Classes Introduction

The World Text REST API is able to query a selection of resources, make groups, add and remove numbers from groups, and send SMS text messages.

The code encapsulates the API similarly to the PHP library, with specific data types defined to encapsulate returned data.

Within the class the account ID and API key are set as constants within the class. You'll need to update this with your account details.

We provide the code for convenience and example - we offer no direct support on client contributed code.

Using the C# class

Using the classes is pretty straightforward: You'll need to instantiate whichever classes you need, based upon which parts of the API your app needs.

At the simplest level you'll likely be using instances of Outgoing.SMS.SMSMessage, along with Outgoing.Group.Send for groups, and whichever other objects you need to populate and manage the group.

You'll need to catch exceptions coming back from the classes as there is no exception processing within the classes aside from those coming back from HttpWebResponse.

Send an SMS Text Message

OK, here's the minimum necessary to send a text message:

                        
                        // Replace id and apiKey with values from http://www.world-text.com/account/
                        
                        WorldTextSms sms = WorldTextSms.CreateSmsInstance( "your account ID", "your API key" );
                        
                        // First, simplest possible test:  Send an SMS...
                        try
                        {
                            List<JMessage> status = sms.send("447598495904", "World Text, for reliable SMS text messaging" );
                            
                            foreach (var obj in status)
                            {
                                Console.WriteLine("  :   state : {0}", obj.state);
                                Console.WriteLine("  : dstaddr : {0}", obj.dstaddr);
                                Console.WriteLine("  :   msgid : {0}", obj.msgid);
                                Console.WriteLine("  : credits : {0}", obj.credits);
                            }
                        }
                        catch ( WorldTextException ex )
                        {
                            
                        }
                        
                        // Catch all exceptions and process ...
                        catch ( Exception ex )
                        {
                            throw;
                        }
                     

Notes on Exception Handling

Some small, but important, exception handling points are discussed over at World Text example C# source code.

Exception Handling: Good Practice

This should be well known to all developers, but it's always worth reiterating. For any developer working within a framework it is essential that the top level app catch exceptions reliably and consistently.

The World Text C# classes have a specific exception: WorldTextException which is typically, but not always, relating to API errors.

Framework calls can throw exceptions, and the only ones caught are those that can be processed and dealt with by the library code. Other exceptions resulting from system calls will therefore be bubbled up to the caller app.

Your code must therefore implement strong exception handling otherwise it's likely that at some point the stack trace will expose your restricted app data to users, such as API key.

Good code throws exceptions as needed, and handles only the exceptions it knows how to handle, leaving the rest to bubble up the stack.

Which means catch exceptions specifically rather than via a cat

C# Helper Classes: WorldText

WorldText is the base class of the C# Libary, containing the core API web send and response processing code, and a selection of utility methods available in all derived classes. It is unlikely you will instantiate this class directly unless you are building your own classes encapsulating the API.

WorldText Methods

public void setHost(string host) For particular customers who have been given a specific host to use, this sets the hostname for subsequent sends using the class.

public void SetSimulated(bool value) If true, requests the API treat sends as simulated on the World Text servers (ie no SMS Text messages will actually be sent).

If false, sets the default state of sending real text messages.

In simulated mode, the API returns successful for message sends, along with appropriate generated message IDs which can be queried for delivery times etc. This allows a complete simulation for testing without incurring live SMS send charges. The only difference to live SMS text messages is live messages can potentially take days to deliver (if, for example, the mobile in question is switched off for the weekend), whereas simulated receipts will come within a few seconds (although the actual time is varied randomly).

public static bool IsUTF8(string str) Returns true if the string is UTF8 extended, otherwise false. Used internally by the class, and also provides an easy way to check if a text is going to trigger UTF8 sending, and hence have half the maximum characters as compared with the GSM char set.

C# Helper Classes: WorldTextGroup

WorldTextGroup is derived from WorldText, and adds methods for convenient management of World Text SMS groups.

Ties directly to the group/ API calls.

Group contents are cached locally at instantiation within the class. This avoids unnecessary API calls when managing groups.

(Population on demand update)

Static Factory methods

To Create a New SMS Group:

public static WorldTextGroup
CreateNewGroupInstance (string id, string apiKey, string GroupName, string SourceAddress, string pin);

Where Group is the name of the group you wish to create, Src is the default source address for the group, and is the 4 digit PIN code for the group (PIN code is used in the web interface, and not actually required for sending via the API).

Open an Existing SMS Group:

public static WorldTextGroup
CreateExistingGroupInstance(string id, string apiKey, string GroupName)

The group must pre-exist on the World Text servers.

Both methods throw WorldTextException in the event of failure.

Create an Unpopulated Group Class

public static WorldTextGroup CreateEmptyGroupInstance(string id, string apiKey)

Useful only in the context of using Find() to find a group and then populating the class by calling Details(). Without a group reference, no other methods are valid, and will throw a WorldTextException if called.

WorldTextGroup methods

public void RemoveContents() Deletes all the names and numbers in the SMS group.

public int create(string GroupName, string SourceAddress, string pin) Typically called during construction with a new group, but also meaningful for creating a new group after a call to destroy to repopulate the class with a new group. Throws a WorldTextException if you call it with an active group in the class.

public int Find( string searchGroup ) Returns the ID of an SMS group in the World Text systems, or 0 if not found.

public void Destroy() Deletes the group from World Text systems, and clears any data in the class. As there's no group data in the class after this call, all you are able to do after is create (or destruct, of course).

public int AddEntries(string list) Adds a list of name+number pairs to the group, formatted as per the API documentation: Number:Name,Number:Name etc. Numbers must be unique within the group, names need not. If a number is submitted that already exists within the SMS Group, the name for that number will be updated. Returns the number of entries added to the group.

public int AddEntry(string name, string number) Adds a name+number pair to the group.

public Dictionary <long, string> details() Returns a Dictionary containing the names and numbers in the SMS Group, or null if empty. Destination Address numbers are stored as longs, being restricted to between 9 and 16 digits, and must be numeric. As they're required to be in E.164 format, leading zeroes are not permitted either.

public int Cost() Returns the cost, in credits, of sending a single part SMS text message to this group.

public List <JMessage> send(string txt, string SourceAddress = null, int multipart = 0) Sends an SMS text message to the group, optionally multi-part, optionally overriding the default source address. If you override source address it must be one already allocated to your World Text account, or the default for your account will be used (The send will go ahead anyway).

Send an SMS Text Message

Minimal code to send an SMS Text message to every member of a group:

This example assumes the group already exists on the World Text servers and is already populated with names and numbers.

                        using WorldText.SMSInterface;
                        namespace WorldText.SMSTest
                        {
                            ...
                            // Replace id and apiKey with values from http://www.world-text.com/account/

                            string AccountID = "XXXXXX";    // Your Account ID
                            string APIKey = "XXXXXX";		// Your secret API Key

                            try
                            {
                            WorldTextGroup group = WorldTextGroup.CreateExistingInstance(AccountID, APIKey, "MyGroup");

                            info = group.send("Example message");
                            } catch (WorldTextException e) {
                            echo 'Caught exception: ', e.Message, "\n";
                            }
                     

WorldTextJsonData: Returned Data Classes

Where the data produced by an API call is more complex than a simple value, we've created classes to encapsulate it. This has the added advantage that we can return a list of them in cases where there are multiple data items (for example a two part SMS send).

JResponse

JResponse is the base class of each of the defined World Text data classes. Simply contains the status returned by the API call, which will always be zero in the case of success.

Used as a convenience so every list item has the overall API call status associated with it.

                            namespace WorldText.SMSInterface
                            {
                                public class JResponse
                                {
                                    public string status;
                                }
                            }

JMessage

A list of JMessage objects is returned by group/send and sms/send, one for each part of the message sent.

                            namespace WorldText.SMSInterface
                            {
                                public class JMessage : JResponse 
                                {
                                    public string state;
                                    public string dstaddr;
                                    public string msgid;
                                    public string credits;
                                }
                            } 

JReceipt

Returned by sms/query

                                namespace WorldText.SMSInterface
                                {
                                    public class JReceipt : JResponse
                                    {
                                        public string state;
                                        public string error;
                                        public string finaldate;
                                    }
                                }
                        

C# Helper Classes: WorldTextSms

WorldTextSms is derived from WorldText, and adds methods necessary for the sms/ API calls.

Static Factory method

public static WorldTextSms CreateSmsInstance( string id, string apiKey );

WorldTextSms methods

cost

public int cost(string dstAddr);

Returns the cost, in credits, of sending a single part SMS text message to this number.

send

public List<JMessage> send(string dst, string txt, int multipart = 0);

Returns a List of Jmessage objects - one for each part you send of a multipart message.

Sends an SMS text message(s) to the number given, optionally multi-part, optionally overriding the default source address. If you override source address it must be one allocated to your World Text account, or the default for your account will be used (The send will go ahead anyway).

It is very straight forward to iterate through the list to process each part in your app. See short example below.

query

public JReceipt query( string msgID )

Queries the delivery status of the specific message.

Send an SMS Text Message

Here's the minimum necessary using the C# library to send a text message:

// Replace id and apiKey with values from http://www.world-text.com/account/

WorldTextSms sms = WorldTextSms.CreateSmsInstance( "your account ID", "your API key" );

// First, simplest possible test:  Send an SMS...
try
{
	List<JMessage> status = sms.send("447598495904", "World Text, for reliable SMS text messaging" );

	foreach (var obj in status)
	{
		Console.WriteLine("  :   state : {0}", obj.state);
		Console.WriteLine("  : dstaddr : {0}", obj.dstaddr);
		Console.WriteLine("  :   msgid : {0}", obj.msgid);
		Console.WriteLine("  : credits : {0}", obj.credits);
	}
}
catch ( WorldTextException ex )
{
	
}

// Catch all exceptions and process ...
catch ( Exception ex )
{
	throw;
}

                     

Static Factory method

smsObject = WorldTextSms.CreateSmsInstance( "yourID", "SecretAPIKey" );

API Libraries: Other Languages

Background

The API libraries make it easier for you to use the World Text REST API from the language of your choice.

All libraries are open source, BSD licensed, hosted on Github, so if you want to extend, encapsulate the API differently, or simply fix a bug, we'd be delighted to have you contribute to the projects.

In producing the official libraries we've intentionally kept a fairly close coupling between the HTTP REST API and the object methods.

Contributing

If you have implemented a helper library of your own or class encapsulating the HTTP REST API, in any language, we'd love to see it. If it's already on Github we'll either link to it, or fork it and modify it to meet the needs of general clients.

We'd also like to see mashups, and plugins for any web services or software.

We're also interested in hearing which languages or systems you'd like to see resources for, if we don't already have it listed. Future libraries and examples will typically be produced for whichever are most popular with our clients

Please Contact us with your suggestions, code and ideas!

We have additional resources available for registered developers, including additional credits on developer accounts for testing!

PHP Helper Classes Introduction

The World Text REST API is able to query a selection of resources, make groups, add and remove numbers from groups, and send SMS text messages.

We have encapsulated the API calls such that you don't need to be concerned directly with URLs, resources, the API calls themselves, or processing the raw JSON responses.

Depending on the calls used, responses can still be in a JSON-like format, but pre-processed.

PHP Classes

All classes, except the exception class, are instantiated via factory pattern xxCreateInstance static methods in the appropriate class.

It's unlikely you'll instantiate the base class directly, but it's not abstract so you can, if need be.

It contains methods for account validation, setting protocols and server, and the actual http send and response processing.

Some minimal pre-processing of the JSON response is also done.

require_once('/path/World-Text-PHP/WorldText.php');

// Replace id and apiKey with values from http://www.world-text.com/account/

$id = "XXXXXX";     // Your Account ID
$apiKey = "XXXXXX"; // Your secret API Key

$sms = worldtext\WorldTextSms::CreateSmsInstance(id, apiKey);

try {
    $info = $sms->send("447989000000", "Example message");
} catch (wtException $e) {
    echo 'Caught exception: ', $e->getMessage(), "\n";
}
                  

PHP Helper Classes: WorldText

WorldText is the base class of the PHP Libary, containing the API send an response processing code, and a selection of utility methods available in all derived classes. As such, it is unlikely you will instantiate this class directly unless you are building your own classes on top of the API.

WorldText Methods

setSecure

If true, checks that the cURL is capable of HTTPS and sets protocol to secure.

If false, sets protocol to HTTP

setHost

For particular customers who have been given a specific host to use, this sets the hostname for subsequent sends using the class.

setSimulated

If true, sets a flag to indicate that sends are to be treated by the World Text servers as simulated (i.e. No SMS text messages will actually be sent)

If false, returns the class to the default state of sending real text messages.

In simulated mode, the API returns successful for message sends, along with appropriate generated message IDs which can be queried for delivery etc. This allows an essentially complete simulation for testing. The only difference to real, live SMS text messages is actual messages can potentially take days to deliver (if, for example, the mobile in question is switched off), whereas simulated receipts come within a few seconds.

static isUTF8

Returns TRUE if the string is UTF8 extended, otherwise FALSE.

PHP Helper Classes: WorldTextAdmin

WorldTextAdmin is derived from WorldText, and adds methods necessary for the ../admin/ API calls.

For day to day use of the interface it's unlikely you'll need the admin class very often.

Typically you're going to use it for double-checking account credit status after a 403 Forbidden (PAYG account which is out of credit). Ping is mainly in the API for historic reasons, but should you wish to query if the host is alive prior to send, you can.

Static Factory Method

$admin = worldtext\WorldTextAdmin::CreateAdminInstance(yourID, 'yourSecretAPIKey');

WorldTextAdmin methods

ping

Pings the World Text SMS gateway and returns success

credits

Checks the number of credits available on an account. Typically negative for invoiced accounts.

PHP Helper Classes: WorldTextGroup

WorldTextGroup is derived from WorldText, and adds methods necessary for the group/API calls.

Group contents are cached locally fter instantiation within the class eliminating superfluous API calls.

Static Factory Methods

Create a new group:

$grp = worldtext\WorldTextGroup::CreateNewInstance(yourID, 'SecretAPIKey', "Group", "Src", "PIN");

Where Group is the name of the group you wish to create, Src us the default source address for the group, and is the 4 digit PIN code for the group (PIN code is used in the web interface).

Open an existing group:

$grp = worldtext\WorldTextGroup::CreateExistingInstance(yourID, 'SecretAPIKey', "Group");

The group must exist.

Both methods throw an exception on failure.

WorldTextGroup Methods

deleteContents

Deletes all the names and numbers in the group

create

Typically called during construction with a new group, but also meaningful for creating a new group after a call to destroy, to repopulate the class with a new group.

Throws an exception if you call it with an active group in the class.

find

Returns the ID of a group in the World Text systems, or a NULL if not found.

destroy

Deletes the group from World Text systems, and clears any data in the class. As there is no group data in the class after this call, all the user is able to do is create or destruct.

entries

Adds a list of name+number pairs to the group, formatted as per the API documentation.

entry

Adds a name+number pair to the group.

details

Returns an array of the names and numbers in the class, or NULL if empty.

cost

Returns the cost of sending a single part SMS text message to this group.

send

Sends an SMS text message(s) to the group, optionally multi-part, optionally overriding the default source address, If you override the source address it must be one allocated to your World Text Account, or the default will be used (The send will go ahead).

Send An SMS Text Message

                        require_once('/path/World-Text-PHP/WorldText.php');
                        
                        // Replace id and apiKey with values from http://www.world-text.com/account/
                        $id = "XXXXXX";     // Your Account ID
                        $apiKey = "XXXXXX"; // Your secret API Key
                         
                        $grp = worldtext\WorldTextGroup::CreateExistingInstance(id, apiKey, "Example");
                        try {
                           $info = $grp->send("Example message");
                        } catch (wtException $e) {
                           echo 'Caught exception: ', $e->getMessage(), "\n";
                        }   
                     

PHP Helper Classes: WorldTextSMS

WorldTextSms is derived from WorldText, and adds methods necessary for the sms/ API calls.

Static Factory Method

$sms = worldtext\WorldTextSms::CreateSmsInstance(yourID, 'SecretAPIKey');

Send An SMS Text Message

                        require_once('/path/World-Text-PHP/WorldText.php');

                        // Replace id and apiKey with values from http://www.world-text.com/account/
                        $id = "XXXXXX";     // Your Account ID
                        $apiKey = "XXXXXX"; // Your secret API Key
                        $sms = worldtext\WorldText::CreateSmsInstance(id, apiKey);
                        try {
                            $info = $sms->send("447989000000", "Example message");
                        } catch (wtException $e) {
                            echo 'Caught exception: ', $e->getMessage(), "\n";
                        }  
                     

PHP Helper Classes: wtException

wtException is derived from Exception, and adds methods necessary for World Text specific status from API calls.

wtException Methods

getStatus

The numeric status returned by the World Text REST API.

getDesc

The description of the error returned by the World Text REST API.

getError

The HTTP response code.

Python Helper Classes

Find py-worldtextsms on GitHub.

                           import http.worldtextsms

                           worldtext.api_key = 1234567890
                           worldtext.account_id = 123

                           sms = http.worldtextsms.SMS()
                           sms.send('44123123123', 'This is a World-Text.com Python Library Test')

                     

Perl Module

Written by Dennis Kaarsemaker you can find Net-SMS-WorldText on GitHub and CPAN. This module uses version 1 on the World-Text HTTP API.

                           // From Module Synopsis
                           use Net::SMS::WorldText;

                           my $wt = Net::SMS::WorldText->new(user => "testuser", pass => "123456");
                           $wt->send( message => "A thing of beauty is a joy forever",
                                      dest => "+15550123456" );