HTTP API (Legacy)

📘

Important: API Channel Activation for New Accounts and Sub-Accounts

When you create a new Account or Sub-Account, please be aware that by default, no API channels will be active. To enable API access and manage your Accounts and Sub-Accounts' API credentials and settings, please follow the steps outlined in the "API Keys" page.

Note for Accounts Created Before 6 June 2023: If you have an Account that was created before 6 June 2023, the API channels would have been automatically enabled. However, if you wish to switch to an alternative API or use additional APIs, you will need to create an API Key for the desired API.

Overview

The page can be referenced at https://legacy.mymobileapi.com/api5/http5.aspx

We do offer HTTP communication, however HTTPS is recommended. To use SSL please replace https with http in all URLs mentioned in this guide. All functions require the following information:

  • Type
  • Username
  • Password

The “Type” defines what function you wish to execute.
The output is XML based and will always contain the following:

<api_result>
	<call_result>
		<result>True</result>
		<error/>
	</call_result>
</api_result>

📘

Please Note:

  • Where XML data is passed the data between the xml tags should be URL encoded.

The following symbols need to be replaced if you’re using the “Get” method.

SymbolReplace With
&%26amp;
<%26lt;
>%26gt;

Sending Messages - Parameter Based

Make use of parameter driven variables to send.
The function accepts the following parameters:

  • Type (String) = “sendparam”
  • Username (String)
  • Password (String)

Examples:
Send to Single Number:
https://legacy.mymobileapi.com/api5/http5.aspx?Type=sendparam&username=xxx&password=yyy&numto=1234567890&data1=mytestmsg

Send to Multiple Numbers:
https://legacy.mymobileapi.com/api5/http5.aspx?Type=sendparam&username=xxx&password=yyy&numto=1234567890,9876543210&data1=mytestmsg

Parameter

Description

Default

live

If Live = false then it will return the result but won’t send the data. It won’t appear in your sent report.

True

return_credits

If True then the current Credits count will be returned.

False

return_msgs_credits_used

If True then the amount of credits used will be returned.

False

return_msgs_success_count

If True then the total success data count will appear in the result.

False

return_msgs_failed_count

If True then the total failed data count will appear in the result.

False

return_entries_success_status

If True then the total success data count will appear in the result.

False

return_entries_failed_status

If True then the data that is rejected will be returned in the result.

False

senderid

This determines where the message will come from. Only certain accounts can alter this.

Repliable

numto

The number you wish to send your data to.

""

date

This is the date the messages must be sent out. Format is dd/MMM/yyyy eg: 13/apr/2009

time

This is the time the messages must be sent out. Format is HH:mm eg: 17:34

curdate

This is the current date on your server. It is used to determine when your messages should go out. If not used then the server date is used.

Server Date

curtime

This is the current time on your server. It is used to determine when your messages should go out. If not used then the server time is used.

Server Time

data1

The data you wish to send

""

msgtype

This defines the type of message you wish to send.
Values can be SMS / SMSR / VCARD / WPUSH / PORT

SMS

costcentre

User Defined

""

campaignname

User Defined

""

customerid

The customerid is a field that is populated that has meaning to your system. This field can be returned in the result sets and can make updating data very easy. We suggest using a GUID or Identity key.

""

mo_forwardemail

All incoming replies will be forwarded to this email.

""

validityperiod

The amount of time in hours an SMS should remain valid. The network will continue to try to deliver the SMS over the validity period.

🚧

All entries marked with * are mandatory

🚧

Post Paid Customers

Return Credits will always return a value of 1000000 on Post Paid accounts as no credit deduction occurs on this account type.

The output of the following XML example is defined by the input of the above parameters:

<api_result>
		<entries_failed>
			<numto/>
			<customerid/>
			<reason>numto invalid</reason>
		</entries_failed>
		<entries_success>
			<numto>2782*******</numto>
			<customerid>UnqiueValue1</customerid>
		</entries_success>
		<entries_success>
			<numto>2782*******</numto>
			<customerid>UnqiueValue1</customerid>
			</entries_success>
			<numto>2782*******</numto>
			<customerid>example1</customerid>
		</entries_success>
	<send_info>
		<eventid>9876543210</eventid>
		<credits>39763</credits>
		<msgs_credits_used>3</msgs_credits_used>
		<msgs_success>3</msgs_success>
		<msgs_failed>1</msgs_failed>
	</send_info>
	<call_result>
		<result>True</result>
		<error/>
	</call_result>
</api_result>

XML tag

Description

entries_failed

If this tag exists then some of the data you pushed has errors.

It will contain: “numto”, “customerid” and “reason”. The reason will be:

  • numto invalid
  • senderid invalid
  • time invalid
  • costcentre invalid
  • campaignname invalid
  • type invalid
  • data1 invalid

entries_success

If this tag exists then it will contain “numto” and “customerid”.

send_info

This describes the overall data returned. It WILL contain “eventid” and COULD have “credits”, “msgs_credits_used”, “msgs_success” and “msgs_failed”.

  • credits = credits remaining in account
  • msgs_credits_used = the amount of credits used
  • msgs_success = a count of the messages accepted for delivery
  • msgs_failed = a count of the messages rejected

Sending Messages - XML

Sending messages is relatively easy, but due to the various options it can seem confusing.
In a nutshell: If you specify a default then it will only be utilized if the entry data does not exist. If neither exists then it will throw an error.

The function accepts 4 parameters
• Type (string) = “send”
• Username (string)
• Password (string)
• XMLData (string)

Example string:
https://legacy.mymobileapi.com/api5/http5.aspx?type=send&username=xxx&password=yyy&xmldata=zzz

The XML object looks like this:

<senddata>
	<settings>
		<live>True</live>
		<return_credits>True</return_credits>
		<return_msgs_credits_used>True</return_msgs_credits_used>
		<return_msgs_success_count>True</return_msgs_success_count>
		<return_msgs_failed_count>True</return_msgs_failed_count>
		<return_entries_success_status>True</return_entries_success_status>
		<return_entries_failed_status>True</return_entries_failed_status>
		<default_senderid/>
		<default_date>01/Jan/2018</default_date>
		<default_time>11:15</default_time>
		<default_curdate>01/Jan/2018</default_curdate>
		<default_curtime>12:00</default_curtime>
		<default_data1>This is a default msg</default_data1>
		<default_type>SMS</default_type>
    <default_costcentre>NA</default_costcentre>
    <default_campaignname>NA</default_campaignname>
		<mo_forwardemail>[email protected]</mo_forwardemail>
		<default_validityperiod>24</default_validityperiod>
	</settings>
		<entries>
			<numto>082*******</numto>
			<customerid>UnqiueValue1</customerid>
			<senderid>Test me</senderid>
			<time>12:00</time>
			<data1>This is a test message 1!</data1>
			<type>SMS</type>
			<costcentre>NA</costcentre>
      <campaignname>NA</campaignname>
			<validityperiod>48</validityperiod>
		</entries>
</senddata>

XML Tag Table

The following table determines how the result of each XML tag is formatted as well as defines the defaults.

XML Tag

Description

Default

live

If Live = false then it will return the result but won’t send the message.

True

return_credits

If True then the current Credits count will be returned.

False

  • *returnmsgs
    credits_used**

If True then the amount of credits used will be returned.

False

  • *returnmsgs_success
    count**

If True then the total success data count will appear in the result.

False

returnmsgs_failed count

If True then the total failed data count will appear in the result.

False

returnentires_success status

If True then the data that is accepted will be returned in the result.

False

default_senderid

This is the default setting for the call but can be overridden by the individual entries. Only certain accounts can alter this.

Repliable

default_date

This is the date the messages must be sent out. Format is dd/MMM/ yyyy eg: 13/apr/2009

default_time

This is the time the messages must be sent out. Format is HH:mm eg: 17:34

default_curdate

This is the current date on your server. It is used to determine when your messages should go out. If not used then the server date is used.

Server Date

default_curtime

This is the current time on your server. It is used to determine when your messages should go out. If not used then the server time is used.

Server time

default_data1

This is the default setting for the call but can be overridden by the individual entries.

““

default_type

This is the default setting for the call but can be overridden by the individual entries. Values can be SMS / SMSR / WPUSH / VCARD

SMS

default_costcentre

User Defined

““

default_campaignname

User Defined

““

mo_forwardemail

All incoming replies will be forwarded to this email address

““

default_validityperiod

The amount of time in hours an SMS should remain valid. The network will continue to try to deliver the SMS over the validity period.

🚧

All entries marked with * are mandatory

🚧

Post Paid Customers

Return Credits will always return a value of 1000000 on Post Paid accounts as no credit deduction occurs on this account type.

For each entry in the XML the following can be utilised:

XML Tag

Description

Default

numto

The number the message must go to.

SMS

customerid

The customerid is a field that is populated that has meaning to your system. This field can be returned in the result sets and can make updating data very easy. We suggest using a GUID or Identity key.

““

senderid

The senderid can be altered (this is the number the message is received from). Only certain accounts allow this feature.

““

time

The time the message must be delivered. This is joined with the default_date. See default_time for formatting.

data1

This is data that will be sent

““

type

This is the default setting for the call but can be overridden by the individual entries.
Values can be SMS / SMSR / VCARD / WPUSH / PORT

SMS

costcentre

User Defined

““

campaignname

User Defined

““

validityperiod

The amount of time in hours an SMS should remain valid. The network will continue to try to deliver the SMS over the validity period. This value will override the ‘default_validityperiod’ setting.

🚧

All entries marked with * are mandatory

The output of the following will be defined by the input of the above parameters:

<api_result>
    <entries_failed>
        <numto/>
        <customerid/>
        <reason>numto invalid</reason>
        </entries_failed>
        <entries_success>
        <numto>2782*******</numto>
        <customerid>UnqiueValue1</customerid>
        </entries_success>
        <entries_success>
        <numto>2782*******</numto>
        <customerid>UnqiueValue1</customerid>
    </entries_success>
    <entries_success>
        <numto>27832297941</numto>
        <customerid>example</customerid>
    </entries_success>
    <send_info>
        <eventid>9876543210</eventid>
        <credits>39763</credits>
        <msgs_credits_used>3</msgs_credits_used>
        <msgs_success>3</msgs_success>
        <msgs_failed>1</msgs_failed>
    </send_info>
    <call_result>
        <result>True</result>
        <error/>
    </call_result>
</api_result>

XML Tag

Description

entries_failed

If this tag exists then some of the data you pushed has errors.

It will contain: “numto”, “customerid” and “reason”. The reason will be:

  • numto invalid
  • senderid invalid
  • time invalid
  • costcentre invalid
  • campaignname invalid
  • type invalid
  • data1 invalid
  • data2 invalid
  • data1 + data2 invalid

entries_success

If this tag exists then it will contain “numto” and “customerid”.

send_info

This describes the overall data returned. It WILL contain “eventid” and COULD have “credits”, “msgs_credits_used”, “msgs_success” and “msgs_failed”.

  • credits = credits remaining in account
  • msgs_credits_used = the amount of credits used
  • msgs_success = a count of the messages accepted for delivery
  • msgs_failed = a count of the messages rejected

Retrieve data from the API (Parameter Based) - OVERVIEW

The SMS Gateway is designed to allow easy retrieval of your sent items and replies.
The design allows the following:

  • Retrieval of items you have not already pulled
  • Instant retrieval of data (due to API table design and indexing)
  • Customisation to the result format
  • Prevention of timeouts

1. Sent Items

The API system uses a unique identity field called “changeid” which increments permanently. When a message status is received from the corresponding network, a new record is written to the API and the changeid will increment by 1. Messages will not be retrieved via the API that do not have any status changes.

In the result set, the element “changeid” will be present along with the other elements you have specified. This needs to be stored and the maximum changeid utilised by the next call. The following is occurring within the SMS gateway:

“Select top 100 * from API_Sent_Table where changeid > @ID order by changeid asc”

RETRIEVING SENT DATA (PARAMETER BASED)

The function accepts the following parameters:

  • Type (String) = “sentparam”
  • Username (String)
  • Password (String)

Example string:
https://legacy.mymobileapi.com/api5/http5.aspx?Type=sentparam&username=xxx&password=yyy&id=zzz

ParameterDescriptionDefault
IDThe max CHANGEID from the previous call. Start with “0”-
Max_recsThe number of records returned from the call. Values 1 to 100100
Cols_returnedThe xml tags returned in the result. Options are: sentid, eventid, smstype, numto, data, customerid, status, statusdate. Each entry must be separated by a comma.ChangeID
Date formatThe format of any dates that are returned.dd/MMM/yyyy HH:mm:ss

🚧

All entries marked with * are mandatory

The output returned will be a data set or XML in the following format for each message sent:

<api_result>
	<data>
		<changeid>21437610891</changeid>
		<sentid>67393185816</sentid>
		<eventid>6403219457</eventid>
		<smstype>Sms</smstype>
		<numto>278********</numto>
		<data>This is a test msg</data>
		<customerid>UnqiueValue1</customerid>
		<status>DELIVRD</status>
		<statusdate>1/Jan/2024 07:53:09</statusdate>
	</data>
	<call_result>
		<result>True</result>
		<error/>
	</call_result>
</api_result>

XML tag

Description

changeid

A unique ID identifying the change in a message status

SentID

A unique value for each message. You could receive the same SentID back if the message
status changes.

eventid

When sending a single or bulk SMS, an eventid is generated. This will be returned in the result xml. This eventid can be for 1 or “infinity” message entries. Note: This is a long value.

smstype

This is the type of message sent. Default = “SMS”

numto

The number the message was sent to

data

The data sent to the mobile number

customerid

The customerid for the message when the data was sent

status

The message status. Options are “DELIVRD”, “UNDELIV”, “BLIST”, “EXPIRED”

statusdate

The date and time the message was sent

2. Replies

The API system uses a unique identity field called “ReplyID” which increments permanently. When an inbound message is received from the corresponding network a new record is written to the API and hence the ReplyID will increment by 1.

In the result set the element “ReplyID” will be present along with the other elements you have specified. This needs to be stored and the maximum replyid utilized by the next call. The following is occurring with the SMS Gateway:

“Select top 100 * from API_Reply_Table where replyid > @ID order by replyid asc”

📘

Tips:

  • Start with id (replyid) = 0
  • Store the max replyid in your local system, permanently (database or IO system).
  • Only pull back data you require, using the “cols_returned” element (this will reduce bandwidth).

🚧

Limitations

  • Inbound messages are only retained for up to seven days, i.e. replies that were sent more than a week ago cannot be retrieved via HTTP.

RETRIEVING REPLIES (PARAMETER BASED)

The function accepts 4 parameters:

  • Type (String) = “repliesparam”
  • Username (String)
  • Password (String)

Example string:
https://legacy.mymobileapi.com/api5/http5.aspx?Type=repliesparam&username=xxx&password=yyy&id=zzz

Parameter

Description

Default

ID

The max REPLYID from the previous call

Max_recs

The number of records returned from the call.
Values 1 to 100

100

Cols_returned

The xml tags returned in the result. Options are: replyid, eventid, numfrom, receiveddata, sentid, sentdata, sentcustomerid, received, sentdatetime, optout. Each entry must be separated with a comma.

ReplyID

Date Format

The format of any dates that are returned.

dd/MMM/yyyy HH:mm:ss

🚧

All entries marked with * are mandatory

The output returned will be a data set or XML in the following format per reply received:

<api_result>
	<data>
		<replyid>509871807</replyid>
		<eventid>6414283881</eventid>
		<numfrom>278********</numfrom>
		<receiveddata>Reply Received</receiveddata>
		<sentid>67758922377</sentid>
		<sentdata>my test msg reply</sentdata>
		<sentcustomerid>UnqiueValue1</sentcustomerid>
		<received>19/Jan/2024 13:40:58</received>
		<sentdatetime>19/Jan/2024 13:40:49</sentdatetime>
		<optout>false</optout>
	</data>
	<call_result>
		<result>True</result>
		<error/>
	</call_result>
</api_result>
XML tagDescription
ReplyIDThe max unique REPLYID for each incoming message
EventIDWhen sending a single or bulk SMS, an eventid is generated. This will be returned in the result xml. This eventid can be for 1 or “infinity” message entries.
NumFromThe number of the user that sent the incoming message
ReceivedDataThe data that the user returned
SentIDThe unique sentid for the outgoing message
SentDataThe data sent to the user
SentCustomerIDThe customerid for the message when the data was sent
ReceivedThe date and time the message was received
SentDateTimeThe date and time the message was sent
OptOutThe value will be True if the reply contains an opt-out trigger word, like STOP, OPTOUT or REMOVE

🚧

All entries marked with * are mandatory

Retrieve data from the API (XML) - OVERVIEW

The SMS Gateway is designed to allow easy retrieval of your sent items and replies.
The design allows the following:

  • Retrieval of items you have not already pulled
  • Instant retrieval of data (due to API table design and indexing)
  • Customisation to the result format
  • Prevention of timeouts

1. Sent Items

The API system uses a unique identity field called “changeid” which increments permanently. When a message status is received from the corresponding network, a new record is written to the API and the changeid will increment by 1. Messages will not be retrieved via the API that do not have any status changes.

In the result set, the element “changeid” will be present along with the other elements you have specified. This needs to be stored and the maximum changeid utilised by the next call. The following is occurring within the SMS gateway:

“Select top 100 * from API_Sent_Table where changeid > @ID order by changeid asc”

📘

Tip:

  • Start with id (changeid) = 0.
  • Store the max changeid in your local system, permanently (database or IO system).
  • Only pull back data you require, using the “cols_returned” element (this will reduce bandwidth).

RETRIEVING SENT DATA (XML)

The function accepts 4 parameters

  • Type (String) = “sent”
  • Username (String)
  • Password (String)
  • XML (String)

Example string:
https://legacy.mymobileapi.com/api5/http5.aspx?type=sent&username=xxx&password=yyy&xmldata=yourxmlstring

The XML object looks like:

<sent>
	<settings>
		<id>0</id>
		<max_recs>100</max_recs>
		<cols_returned>sentid,eventid,numto,data</cols_returned>
		<date_format>dd/MMM/yyyy HH:mm:ss</date_format>
	</settings>
</sent>
ParameterDescriptionDefault
IDThe max changeid from the previous call. Start with “0”-
Max_recsThe number of records returned from the call (values 1 to 100)100
Cols_returnedThe xml tags returned in the result. Options are: sentid, eventid, smstype, numto, data, customerid, status, statusdate. Each entry must be separated by a comma.ChangeID
Date FormatThe format of any dates that are returned.dd/MMM/yyyy HH:mm:ss

🚧

All entries marked with * are mandatory

The output returned will be a data set or XML in the following format:

2. Replies

The API system uses a unique identity field called “ReplyID” which increments permanently. When an inbound message is received from the corresponding network a new record is written to the API and hence the ReplyID will increment by 1.

In the result set the element “ReplyID” will be present along with the other elements you have specified. This needs to be stored and the maximum replyid utilized by the next call. The following is occurring with the SMS Gateway:

“Select top 100 * from API_Reply_Table where replyid > @ID order by replyid asc”

📘

Tips:

  • Start with id (replyid) = 0.
  • Store the max replyid in your local system, permanently (database or IO system).
  • Only pull back data you require, using the “cols_returned” element (this will reduce bandwidth).

RETRIEVING REPLIES (XML)

The function accepts 4 parameters:

  • Type (string) = “replies”
  • Username (string)
  • Password (string)
  • XML (String or data set: depending on the function you choose)

Example string:
https://legacy.mymobileapi.com/api5/http5.aspx?Type=replies&username=xxx&password=yyy&xmldata=yourxmlstring

The XML object looks like:

<reply>
	<settings>
		<id>0</id>
		<max_recs>100</max_recs>
		<cols_returned>sentid,sentdata,received,sentdatetime,optout</cols_returned>
		<date_format>dd/MMM/yyyy HH:mm:ss</date_format>
	</settings>
</reply>

Parameter

Description

Default

ID

The max REPLYID from the previous call

Max_recs

The number of records returned from the call. Values 1 to 100

100

Cols_returned

The xml tags returned in the result. Options are:
replyid, eventid, numfrom, receiveddata, sentid, sentdata, sentcustomerid, received, sentdatetime, optout. Each entry must be separated with a comma.

ReplyID

Date Format

The format of any dates that are returned.

dd/MMM/yyyy HH:mm:ss

🚧

All entries marked with * are mandatory

The output returned will be a data set or XML in the following format:

<api_result>
	<data>
		<replyid>509871807</replyid>
		<eventid>6414283881</eventid>
		<numfrom>278*******</numfrom>
		<receiveddata>Testing</receiveddata>
		<sentid>67758922377</sentid>
		<sentdata>Testing Replies</sentdata>
		<sentcustomerid>UnqiueValue1</sentcustomerid>
		<received>19/Jan/2024 13:40:58</received>
		<sentdatetime>19/Jan/2024 13:40:49</sentdatetime>
		<optout>false</optout>
	</data>
	<call_result>
		<result>True</result>
		<error/>
	</call_result>
</api_result>
XML tagDescription
ReplyIDThe max unique REPLYID for each incoming message
EventIDWhen sending a single or bulk SMS, an eventid is generated. This will be returned in the result xml. This eventid can be for 1 or “infinity” message entries. Note: This is a long value.
NumFromThe number of the user that sent the incoming message
ReceivedDataThe data that the user returned
SentIDThe unique sentid for the outgoing message
SentDataThe data sent to the user
SentCustomerIDThe customerid for the message when the data was sent
ReceivedThe date and time the message was received
SentDateTimeThe date and time the message was sent
StatusDateThe date and time the status was received
OptOutThe value will be True if the reply contains an opt-out trigger word, like STOP, OPTOUT or REMOVE

🚧

All entries marked with * are mandatory

Check Balance (HTTP)

The function accepts 3 parameters:

  • Type (String) = “credits
  • Username (String)
  • Password (String)

Example: http://legacy.mymobileapi.com/api5/http5.aspx?Type=credits&username=xxx&password=yyy

<api_result>
	<data>
		<credits>xxxxx</credits>
	</data>
	<call_result>
		<result>True</result>
		<error/>
	</call_result>
</api_result>

Your current credit value will be displayed between the “credits” tag.

🚧

Post Paid Customers

Credits will always return a value of 1000000 on Post Paid accounts as no credit deduction occurs on this account type.

Code Examples (HTTP)

package co.za.smsportal.sample;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * SampleCreditChecker is an example that demonstrates how to connect to 
 * MyMobileApi. It by no means is a complete and robust solution and should not
 * be used in any production code.
 */
public class SampleCreditChecker {

	public static final String MY_MOBILE_API_URL = 
		"http://legacy.mymobileapi.com/api5/http5.aspx?";
	private URLConnection urlConnection;
	
	/**
	 * Initializes a new SampleCreditChecker which will check the number of 
	 * credits available for a given username and password.
	 * 
	 * @param urlConnection	A URLConnection containing a URL to the API.
	 */
	public SampleCreditChecker(URLConnection urlConnection) {
		this.urlConnection = urlConnection;
	}
	
	/**
	 * Gets the number of credits available for the specified username and 
	 * password.
	 * 
	 * @param username	The username.
	 * @param password	The password for the username.
	 * @return			A integer value indicating how many credits the user has
	 * @throws Exception 
	 */
	public int getCredits(String username, String password) throws Exception {
		try {
			//Set DoInput to true so that we can write to the server.
			urlConnection.setDoInput(true);
			//Set DoOutput to true so that we can read from the server.
			urlConnection.setDoOutput(true);
			
			//Create a writer to the server.
			OutputStream raw = urlConnection.getOutputStream();
			OutputStream buffered = new BufferedOutputStream(raw);
			OutputStreamWriter writer = new OutputStreamWriter(buffered, 
					"8859_1");
			
			//Write the following to the server via the URL.
			writer.write("type=credits&username=" + username 
					+ "&password=" + password);
			
			//Don't forget to flush and close the writer.
			writer.flush();
			writer.close();
			
			//Parse the returned XML. Use the InputStream from the connection.
			return parseXmlForCredits(urlConnection.getInputStream());
		} catch (ParserConfigurationException e) {
			System.out.println("Parser Configuration Exception");
			e.printStackTrace();
		} catch (SAXException e) {
			System.out.println("SAX Exception");
			e.printStackTrace();
		}
		return -1;
	}
	
	private int parseXmlForCredits(InputStream stream) 
	throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(stream);
		
		//First check if there are any errors.
		NodeList errors = document.getElementsByTagName("error");
		if (errors.getLength() > 0) {
			Node errorNode = errors.item(0);
			String errorMsg = errorNode.getTextContent();
			if (!errorMsg.isEmpty()) 
				throw new Exception("Error getting credits. " + errorMsg);
		}
		
		//Now check for the number of credits.
		NodeList nodes = document.getElementsByTagName("credits");
		Node creditNode = nodes.item(0);
		return Integer.parseInt(creditNode.getTextContent());
	}
	
	/**
	 * Main entry point for sample.
	 * 
	 * @param args	Command line arguments.
	 */
	public static void main(String[] args) {
		URL url;
		try {
			url = new URL(MY_MOBILE_API_URL);
			URLConnection urlConnection = url.openConnection();
			SampleCreditChecker client = new SampleCreditChecker(urlConnection);
			
			//Please note that xxx and yyy are NOT real usernames and passwords
			//Susbsitute your own username and password.
			int nrCredits = client.getCredits("xxx", "yyy");
			System.out.println("Number of credits = " + nrCredits);
		} catch (MalformedURLException me) {
			System.out.println("The URL is malformed. " + MY_MOBILE_API_URL);
			me.printStackTrace();
		} catch (IOException ioe) {
			System.out.println("An IO Exception has occured.");
			ioe.printStackTrace();
		} catch (Exception e) {
			System.out.append(e.getMessage());
			e.printStackTrace();
		}
	}
}
<?php
    
class MyMobileAPI
{

    public function __construct() {
        $this->url = 'http://api.smsportal.com/api5/http5.aspx';
        $this->username = 'someusername'; //your login username
        $this->password = 'somepassword'; //your login password
      //$this->validityperiod = '24'; //optional- set desired validity (represents hours)
    }
    
    public function checkCredits() {
        $data = array(
            'Type' => 'credits', 
            'Username' => $this->username,
            'Password' => $this->password
        );
        $response = $this->querySmsServer($data);
        // NULL response only if connection to sms server failed or timed out
        if ($response == NULL) {
            return '???';
        } elseif ($response->call_result->result) {
	    echo '</br>Credits: ' .  $response->data->credits;
            return $response->data->credits;
        }
    }
    
   public function sendSms($mobile_number, $msg) {
        $data = array(
            'Type' => 'sendparam', 
            'Username' => $this->username,
            'Password' => $this->password,
            'numto' => $mobile_number, //phone numbers (can be comma seperated)
            //'validityperiod' => $this->validityperiod, //the duration of validity
            'data1' => $msg //your sms message
	   			
        );
        $response = $this->querySmsServer($data);
        return $this->returnResult($response);
    }
    
    // query API server and return response in object format
    private function querySmsServer($data, $optional_headers = null) {

        $ch = curl_init($this->url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // prevent large delays in PHP execution by setting timeouts while connecting and querying the 3rd party server
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 2000); // response wait time
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 2000); // output response time
        $response = curl_exec($ch);
        if (!$response) return NULL;
        else return new SimpleXMLElement($response);
    }

    // handle sms server response
    private function returnResult($response) {
        $return = new StdClass();
        $return->pass = NULL;
        $return->msg = '';
        if ($response == NULL) {
            $return->pass = FALSE;
            $return->msg = 'SMS connection error.';
        } elseif ($response->call_result->result) {
            $return->pass = 'CallResult: '.TRUE . '</br>';
	    $return->msg = 'EventId: '.$response->send_info->eventid .'</br>Error: '.$response->call_result->error;
        } else {
            $return->pass = 'CallResult: '.FALSE. '</br>';
            $return->msg = 'Error: '.$response->call_result->error;
        }
	echo $return->pass; 
	echo $return->msg; 
        return $return; 
    }
    
}


//Execute script
$test = new MyMobileAPI();
$test->sendSms('0810000000','Test Message'); //Send SMS
$test->checkcredits(); //Check your credit balance


?>