SMS is used for various purposes these days. For example, large websites like Gmail and Facebook use SMS multi-factor authentication and notify users about updates to improve their authentication process. This is a one-way SMS application since messages can only be sent from users of these websites.
Two-way SMS applications are not as complicated as one-way. With two-way SMS applications, users can initiate a conversation by sending a message, and then based on the user's commands, the application responds.
In this article, I will explain the process of two-way SMS interaction and tell you how you can incorporate it into your PHP application. There are many popular SMS gateways around the world that provide two-way communication, here I explain, I will be using Clickatell.
of two-way SMS lifecycle
The life cycle of two-way SMS can be divided into 4 main steps as follows:
1, The user sends a request to the SMS gateway
2. The SMS gateway request is forwarded to the application server
3. The application server processes the request and responds to the SMS gateway
4. The SMS gateway forwards the user request
Step 1 - User SMS Gateway
The user sends the conversation through the SMS gateway. Initially, it goes through the user's mobile service provider. This part is not very important for us as it is in the local service provider domain. SMS gateway where messages are received via local service provider.
The user obviously needs his message to be sent to a specific number. You can use two-way communication, either shortcodes or dedicated long numbers (DID) specific to the application. These numbers are sent via SMS gateway and usually you need to purchase these numbers.
A dedicated number is a standard phone number, such as 94112367899. A shortcode is a 4-6 digit code. Everyone has their own strengths and weaknesses:
Shortcodes are dedicated and easier to remember than long numbers.
Dedicated numbers can be used worldwide, while shortcodes are usually limited to a single service provider in a specific country.
Dedicated long numbers can handle large numbers of messages compared to short code numbers for a given time.
The choice of whether to use shortcodes or dedicated long quantities is ultimately up to you.
Once the SMS gateway receives it, it should be routed to the processing application. For previous message routing, the gateway needs to do two things:
Prepare the message data in a way that the application can understand
URL mapping of the app to a dedicated number or shortcode
Each gateway has its own method of transferring data to the application server, although XML or SOAP over an HTTP connection are usually the most popular. The gateway should provide some sort of API documentation for the methods ever used.
The application developer creates a system to handle the specific entry point of the message received from the gateway, which is called the application URL. The process of mapping application URLs to dedicated numbers or short codes changes from one gateway to another. Some allow configuration directly through the user account interface, such as Clickatell does. If this option is not available, we have a technical support resource to contact the gateway and provide them with the URL of the application to be configured.
Stage 2 - SMS Gateway Application Server
The application owner then decides how to receive data from the gateway. clickatell allows you to specify this method within a user account. If it is unavailable, again, you need to contact the technical team of the specific gateway.
The code example below shows you how Clickatell can now receive the data it sends via the HTTP GET method. Other gateways will provide similar methods as well.
https://www.example.com/sms/sms.php?api_id=12345&from=279991235642&to=27123456789×tamp=2008-08-0609:43:50&text=Hereisthe%20messagetext&charset=ISO-8859-1&udh=&moMsgId=b2aee 337abd962489b123fda9c3480fa
1
2 $fromNo = $_GET["from"];
3 $toNo = $_GET["to"];
4 $message = $_GET["text"];
5 $msgID = $_GET["moMsgId"];
6
7 // Process the user command and generate output
8 ...
Here is an example of data being published as an XML document.
01
02
03
04
05
06
07
08
09
10
11
view source
print?
01
02
$data = $_POST["data"];
03
04
$xmlDoc = new DOMDocument();
05
$xmlDoc->loadXML($data);
06
07
$fromNo = $xmlDoc->getElementsByTagName("from");
08
$fromNo = $fromNo->item(0)->nodeValue;
09
10
$toNo = $xmlDoc->getElementsByTagName("to");
11
$toNo = $toNo->item(0)->nodeValue;
12
13
$message = $xmlDoc->getElementsByTagName("text");
14
$message = $message->item(0)->nodeValue;
15
16
// Process User Message and Generate Response
17
...
The application needs to capture the incoming data, use one of the available methods, and handle the user's commands. This code works perfectly in a simple scenario where the user's message is less than 160 characters. But what happens if the message is longer than 160 characters?
Suppose a TV station starts an advertisement and users can send SMS advertisements. Once the SMS is sent, the user will receive a time period during which advertisements will be displayed by the server. Advertisements are plain text that will appear at the bottom of the screen. We also assume that we have a predefined format for sending messages like the one below.
Advertising Campaign Title Your Advertising Title, Your Advertising Information Content
Everything in the message in which the value pair appears. Ads will be labeled and sports will represent the value of the ad category. Then the title is the next tag and its value will be the title of the ad. Message is the final tag that contains the content that the user wants to display in the ad.
Depending on the title and message length, this text message can have more than 160 characters. When each lengthy message is received, the gateway splits it into multiple parts of 160 characters. But we still have to handle the 2 pieces as a single message.
If we use the previous code example to parse the message, parts 1 and 2 of the same message will be processed as two different messages. Because these two parts do not have complete commands, the application will send an error back to the user. UDH is going to solve this problem.
What is UDH?
The UDH group represents User Data Header. When we send a long message, the sending device (mobile phone) splits the message and sends it as separate messages. UDH values will be assigned to the beginning of each message part so that the receiving device can identify them as belonging to a single message and reassemble them
A scenario with an earlier UDH group value looks like this:
Part 1 - 05 00 03 CC 02 01
Part 2 - 05 00 03 CC 02 02
The last two hex values will be the most significant value in the UDH. The second to last number is 02 the part number defined in the code and message above. Therefore, this message is split into two parts. If there are three parts, then this value should be 03, etc. The next number defines the part of the message. 01 means it's the first part, 02 means the second part, etc.
Now, what we have, we need to know that the processing time is extended and the message is split into multiple parts.
01
02
$fromNo = $_GET["from"];
03
$toNo = $_GET["to"];
04
$message = $_GET["text"];
05
$msgID = $_GET["moMsgId"];
06
$udh = $_GET["udh"];
07
08 $total = 1;
09
$count = 1;
10
if ($udh) {
11
$tmp = str_split($udh, 2);
12
$total = hexdec($tmp[4]);
13
$count = hexdec($tmp[5]);
14
}
15
16
if ($count != $total) {
17
// Save the message fragment in database
18
SaveMessagePart($db, $from, $message, $udh);
19
}
20
else if ($total != 1) {
21
$prevParts = getMessageParts($db, $from);
22
$message = $prevParts . $message;
23
}
24
25
// process $message
26
...
Now we can handle a complete message and action, completing this stage of the request cycle. The next two stages are how the response is sent back by the user through the gateway.
Stage 3 and 4 – SMS gateway, gateway to user’s application server
In the previous stage, I explained the process of receiving mail from the gateway, and processing it in your application. Once the request is processed and the response is generated, we need to send it back to the gateway.
Generally speaking, SMS gateway provides a callback URL for us to pass the response data. You usually have to provide the number of receivers, the sender's phone number, the contents of the message, and some authentication information. The exact parameters will vary depending on the gateway, but they are clickatell, from, text, and api_id, username, password.
01
02
$message = array(
03
"to" => 942288345,
04
"from" => 944488345,
05
"text" => "sample message",
06
"api_id" => API_KEY,
07
"user" => "myUsername",
08
"password" => "secret"
09
);
10
11
$apiUrl = "http://api.clickatell.com/http/sendmsg?";
12
foreach ($message as $parameter => $value ) {
13
$apiUrl .= $parameter . "=" . urlencode($value) . "&";
14
}
15
$apiUrl = rtrim($apiUrl, "&");
16
17
$ch = curl_init();
18
curl_setopt($ch, CURLOPT_HEADER, 0);
19 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
20
curl_setopt($ch, CURLOPT_URL, $apiUrl);
21
22
curl_exec($ch);
23
curl_close($ch);
The first code example above encodes all the parameters using urlencode() and adds them to the API callback URL. We then initialize the curl request and call the URL. The response message has been sent to the gateway and step 3 is completed.
Step 4 is easy, we don't have to do any part in this process. The gateway is responsible for sending all messages to the user's mobile in the correct order.
Summary
We start this tutorial by discussing two-way SMS messaging and why it is useful. We then discussed the 4 main stages that the two-way communication process goes through. You should now be able to apply the concepts covered with any particular SMS gateway and implement bidirectional SMS in your PHP application.