Twilio API for SMS based web application

A few months ago I worked in a web project where we had to develop web & SMS application. Our main project is fully web application where we need to integrate SMS and some voice feature. We also wanted to integrate this feature easily and cost effectively. After some R&D in google search we found several web services for this purpose. Among all the services we liked Twilio.

There are several reasons to choose Twilio. One of the most important reason is, its very easy to integrate Twilio’s REST API. The price is also cheap compare to other services. In this post I’ll not write details about Twilio. You can easily learn more about it by there web site. I’ll mention some features that we integrated in our application.

Our project is developed based on CodeIgniter framework. So we just downloaded the REST library provided by Twilio and dropped in our libraries folder.

Twilio PHP Library

Then I wrote a class to use the Twilio API to serve our application purpose. Our application’s task was:

  1. Send SMS
  2. User can search and select custom phone number
  3. User can buy a local phone number

Here is my class that I’ve written. You’ll see this class named is Smsapi and its located in the libraries folder follow the above image.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * This is a wrapper class for sending sms. Twilio Api Custom Library suitable for our CI Project
 * @author: Mahmud
 * @category Library
 */

// Include the PHP TwilioRest library
require "twilio/twilio.php";

class Smsapi {
    private $client;
    private $AccountSid;
    private $AuthToken;
    private $CallerID;
    private $ApiVersion;
    private $CI;
    private $SMS_Callback;
    private $VOICE_Callback;
    private $VOICE_fallback;
    private $VOICE_status;

    function __construct(){
        // Twilio REST API version
        $this->ApiVersion   =   "2010-04-01";

        $this->CI           =   &get_instance();

        // Set our AccountSid and AuthToken
        $this->AccountSid       =   $this->CI->config->item('twilio_sid'  );
        $this->AuthToken        =   $this->CI->config->item('twilio_token');
        $this->SMS_Callback     =   $this->CI->config->item('twilio_sms_callback');
        $this->VOICE_Callback   =   $this->CI->config->item('twilio_voice_callback');
        $this->VOICE_fallback   =   $this->CI->config->item('twilio_voice_fallback');
        $this->VOICE_status     =   $this->CI->config->item('twilio_voice_status');

        // Outgoing Caller ID you have previously validated with Twilio
        $this->CallerID     =   $this->CI->config->item('twilio_phone');

        // Instantiate a new Twilio Rest Client
        $this->client       =   new TwilioRestClient($this->AccountSid, $this->AuthToken);
    }

    /**
     * This function is a wrapper to send SMS to a phone number. You should use this method for all type
     * of SMS message sending.
     * @param string $number phone number to whom sms will send
     * @param string $message message that will send to the phone number
     */
    public function send_sms($number, $message){
        $response = $this->client->request("/{$this->ApiVersion}/Accounts/{$this->AccountSid}/SMS/Messages",
                "POST", array(
                "To" => $number,
                "From" => $this->CallerID,
                "Body" => $message
        ));
        if($response->IsError){
            $error  =   "Error: {$response->ErrorMessage} " . " File: Smsapi.php 42 no line. Number: $number";
           // echo $error;
           log_message('error', $error);
           return FALSE;
        }
        else{
            //echo "Sent message to $number";
            return TRUE;
        }
    }

    /**
     * This function search for available mobile numbers based on ZIP code
     * @access public
     * @param string $zip ZIP code of US or Canada
     * @param string $country US or CA
     * @return BOOLEAN TRUE for get result and FALSE for error or no result
     */
    public function search_mobile_numbers($zip='', $postal='', $country='US', $failsearch=FALSE){
        $SearchParams['InPostalCode']   = !empty($zip)    ? $zip    : '';
        $SearchParams['NearNumber']     = '';
        $SearchParams['Contains']       = '';
        $SearchParams['AreaCode']       = !empty($postal) ? $postal : '';

        /* Initiate US Local PhoneNumber search with $SearchParams list */
        $response = $this->client->request("/{$this->ApiVersion}/Accounts/{$this->AccountSid}/AvailablePhoneNumbers/$country/Local",
                         "GET",
                          $SearchParams);

        if($response->IsError) {
            return $response->IsError;
        }

        $AvailablePhoneNumbers = $response->ResponseXml->AvailablePhoneNumbers->AvailablePhoneNumber;

        if (empty($AvailablePhoneNumbers)){
            $AvailablePhoneNumbers  =   "No available numbers in your zip code";
            if ($failsearch){
                //now check only available number not need to zip code specific
                $SearchParams['InPostalCode']   = '';
                $response = $this->client->request("/{$this->ApiVersion}/Accounts/{$this->AccountSid}/AvailablePhoneNumbers/$country/Local",
                             "GET",
                              $SearchParams);

                if($response->IsError) {
                    return $response->IsError;
                }

                $AvailablePhoneNumbers = $response->ResponseXml->AvailablePhoneNumbers->AvailablePhoneNumber;
            }
        }

        return $AvailablePhoneNumbers;
    }

    /**
     * Buy mobile phone number
     * @param STRING $number the phone number user wants to buy
     * @return mixed TRUE for success and string for error message
     */
    public function buy_mobile_number($number){
        /* Purchase the selected PhoneNumber */
        $response = $this->client->request("/{$this->ApiVersion}/Accounts/{$this->AccountSid}/IncomingPhoneNumbers",
                                     "POST",
                                     array(
                                         'PhoneNumber'          => $number,
                                         'SmsUrl'               => $this->SMS_Callback,
                                         'SmsMethod'            => 'POST',
                                         'VoiceCallerIdLookup'  => TRUE,
                                         'VoiceUrl'             => $this->VOICE_Callback,
                                         'VoiceMethod'          => 'POST',
                                         'VoiceFallbackUrl'     => $this->VOICE_fallback,
                                         'VoiceFallbackMethod'  => 'POST',
                                         'StatusCallback'       => $this->VOICE_status,
                                         'StatusCallbackMethod' => 'POST',
                                     ));

        if($response->IsError) {
            $err = urlencode("Error purchasing number: $response->ErrorMessage");
            return $err;
        }

        return TRUE;
    }
}

?>

I also provided the constant variables in config.php. You’ve to provide your own API Key, token, Twilio Phone Number in this variables.

//Third Party Library Configuratio
$config['twilio_sid']           =   'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$config['twilio_token']         =   'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$config['twilio_phone']         =   'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$config['twilio_phone_display'] =   'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$config['twilio_sms_callback']  =   $config['base_url'] . '/sms'; //it should be our application's dedicated sms url
$config['twilio_voice_callback']=   $config['base_url'] . '/voice'; //it should be our application's dedicated voice url
$config['twilio_voice_fallback']=   $config['base_url'] . '/voice/fallback';
$config['twilio_voice_status']  =   $config['base_url'] . '/voice/status';

In my class you’ll see 3 functions

  1. public function send_sms($number, $message);
  2. public function search_mobile_numbers($zip=”, $postal=”, $country=’US’, $failsearch=FALSE);
  3. public function buy_mobile_number($number);

Using send_sms() function you just have to provide the phone number and message to send as text. Using search_mobile_numbers() function you can search and get the available phone numbers based on ZIP, POSTAL and Country code. And the final function buy_mobile_number() you can purchase the number from Twilio and from then that number will be not available for other users.

We also integrated some other features like some voice, automatic SMS answer when user send text to a number. But for simplicity I’ve not described them in this post.Hope this article will help you to work on Twilio.

About mahmud ahsan

Programming is my passion from high school. I always looking for innovating new ideas and making them real application. I love mobile application and game development as well as web development. Having 4+ years web development experience and 6+ years mobile application development experience on different platform and business on it. My Mobile Apps Portfolio: iThinkdiff.net Mobile Apps

, , , ,

11 Responses to Twilio API for SMS based web application

  1. jeffrey March 13, 2012 at 7:35 pm #

    WOW! this is amazing. , Thanks for tut.

    http://alltour4you.com

  2. industrial training indore March 19, 2012 at 6:20 pm #

    Hello there I am so delighted I found your blog page, I really found you by mistake, while I was researching for something else,
    Regardless I am here now and would just like to say many thanks for a remarkable post and a all round enjoyable blog.Please do keep up the excellent work.

  3. Gadgets April 8, 2012 at 7:11 pm #

    Very nice Information and good post… Thanks for posting that….

  4. dynaprocess May 5, 2012 at 12:55 am #

    I Like it, is there any visual tools for that?
    Thank you

  5. Josh June 22, 2012 at 8:11 pm #

    Great article! I am also trying to use Twilio for my organization. We will be sending texts about 3 times a week to about 6 million people. I am skeptical as per the costs, since that will cost over $200, 000 a week. What are your thoughts?

    • mahmud ahsan June 24, 2012 at 6:21 pm #

      You can check if there are other similar but cheaper service available or not

    • Shawn July 13, 2012 at 6:39 pm #

      Josh – I’m curious to know if you found a solution to your problem. My understanding of the limitations of the Twilio API are that it will send 1 msg per second. For your six million people that would be over 69 days to send each message.

      • mahmud ahsan July 13, 2012 at 9:25 pm #

        I long time didn’t work about this API. Please contact with them if they support bulk SMS send service.

  6. Serg August 7, 2012 at 8:40 am #

    Thanks for the API.Will take a look at the twilio apps

  7. IT PIONEER December 26, 2012 at 8:41 pm #

    Hi guys, anyone please i need assistance. I am new to twilio however am trying my best to make things happen Currently am stuck on my application that a user is supposed to call and enter his special user code and compare with the database in the server. I tried with the sample of sql lite it works fine but for my case i need to use MYSQL. Please i need help in summary. User calls, enter the cide number-> checks in the db -> and proceed to record the message.

  8. tummy tuck sydney February 4, 2013 at 5:03 pm #

    thanks for sharing your knowledge….can i use this in joomal ?