Tuesday, 26 March 2013

Twilio API for SMS based web application


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.
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?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.
1
2
3
4
5
6
7
8
9
//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.

2 comments:

  1. SMS API integration is the way to integrate SMS services on your panels like website, software, CRM etc. SMS API integration is the easiest way to send automated SMSs directly from your platform.Bulk SMS API

    ReplyDelete
  2. Thanks for sharing this information.

    SMS API PHP

    ReplyDelete