TaCode Tuesdays: How to Enable Multiple SMS Sending for Digital Marketing Campaigns

Posted by Alex Misevski on November 22, 2016


Welcome back to TaCode Tuesdays! This is the only place you can find snippets of code for use in your very own text/voice apps, along with a weekly dose of taco puns. I’m a developer here at Zang and not only am I a big fan of tacos (if that wasn’t already apparent), I’m also a fan of open source. My goal is to share a new app idea each week that you're free to use “as is” or modify and use as the basis for your next app.

In the last few weeks, I detailed how you can detect and minimize the threat of fraud in your voice and SMS apps—you can get the free code here, and as always, if you’d like to learn how to get started on Zang, take a look at our very first post.

This week I’m going to talk about SMS and more specifically how it can be enabled for use within your marketing campaigns.

On average, 90 percent of text messages are read within three seconds of being received, and have a 98 percent open rate. This figure is a hundred times higher than email, which normally take 2.5 days. Because of short message service (SMS) success rate, marketers often use them to:
  1. Promote business, especially during off-peak hours or seasons.
  2. Generate warm leads through an opt-in SMS mailing list to prospects or new contacts.
  3. Enhance overall client experience by utilizing SMS as a main consumer channel.
  4. Confirm purchases, reservations, shipping and appointments.
  5. Serve as a real-time communication channel for organizing events.
Utilizing text message marketing can help cut costs and increase overall revenue, especially if it can reach a wider market than manual texting. Therefore, bulk SMS is a feature that most digital marketing solutions integrate in their platform. Unfortunately, it typically comes with a hefty price tag. A typical software as a service (SaaS) SMS platform could cost anywhere from $500-$17,000.
In this post, I’ll teach you how to create a bulk SMS sending tool that can be used for digital marketing campaigns. These are the minimum skills you'll need to pull it off:
  1. Intermediate skill of any web programming language (e.g. PHP, Ruby, Python, ASP.NET, VB.NET)
  2. Basic skill of web services implementation and usage (e.g. WPF/WCF, RESTful, Soap)
  3. knowledge of parsing JSON formatted data
  4. Basic knowledge of SQL
  5. Basic knowledge of building front end web user interfaces using HTML/CSS/JavaScript

Now, Let’s Get Started!

There are two ways to architect your SMS web application platform:
1.The first option is to set up an SMS sending box powered by a local provider SIM card in your local server.
With this option, web application will push text messages to the box acting as a gateway. This option is more expensive because it will require you to purchase your own SMS server, an SMS gateway hardware, and a text subscription plan from your local telecom provider. An upside, though, is an assurance that your SMS will be sent even if internet connection gets cut-off because the box directly communicates with the cellular operator.
2.The second option is to subscribe to a cloud-based SMS platform that will give you the abstraction layer for your SMS gateway.
This approach will allow you to have a more cost efficient SMS sending capability that is easy to scale up or down depending on user demand. For example, Zang will only charge you $0.005 for an outbound SMS and $0.01 for an inbound SMS.
For this tutorial, we will be using the second option, using Zang with PHP as the programming language. Below are the steps:
  1. Subscribe to zang.io and you will receive your own developer keys for your '{AccountSid}' and '{AuthToken}'.
  2. Create your web user interface using HTML5/CSS /Javascript keeping in mind that you will need a text input box for your SMS functionality. The user interface must allow the user to enter multiple numbers or upload an Excel file containing the numbers where the SMS will be sent to.
  3. Use Zang’s CURL POST request with JSON data to send out the text to the defined numbers.
  4. Validate that the bulk SMS messages has been sent.
Step 1: Subscribe to Zang and you will receive your own developer keys for your '{AccountSid}' and '{AuthToken}'
Getting an account subscription to Zang is easy–just click here. Upon signing up, you automatically receive a free $2 credit that can be used to play around with our API. Also, you'll find the Account Sid and AuthToken on the dashboard, after you sign in.
Step 2: Create your web user interface using HTML5/CSS /Javascript.
The user interface can be designed to handle a direct input to the web application or to accept an Excel file which contains all numbers for bulk SMS sending. In our server side PHP code, we will be using cURL to execute a $_POST transmission to Zang.io server. Keep in mind that it only accepts JSON format; below is a code example for your front end HTML:
     <title> example </title>
          <script language=”javascript”>
           //create a static numbers and have it comma separated
          var numSMS = “+639173893535,+639198231767,+639183782109,+639173843546”;
          var temp = new Array();
          temp = numSMS.split(“,”);
          for (a in temp) {
          temp[a] = parseInt(temp[a],10);
     <form id="sms_form" name="sms_form" method="post" action="send.php">
     <table border=1>
               <td>enter sms number </td>
               <td><input type="text" name="sms_number" id="sms_number" value=""> </td>
               <td>enter sms message </td>
               <td><input type="text" name="sms_message" id="sms_message" value=""> </td>
               <td><input type="submit" name="sms_send" id="sms_send" value="send"> </td>
Step 3: Create a PHP cURL POST request, with JSON data through a HTTP POST call.
This works by having your code sit in the middle of the client and another web service. Your front end UI gives this script the data in a simple POST format, converting it to JSON and eventually passing it to the HTTPs call.  Zang will return whatever information that its API have processed directly to the client.
//set the zang api send sms method
$url = '{https://api.zang.io/v2/Accounts/:AccountSid/SMS/Messages.json}';
//create an array of fields coming from submitted form variables via the POST method
$fields = array(
To' => urlencode($_POST['sms_number']),
'Body' => urlencode($_POST['sms_message']),
'From' => “+639173893535”), // a TelAPI number associated with your account.
'StatusCallback' => “{url}”), /*Zang cURL for SMS sending. URL length is limited to 200 characters.*/
'StatusCallbackMethod' => “POST”),  //The HTTP method used to request the
'AllowMultiple' => “true”) ); /* values can be true or false for allowing multiple data sending*/
//create JSON string for POST data coming from the submitted form
$data_string = json_encode($fields);
$ch = curl_init();
Use the HTTP POST method in sending cURL request. Keep in mind that when you change the request method by setting CURLOPT_CUSTOMREQUEST to something, you don't actually change how libcurl behaves or acts in regard to the particular request method, it will only change the actual string sent in the request.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
Post the JSON encoded data. You must make sure that the data is formatted the way you want the server to receive it as libcurl, and will not convert or encode it for you in any way. For example, the web server may assume that this data is URL encoded.
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//Set an option for a cURL transfer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//tell the web services server that its a JSON formatted type of headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //set maximum time the request is allowed to take
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //timeout for the connect phase
Execute the given cURL session. This function should be called after initializing a cURL session and all the options for the session are set.
$result = curl_exec($ch);
Close the cURL session and free all resources. The cURL handle ch, will also be deleted.
echo $result; //output the JSON formatted data
Using cURL when you set all options you need to run the request with curl_exec($ch). This method will provide you with a response that you can present as JSON and it is suitable for future parsing. After you execute the request, information about HTTP response code will be available.
Step 4: Validate the successful operation of your HTTP post using cURL.
If all went right and HTTP response code was received correctly (200 OK, 201 CREATED etc.) you can extract the needed information from the response body and present it to your user. Zang.io provides thirteen variables from its JSON response. The following is an example of JSON server response after cURL was initiated by your PHP code from above.
"api_version": "v2",
"sid": "{SmsSid}",
"account_sid": "{AccountSid}",
"date_created": "Tue, 24 Jul 2012 14:08:23 +0000",
"date_updated": "Tue, 24 Jul 2012 14:08:24 +0000",
"date_sent": "Tue, 24 Jul 2012 14:08:24 +0000",
"to": "+17325551234",
"from": "+14245551234",
"body": "Test message sent from TelAPI!",
"status": "sent",
"direction": "outbound-api",
"price": "0.070000",
"uri": "/v2/Accounts/AC5521767e53d04deeb0a06f660cee50f9/SMS/Messages/{SmsSid}.json"
For each loop, iterate through the array of sent message responses and write a single row for each sent message coming from the server.
If ( $http_status > = 200 && $http_status < 300 )  {
$messages = $responseBody->messages;
} …
foreach ($messages as $m ) {
echo = “”;
echo .= $m->api_version;
echo .=$m->to;
echo .=$m->from;

Wrapping it Up

Bulk SMS can be an effective yet cost efficient text message marketing strategy if its developed through a cPaaS solution that only charges what you consume and automatically scales up on demand. Building a custom SMS platform through Zang is easy through following four easy steps – first, secure a free subscription allowing you to test sending and receiving of SMS through their API. Second, create a simple front-end UI that will accept SMS numbers in bulk. Third, build a PHP cURL POST request, with JSON data through a HTTP POST call allowing you>to call the send SMS method of Zang. Finally, validate if your bulk SMS is successfully sent by looking at Zang’s return post.
Well, that’s it for this week! If you have any thoughts about the app or just want to share some taco puns, you can comment below.  I'll be back soon with another installment of TaCode Tuesday. If you want a reminder, sign up to get notifications of new blog posts.

Topics: Communication Apps, Ideas, TaCode Tuesday, cPaaS