Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Twilio Cookbook
Twilio Cookbook

Twilio Cookbook: The Twilio cookbook will enable all kinds of telephone usage, including SMS, on your websites. It's a totally practical guide with a hands-on approach to help you dig deep into the enormous potential of telephone facilities on the Web.

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Twilio Cookbook

Chapter 1. Into the Frying Pan

In this chapter we will cover:

  • Adding two-factor voice authentication to verify users

  • Using Twilio SMS to set up two-factor authentication for secure websites

  • Adding order verification

  • Adding Click-to-Call functionality to your website

  • Recording a phone call

  • Setting up a company directory

  • Setting up Text-to-Speech

Introduction


Twilio's API allows you to do some incredible things. Combine it with PHP and you have a powerful tool that you can use to enhance your business or even build entirely new businesses around it.

I've worked with Twilio on dozens of projects over the past three and a half years and have built entire startups around it such as TheInterviewr.com.

This chapter will get you started on using Twilio for two-factor authentication functionality, order verification, adding Click-to-Call to your website, recording phone calls, setting up a company directory, and using Twilio Client to add Text-to-Speech capabilities to your website.

Before we begin, you'll need a twilio.com account, so go to http://twilio.com and sign up.

To get started, you will want to have Twilio's helper library at http://www.twilio.com/docs/libraries.

You can get your Twilio ACCOUNT SID and AUTH TOKEN from your account page here:

You can also click on NUMBERS to manage your list:

Now, let's get started with some code...

Adding two-factor voice authentication to verify users


Being able to verify that the users are actual users, and being able to help them have better security, is an important factor for everyone, and that's where two-factor authentication comes in handy.

Two-factor authentication is a more secure way of logging in to a website. In addition to entering a password online, a user has to enter a random verification code generated at login time. This combination of passwords makes it easier to safeguard your applications.

Two-factor authentication is used in:

  • E-commerce sites

  • Sites that allow users to sign up

  • Recovering lost passwords (by sending the new code to a phone number already saved)

More and more big web services are starting to activate two-factor authentication as they realize how important it can be. Amazon, Google, and Apple are just some of the companies that have begun utilizing two-factor authentication for user protection.

Getting ready

The complete source code for this recipe can be found in at Chapter1/Recipe1.

How to do it...

We're going to build our first Twilio app, a two-factor voice authentication system. This can be plugged into websites to allow users to get called on a phone and verify whether they are who they say they are. Perform the following steps:

  1. Download the Twilio Helper Library (from https://github.com/twilio/twilio-php/zipball/master) and unzip it.

  2. Upload the Services/ folder to your website.

  3. Upload config.php to your website and make sure the following variables are set:

    <?php
      $accountsid = '';	//	YOUR TWILIO ACCOUNT SID
      $authtoken = '';	//	YOUR TWILIO AUTH TOKEN
      $fromNumber = '';	//	PHONE NUMBER CALLS WILL COME FROM
    ?>

    This file will let you configure your web app with your Twilio account information.

  4. We'll set up a file called two-factor-voice.php, which will sit on your web server. This file handles the two-factor authentication:

    <?php
      session_start();
      include 'Services/Twilio.php';
      include 'config.php';
      include 'functions.php';
      $username = cleanVar('username');
      $password = cleanVar('password');
      $phoneNum = cleanVar('phone_number');
      if( isset($_POST['action']) ){
        if( isset($_POST['username']) &&
          isset($_POST['phone_number'])
          ){
          $message = user_generate_token($username,
            $phoneNum,'calls');
        }else if( isset($_POST['username']) &&
          isset($_POST['password']) ){
          $message = user_login($username, $password);
        }
        header("Location: two-factor-voice.php?message=" .urlencode($message));
        exit;
      }
    ?>
    <html>
    <body>
      <p>Please enter a username, and a phone number you can bereached at, we will then call you with your one-timepassword</p>
      <span id="message">
      <?php
        echo cleanVar('message');
        $action = (isset($_SESSION['password'])) ? 'login' :'token';
      ?>
      </span>
      <form id="reset-form"  method="POST" class="center">
      <input type="hidden" name="action" value="<?php echo$action;?>" />
      <p>Username: <input type="text" name="username"id="username"value="<?php echo $_SESSION['username']; ?>" /></p>
      <?php if (isset($_SESSION['password'])) { ?>
      <p>Password: <input type="password" name="password"id="password" /></p>
      <?php } else { ?>
      <p>Phone Number: <input type="text" name="phone_number"id="phone_number" /></p>
      <input type="hidden" name="method" value="voice" />
      <?php } ?>
      <p><input type="submit" name="submit" id="submit"value="login!"/></p>
      <p>&nbsp;</p>
      </form>
    </body>
    </html>

    You may notice one of the functions we called is cleanVar(); this is a little function I like to use to make sure certain variables, specifically usernames, passwords, and phone numbers, follow a set rule.

  5. Finally, create a file called functions.php on your web server:

    <?php
      function cleanVar($key){
        $retVal = '';
        $retVal = isset( $_REQUEST[$key]) ?
          $_REQUEST[$key] : '';
        switch($key){
          case 'username':
          case 'password':
            $retVal = preg_replace("/[^A-Za-z0-9]/",
              "", $retVal);
            break;
          case 'phone_number':
            $retVal = preg_replace("/[^0-9]/", "", $retVal);
            break;
          case 'message':
            $retVal = urldecode($retVal);
            $retVal = preg_replace("/[^A-Za-z0-9 ,']/",
              "", $retVal);
    
        }
        return $retVal;
      }
    
      function user_generate_token($username, $phoneNum,
        $method='calls'){
        global $accountsid, $authtoken, $fromNumber;
        $password = substr(md5(time().rand(0, 10^10)), 0, 10);
        $_SESSION['username'] = $username;
        $_SESSION['password'] = $password;
        $client = new Services_Twilio($accountsid, $authtoken);
        $content = "Your newly generated password
          is ".$password."To repeat that, your password
          is ".$password;
        $item = $client->account->$method->create(
          $fromNumber,
          $phoneNum,
          $content
        );
        $message = "A new password has been generated and sent
          to your phone number.";
        return $message;
      }
      function user_login($username, $submitted) {
        // Retrieve the stored password
        $stored = $_SESSION['password'];
        // Compare the retrieved vs the stored password
        if ($stored == $submitted) {
          $message = "Hello and welcome back $username";
        }else {
          $message = "Sorry, that's an invalid username and
            password combination.";
        }
        // Clean up after ourselves
        unset($_SESSION['username']);
        unset($_SESSION['password']);
        return $message;
      }
    ?>

How it works...

In steps 1 and 2, we downloaded and installed the Twilio Helper Library for PHP; this library is the heart of your Twilio-powered apps.

In step 3, we uploaded config.php that contains our authentication information to talk to Twilio's API.

When your users go to two-factor-voice.php, they are presented with a form where they enter a username and their phone number. Once they submit the form, it generates a one-time usage password and sends it as a text message to the phone number they entered. They then enter this password in the form on the site to verify that they are who they say they are.

I've used this on several different types of websites; it's a feature that people always want in some way to help verify that your users are who they say they are.

Using Twilio SMS to set up two-factor authentication for secure websites


This recipe is similar to the two-factor voice authentication recipe but uses SMS instead and texts the user their one-time password.

Again, two-factor authentication is an important tool to verify your users for various purposes and should be used on sites if you care at all about user security.

Forcing a user to verify their identity using two-factor authentication, in order to do something as simple as changing their password, can help promote trust between both you and your users.

Getting ready

The complete source code for this recipe can be found at Chapter1/Recipe2.

How to do it...

We're going to build our first Twilio app, a two-factor SMS authentication system. This can be plugged into websites to allow users to get called on a phone and verify that they are who they say they are.

  1. Download the Twilio Helper Library (from https://github.com/twilio/twilio-php/zipball/master) and unzip it.

  2. Upload the Services/ folder to your website.

  3. Upload config.php to your website and make sure the following variables are set:

    <?php
      $accountsid = '';  //  YOUR TWILIO ACCOUNT SID
      $authtoken = '';  //	  YOUR TWILIO AUTH TOKEN
      $fromNumber = '';  //  PHONE NUMBER CALLS WILL COME FROM
    ?>
  4. We'll set up a file called two-factor-sms.php, which will sit on your web server; this file handles the two-factor authentication.

    <?php
      session_start();
      include 'Services/Twilio.php';
      include 'config.php';
      include 'functions.php';
      $username = cleanVar('username');
      $password = cleanVar('password');
      $phoneNum = cleanVar('phone_number');
      if( isset($_POST['action']) ){
        if( isset($_POST['username']) &&
          isset($_POST['phone_number'])){
          $message = user_generate_token($username, $phoneNum,
            'sms');
      }else if( isset($_POST['username']) &&
        isset($_POST['password'])
        ){
        $message = user_login($username, $password);
      }
    
      header("Location: two-factor-sms.php?message=" .urlencode($message));
      exit;
    }
    ?>
    <html>
    <body>
    <p>Please enter a username, and a phone number you can be reached at, we will then send you your one-time password via SMS.</p>
    <span id="message">
    <?php
      echo cleanVar('message');
      $action = (isset($_SESSION['password'])) ? 'login' : 'token';
    ?>
    </span>
    <form id="reset-form"  method="POST" class="center">
    <input type="hidden" name="action" value="<?php echo$action; ?>"/>
    <p>Username: <input type="text" name="username"id="username" value="<?php echo $_SESSION['username'];?>" /></p>
    <?php if (isset($_SESSION['password'])) { ?>
      <p>Password: <input type="password" name="password"id="password" /></p>
    <?php } else { ?>
      <p>Phone Number: <input type="text" name="phone_number"id="phone_number" /></p>
      <input type="hidden" name="method" value="sms" checked="checked"/>
    <?php } ?>
    <p><input type="submit" name="submit" id="submit"value="login!"/></p>
    <p>&nbsp;</p>
    </form>
    </body>
    </html>
  5. Finally, we're going to include the same functions.php file we used in the Adding two-factor voice authentication to verify user s recipe.

How it works...

In steps 1 and 2, we downloaded and installed the Twilio Helper Library for PHP; this library is the heart of your Twilio-powered apps.

In step 3, we uploaded config.php that contains our authentication information to talk to Twilio's API.

Your user is presented with a form where they enter a username and their phone number. Once they submit the form, it generates a one-time usage password and sends it as a text message to the phone number they entered. They then enter this password in the form on the site to verify that they are who they say they are.

What's the big difference between recipes 1 and 2? Really, it's that one does voice and one does SMS. You could combine these as options if you wanted to so that people can choose between voice or SMS. The biggest key is when you call the function user_generate_token; you specify the method as either calls or sms.

Adding order verification


If you handle any type of commerce, such as e-commerce and callin orders, you know that giving your customers a way to quickly check their orders is handy for selling anything.

Making things easy for customers keeps them coming back again; having a way for your customers to just text you an order ID and tracking their purchase at any time is really handy.

In this example, a user will text an order ID and we will return a result based on an array.

The array will be formatted by order ID and status as follows:

$orders = array(
  'order id'=>'status'
);

Getting ready

The complete source code for this recipe can be found at Chapter1/Recipe3.

How to do it...

We're going to set up a simple order verification system. A user will text us an order number and we will reply back with the status of that order.

  1. Upload a file called order_verification.php to your server:

      <?php
        $orders = array(
          '111'=>'shipped',
          '222'=>'processing',
          '333'=>'awaiting fullfillment'
        );
        if( isset($_POST['Body']) ){
          $phone = $_POST['From'];
          $order_id = strtolower($_POST['Body']);
          $status = order_lookup($order_id);
          print_sms_reply("Your order is currently set atstatus'".$status."'");
        }else{
          print_sms_reply("Please send us your order id and wewill look it up ASAP");
        }
        function print_sms_reply ($sms_reply){
          echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
          echo "<Response>\n<Sms>\n";
          echo $sms_reply;
          echo "</Sms></Response>\n";
        }
        function order_lookup($order_id){
          global $orders;
          if( isset($orders[$order_id]) ){
            return $orders[$order_id];
          }
          return 'No Order Matching that ID was found';
        }
      ?>
  2. To have a number point to this script, log in to your Twilio account and point your Twilio phone number to it:

Insert the URL in the SMS Request URL field on this page. Then, any text messages that you receive on this number will be processed via order_verification.php.

How it works...

In step 1, we created order_verification.php.

In step 2, we configured a number in our Twilio account to call order_verification.php.

This is a one-step recipe. A user sends you a text message containing their order ID; you then perform a lookup and return the status.

If no order exists, it returns that the order wasn't found in the system.

Adding the Click-to-Call functionality to your website


Click-to-Call is a handy functionality where you can have your website visitors click a button to start a call. This can be useful for handling support, sales calls, or just chatting with your users.

Getting ready

The complete source code for this recipe can be found at Chapter1/Recipe4.

How to do it...

Ready? We're going to build a simple Click-to-Call system. With this, you can set up any website to allow a visitor to type in a phone number and connect a call between you and them.

  1. Download the Twilio Helper Library ( from https://github.com/twilio/twilio-php/zipball/master) and unzip it.

  2. Upload the Services/ folder to your website.

  3. Upload config.php to your website and make sure the following variables are set:

    <?php
      $accountsid = '';  //  YOUR TWILIO ACCOUNT SID
      $authtoken = '';  //	  YOUR TWILIO AUTH TOKEN
      $fromNumber = '';  //  PHONE NUMBER CALLS WILL COME FROM
      $toNumber = '';  //  YOUR PHONE NUMBER TO CONNECT TO
    ?>
  4. Upload a file called click-to-call.php to your website:

    <?php
    session_start();
    include 'Services/Twilio.php';
    include("config.php");
    if( isset($_GET['msg']) )
      echo $msg;
    ?>
    <h3>Please enter your phone number, and you will be connected to <?=$toNumber?></h3>
    <form action="makecall.php" method="post">
    <span>Your Number: <input type="text" name="called"/></span>
    <input type="submit" value="Connect me!" />
    </form>

    This file displays a form that, when submitted, triggers the rest of the calling process.

  5. Now, upload a file named makecall.php to your website:

    <?php
    session_start();
    include 'Services/Twilio.php';
    include("config.php");
    
    $client = new Services_Twilio($accountsid, $authtoken);
    if (!isset($_REQUEST['called'])) {
      $err = urlencode("Must specify your phone number");
      header("Location: click-to-call.php?msg=$err");
      die;
    }
    $call = $client->account->calls->create($fromNumber,$toNumber,'callback.php?number=' . $_REQUEST['called']);
    $msg = urlencode("Connecting... ".$call->sid);
    header("Location: click-to-call.php?msg=$msg");
    ?>
  6. Finally, upload a file named callback.php to your website:

    <?php
      header("content-type: text/xml");
      echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    ?>
    <Response>
      <Say>A customer at the number <?php echo$_REQUEST['number']?>is calling</Say>
      <Dial><?php echo $_REQUEST['number']?></Dial>
    </Response>

How it works...

In steps 1 and 2, we downloaded and installed the Twilio Helper Library for PHP.

In step 3, we uploaded config.php containing our authentication information to talk to Twilio's API.

In steps 4, 5, and 6, we created the backbone of our Click-to-Call system.

We display a form on your website, where a user enters his or her phone number and clicks the Connect me! button. The system then calls your phone number; once you answer, it will connect you to the user.

Recording a phone call


Recording a call is handy for conducting interviews. In this example, we're going to build on the Click-to-Call recipe and add in the ability to record the call.

Getting ready

The complete source code for this recipe can be found at Chapter1/Recipe5.

How to do it...

This recipe will expand on our Click-to-Call system to include the ability to record the phone call. We'll also set up a nice method to retrieve recordings.

  1. Download the Twilio Helper Library (from https://github.com/twilio/twilio-php/zipball/master) and unzip it.

  2. Upload the Services/ folder to your website.

  3. Upload config.php to your website and make sure the following variables are set:

    <?php
      $accountsid = '';  //  YOUR TWILIO ACCOUNT SID
      $authtoken = '';  //  YOUR TWILIO AUTH TOKEN
      $fromNumber = '';  //  PHONE NUMBER CALLS WILL COME FROM
      $toNumber = '';  // 	 YOUR PHONE NUMBER TO CONNECT TO
      $toEmail = ''; // YOUR EMAIL ADDRESS TO SEND RECORDING TO
    ?>
  4. Upload a file called record-call.php to your website:

    <?php
    session_start();
    include 'Services/Twilio.php';
    include("config.php");
    if( isset($_GET['msg']) )
      echo $msg;
    ?>
    <h3>Please enter your phone number, and you will beconnected to <?=$toNumber?></h3>
    <form action="makecall.php" method="post">
    <span>Your Number: <input type="text"name="called" /></span>
    <input type="submit" value="Connect me!" />
    </form>

    This file displays a form that, when submitted, triggers the rest of the calling process.

  5. Now, upload a file named makecall.php to your website:

    <?php
    session_start();
    include 'Services/Twilio.php';
    include("config.php");
    $client = new Services_Twilio($accountsid, $authtoken);
    if (!isset($_REQUEST['called'])) {
      $err = urlencode("Must specify your phone number");
      header("Location: record-call.php?msg=$err");
      die;
    }
    
    $url = (!empty($_SERVER['HTTPS'])) ?"https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']:"http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    $url = str_replace("makecall","recording",$url);
    
    $call = $client->account->calls->create($fromNumber, $to,'callback.php?number=' .$_REQUEST['called'],array("record"=>true));
    
    $msg = urlencode("Connecting... ".$call->sid);
    $_SESSION['csid'] = $call->sid;
    $RecordingUrl = $url."?csid=".$call->sid;
    $subject = "New phone recording from{$_REQUEST['called']}";
    $body = "You have a new phone recording from{$_REQUEST['called']}:\n\n";
    
    $body .= $RecordingUrl;
    
    $headers = 'From: noreply@'.$_SERVER['SERVER_NAME']. "\r\n" .
      'Reply-To: noreply@'.$_SERVER['SERVER_NAME'] . "\r\n" .
      'X-Mailer: Twilio';
    mail($toEmail, $subject, $body, $headers);
    header("Location: record-call.php?msg=$msg");
    ?>

    The makecall.php file handles the actual setting up of the call and also sends you an e-mail that provides you with a link to view the recording.

  6. Next, upload a file named callback.php to your website:

    <?php
      header("content-type: text/xml");
      echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    ?>
    <Response>
      <Say>A customer at the number <?php echo$_REQUEST['number']?> is calling</Say>
      <Dial record=true><?php echo $_REQUEST['number']?></Dial>
    </Response>

    Did you catch what we did here? We told the Dial command to record the call. This means anything that is spoken during this call is now recorded.

  7. Finally, upload a file named recording.php to your website:

    <?php
    if( isset($_GET['csid']) ){
      getRecording( $_GET['csid'] );
    }else{
      die( "Invalid recording!");
    }
    function getRecording($caSID){
      global $accountsid,$authtoken;
        $version = '2010-04-01';
        $url = "https://api.twilio.com/2010-04-01/Accounts/{$accountsid}/Calls/{$caSID}/Recordings.xml";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERPWD,"{$accountsid}:{$authtoken}");
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        $output = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
        $output = simplexml_load_string($output);
        echo "<table>";
        foreach ($output->Recordings->Recording as $recording)
    	{
          echo "<tr>";
          echo "<td>".$recording->Duration." seconds</td>";
          echo "<td>".$recording->DateCreated."</td>";
          echo '<td><audio src="https://api.twilio.com/2010-04-01/Accounts/'.$sid.'/Recordings/'.$recording->Sid.'.mp3" controls preload="auto"autobuffer></audio></td>';
            echo "</tr>";
        }
        echo "</table>";
    }

How it works...

In steps 1 and 2, we downloaded and installed the Twilio Helper Library for PHP.

In step 3, we uploaded config.php that contains our authentication information to talk to Twilio's API.

In steps 4, 5, and 6, we re-created the Click-to-Call functionality from the previous recipe but with one difference: we also set makecall.php to e-mail us a link to do the recording, as well as setting callback.php to actually do the recording.

As with the preceding Adding Click-to-Call functionality to your website recipe, a user is presented with a form on the website where they enter their information and click to begin a call. The difference here is that the call is actually recorded; once it's finished, the system e-mails you a link to listen to your recording.

One thing to remember with recordings is that it could take a few minutes after the call for the recording to be available. Hence, the script e-mails you a link to view the recording instead of the recording itself.

Setting up a company directory


A company directory is a very handy thing to have when you want a company phone number to be published and then have it contact other people in your company. It's also nice to make it searchable and that is what we are doing today.

This particular company directory has served me well at several companies I've worked with over the years and I'm especially pleased with its ability to convert names into their matching digits on a phone pad using this function:

  function stringToDigits($str) {
    $str = strtolower($str);
    $from = 'abcdefghijklmnopqrstuvwxyz';
    $to = '22233344455566677778889999';
    return preg_replace('/[^0-9]/', '', strtr($str, $from, $to));
  }

This function works such that a name such as Stringer (my last name), gets converted into 78746437. Then, as the caller does a search, it will return an employee whose name matches the digits entered and will then connect the call.

Getting ready

The complete source code for this recipe can be found at Chapter1/Recipe6.

How to do it...

We're going to build a basic, searchable company directory that will let callers either enter an extension or search by their last name.

  1. Download the Twilio Helper Library (from https://github.com/twilio/twilio-php/zipball/master) and unzip it.

  2. Upload the Services/ folder to your website.

  3. Upload config.php to your website and make sure the following variables are set:

    <?php
      $accountsid = '';  //  YOUR TWILIO ACCOUNT SID
      $authtoken = '';  //  YOUR TWILIO AUTH TOKEN
      $fromNumber = '';  //  PHONE NUMBER CALLS WILL COME FROM
    ?>
  4. Let's create the file called company-directory-map.php, which sets up the map for the company directory:

    <?php
      $directory = array(
        '0'=> array(
          'phone'=>'415-555-1111',
          'firstname' => 'John',
          'lastname' => 'Smith'
        ),
        '1234'=> array(
          'phone'=>'415-555-2222',
          'firstname' => 'Joe',
          'lastname' => 'Doe'
        ),
        '4321'=> array(
          'phone'=>'415-555-3333',
          'firstname' => 'Eric',
          'lastname' => 'Anderson'
        ),
      );
      $indexes = array();
      foreach($directory as $k=>$row){
        $digits = stringToDigits( $row['lastname'] );
        $indexes[ $digits] = $k;
      }
      function stringToDigits($str) {
        $str = strtolower($str);
        $from = 'abcdefghijklmnopqrstuvwxyz';
        $to = '22233344455566677778889999';
        return preg_replace('/[^0-9]/', '', strtr($str, $from,$to));
      }
      function getPhoneNumberByExtension($ext){
        global $directory;
        if( isset( $directory[$ext] ) ){
          return $directory[$ext];
        }
        return false;
      }
      function getPhoneNumberByDigits($digits){
        global $directory,$indexes;
        $search = false;
        foreach( $indexes as $i=>$ext ){
          if( stristr($i,$digits) ){
            $line = $directory[ $ext ];
            $search = array();
            $search['name']= $line['firstname']."".$line['lastname'];
            $search['extension']=$ext;
          }
        }
        return $search;
      }
    ?>

    This file handles the list of extensions, and also takes care of the functions that handle the searching. One of the steps it performs is to loop through each extension and convert the last name into digits corresponding with a phone pad.

  5. Now, we'll create company-directory.php to handle the logic for incoming calls:

    <?php
      session_start();
      include 'Services/Twilio.php';
      include 'config.php';
      include('company-directory-map.php');
      $first = true;
      if (isset($_REQUEST['Digits'])) {
        $digits = $_REQUEST['Digits'];
        if( $digits == "*"){
          header("Location: company-directory-lookup?Digits=".$digits);
          exit();
        }
      } else {
        $digits='';
      }
      if( strlen($digits) ){
        $first = false; 
        $phone_number = getPhoneNumberByExtension($digits);
        if($phone_number!=null){
          $r = new Services_Twilio_Twiml();
          $r->say("Thank you, dialing now");
          $r->dial($phone_number);
          header ("Content-Type:text/xml");
          print $r;
          exit();
        }
      }
      $r = new Services_Twilio_Twiml();
      $g = $r->gather();
      if($first){
        $g->say("Thank you for calling our company.");
      }else{
        $g->say('I\'m sorry, we could not find the extension '. $_REQUEST['Digits']);
      }
      $g->say(" If you know your party's extension, please enter the extension now, followed by the pound sign. To search the directory, press star. Otherwise, stay on the line for the receptionist.");
      $r->say("Connecting you to the operator, please stay on the line.");
      $r->dial($receptionist_phone_number);
      header ("Content-Type:text/xml");
      print $r;
      exit;
    ?>

    All incoming calls will first come into this file and, from there, will either be redirected straight to an extension or start the lookup process based on the last name.

  6. And finally, we create company-directory-lookup.php that adds the ability to perform search operations:

    <?php
      session_start();
      include 'Services/Twilio.php';
      include 'config.php';
      include('company-directory-map.php');
      $error = false;
      if (isset($_REQUEST['Digits'])){
        $digits = $_REQUEST['Digits'];
      }else{
        $digits='';
      }
      if(strlen($digits)){
        $result = getPhoneNumberByDigits($digits);
        if($result != false){
          $number = getPhoneNumberByExtension($result['extension']);
          $r = new Services_Twilio_Twiml();
          $r->say($result['name']."'s extension is".$result['extension']." Connecting you now");
          $r->dial($number);
          header ("Content-Type:text/xml");
          print $r;
          exit();
        } else {
          $error=true;
        }
      }
      $r = new Services_Twilio_Twiml();
      if($error)	$r->say("No match found for $digits");
      $g = $r->gather();
      $g->say("Enter the first four digits of the last name of the party you wish to reach, followed by the poun dsign");
      $r->say("I did not receive a response from you");
      $r->redirect("company-directory.php");
      header ("Content-Type:text/xml");
      print $r;
    ?>

    This file handles our lookups; as a caller types digits into a phone dial pad, this script will loop through the extensions to find a name that matches the digits entered.

  7. Finally, we need to have a number point to this script. Upload company-directory.php somewhere and then point your Twilio phone number to it:

    Insert the URL in the Voice Request URL field on this page. Then, any calls that you receive at this number will be processed via company-directory.php.

How it works...

In steps 1 and 2, we downloaded and installed the Twilio Helper Library for PHP.

In step 3, we uploaded config.php that contains our authentication information to talk to Twilio's API.

In step 4, we set up the $directory array in company-directory-map.php, which is the core of this system; it handles the extension number for each employee as well as containing his/her phone number, first name, and last name.

When a caller chooses to search for an employee, the last name is converted into corresponding digits similar to what you see on a phone.

So for example, Stringer becomes 78746437; as the caller does a search, it will return an employee whose name matches and will then connect the call.

Finally, in step 7, we set up our phone number in Twilio to point to the location where company-directory.php has been uploaded so that all calls to that phone number go straight to company-directory.php.

You now have a nice, searchable company directory. I've been using this directory myself for the last two years at various companies and it works nicely.

Setting up Text-to-Speech


The final recipe of this chapter is going to use the Twilio Client to add handy functionality on your site.

Text-to-Speech is useful for having a voice read back text on a web page. You could do this by having a textbox of text that gets read back; or maybe you want to select text on a web page to be read back to a visitor.

Twilio Client is also handy for doing phone work straight from your browser.

Getting ready

The complete source code for this recipe can be found at Chapter1/Recipe7.

How to do it...

We're going to use the Twilio Client to set up a form where people can type in a message and have it spoken back to them either by a male or female voice.

  1. First, since this is using the Twilio Client, you need to set up a Twiml app under your account.

    Click on the Create TwiML App button and enter a name for your app. Also, you'll need to enter a URL for the Voice. In this case, set it to the URL where you have uploaded incoming_call.php, that is, http://MYWEBSITE.COM/incoming_call.php.

    Now, go back to the application list and you will see your new app. Look at the line directly beneath the name of your app; this is your app SID. Copy that as you will need it for this recipe.

  2. Download the Twilio Helper Library from https://github.com/twilio/twilio-php/zipball/master and unzip it.

  3. Upload the Services/ folder to your website.

  4. Upload config.php to your website and make sure the following variables are set:

    <?php
      $accountsid = '';  //  YOUR TWILIO ACCOUNT SID
      $authtoken = '';  //	  YOUR TWILIO AUTH TOKEN
      $fromNumber = '';  //  PHONE NUMBER CALLS WILL COME FROM
    ?>
  5. Let's create a file on your website called text-to-speech.php:

    <?php
      require_once('Services/Twilio/Capability.php');
      include("config.php");
      $APP_SID = 'YOUR APP SID';
      $token = new Services_Twilio_Capability($accountsid,$authtoken);
      $token->allowClientOutgoing($APP_SID);
    ?>
    <html> 
    <head> 
      <title>Text-To-Speech</title>
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
      <script type="text/javascript"src="//static.twilio.com/libs/twiliojs/1.1/twilio.min.js"></script>
      <script type="text/javascript"> 
        Twilio.Device.setup("<?php echo $token->generateToken();?>",{"debug":true});
        $(document).ready(function() {
          $("#submit").click(function() {
            speak();
          });
        });
        function speak() {
          var dialogue = $("#dialogue").val();
          var voice =$('input:radio[name=voice]:checked').val();
          $('#submit').attr('disabled', 'disabled');
          Twilio.Device.connect({ 'dialogue' :dialogue, 'voice' : voice });
        }
        Twilio.Device.disconnect(function (conn) {
          $('#submit').removeAttr('disabled');
        });
      </script> 
    </head> 
    <body> 
    <p> 
      <label for="dialogue">Text to be spoken</label> 
      <input type="text" id="dialogue" name="dialogue"size="50">
    </p>
    <p>
      <label for="voice-male">Male Voice</label>
      <input type="radio" id="voice-male" name="voice"value="1" checked="checked"> 
      <label for="voice-female">Female Voice</label> 
      <input type="radio" id="voice-female" name="voice"value="2">
    </p>
    <p>
      <input type="button" id="submit" name="submit"value="Speak to me"> 
    </p> 
    </body> 
    </html>

    Tip

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

  6. Now, let's create another file on your website called incoming_call.php, which is the file Twilio Client will call. This will then read back the text you entered using either a male or female voice:

    <?php
      header('Content-type: text/xml');
      echo '<?xml version="1.0" encoding="UTF-8" ?>';
      $dialogue = trim($_REQUEST['dialogue']);
      $voice = (int) $_REQUEST['voice'];
      if (strlen($dialogue) == 0){
      $dialogue = 'Please enter some text to be spoken.';
      }
    if ($voice == 1){
      $gender = 'man';
    }else {
      $gender = 'woman';
    }
    ?>
    <Response>
      <Say voice="<?php echo $gender; ?>"><?php echo htmlspecialchars($dialogue); ?></Say>
    </Response>

How it works...

In step 1, we set up our Twiml app in our Twilio account.

In steps 2 and 3, we downloaded and installed the Twilio Helper Library for PHP.

In step 4, we uploaded config.php that contains our authentication information to talk to Twilio's API.

Using Twilio Client, this recipe will read the content of a text box and play it back to you in either a male or female voice.

Twilio Client is a nice addition to the Twilio API that lets you do phone work straight from the browser. This way, you can add functionality directly to your web apps.

Left arrow icon Right arrow icon

Key benefits

  • Teaches software developers to programmatically make and receive phone calls and send and receive text messages using Twilio's web service APIs
  • The only book that teaches you how to set up your own conference calling system or how to build a PBX for your company, or how to build a local solution that can tell you the weather where you are
  • Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible

Description

Have you ever wanted to integrate phone features into a project you were working on? Maybe you wanted to send SMS messages to your customers about the latest sales? Maybe you want to set up a company directory with voice mail? Or maybe you want to add two factor authentication to your web sites to verify your users? Since Twilio was launched in 2007, developers have had a way to do these tasks. The power of Twilio's API is huge and lets you add any type of phone solution to your web site from 2-factor authentication for verifying your users, to setting up a company directory and a voice mail system. The possibilities are endless. "Twilio Cookbook" is your Swiss army knife for Twilio development, providing you with a number of clear step-by-step exercises. It helps you take advantage of the real power of the Twilio API, and gives you a good grounding in using it in your websites. This book looks at the Twilio API, and breaks down the mystery and confusion that surrounds adding telephone functionality to your websites. As you go through the recipes, you will learn how to take advantage of the Twilio API quickly and painlessly. You will learn how to build your own IVR system, company directory, and voicemail box, and also how to set up a 2-factor authentication system to verify users, track orders via SMS, send surveys using SMS, allow users to buy phone numbers, set up and delete sub-accounts, and check to see if a human is answering a phone call. We will also combine Twilio with other APIs to build a handy local search system such as a local business search, movie listings search, and web search. If you want to take advantage of using Twilio's API to add telephone functionality to your websites, then this book is for you. "Twilio Cookbook' will leave you with a black belt in Twilio development and enable you to integrate the API into your websites.

Who is this book for?

This book is great for developers who already have knowledge of PHP and MySQL and who want to learn about integrating Twilio's API into their websites for telephone solutions.

What you will learn

  • Add 2-factor authentication to your web apps to verify your users
  • Set up a company directory
  • Buy a phone number
  • Conduct surveys using SMS
  • Set up a conference calling system
  • Use APIs to build a local search system for finding businesses, movies, and weather forecasts
  • Delve into SMS messaging and learn how to set up order tracking, bulk SMS sending, and a group chat system
  • Set up an appointment reminder using SMS
  • Build an interactive IVR menu system
  • Build your first PVR
  • Learn about OpenVBX plugins to extend its existing functionality
  • Verify that a person is answering the phone and not a machine

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 18, 2013
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781782166078
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 18, 2013
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781782166078
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 110.97
Getting Started with WebRTC
€26.99
Twilio Cookbook
€41.99
Building Machine Learning Systems with Python
€41.99
Total 110.97 Stars icon

Table of Contents

10 Chapters
Into the Frying Pan Chevron down icon Chevron up icon
Now We're Cooking Chevron down icon Chevron up icon
Conducting Surveys via SMS Chevron down icon Chevron up icon
Building a Conference Calling System Chevron down icon Chevron up icon
Combining Twilio with Other APIs Chevron down icon Chevron up icon
Sending and Receiving SMS Messages Chevron down icon Chevron up icon
Building a Reminder System Chevron down icon Chevron up icon
Building an IVR System Chevron down icon Chevron up icon
Building Your Own PBX Chevron down icon Chevron up icon
Digging into OpenVBX Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(5 Ratings)
5 star 40%
4 star 40%
3 star 20%
2 star 0%
1 star 0%
Leo Oct 26, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I would definitely recommend this book to anyone doing work on Twilio.There is a section of OpenVBX which is a life saver. I got the book in Kindle edition which I think works better for a reference book like this. Twilio has good sample codes but this brings it to another level. I don't think there is another book on Twilio out there or I just couldn't find one.
Amazon Verified review Amazon
GrahamC Oct 24, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I'd been planning to take a look at Twilio for a while now but other projects kept getting in this way so I was looking forward to getting my hands on the Twilio cookbook.I read the book cover to cover over a long weekend and was able to implement the recipes I needed as soon as I returned to the office.I'd thoroughly recommend this book for anyone considering implementing Twilio into their own solutions.
Amazon Verified review Amazon
David Nov 10, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
_Twilio Cookbook_ is a useful introduction, accessible to PHP developers at all levels, to developing apps using Twilio's telephony platform. I had no experience with Twilio before reading this book and I now feel confident that I could easily incorporate Twilio functionality into my own applications.The book is part of Packt's "Cookbook" series, so it contains a fairly structured format for each application/recipe. The format can be roughly summarized in three steps:* What we are going to do: a brief overview of the app/goal* How to do it: the code, the recipe itself* How it works: a more detailed explanation of what the code achieves The book clearly demonstrates how Twilio can be used to implement a wide variety of web-controlled telephony services, including SMS-based or Voice-based two-factor authentication, SMS-based surveys, conference calling, voice-mail with notifications, and others.In general, the recipes often boil down to:1. put a script (or collection of scripts) on your publicly accessible web-server, and2. point your Twilio phone number to that script.Like other reviewers, I would have liked to see more conceptual overview of Twilio's services. But the Cookbook format is geared towards diving right in to code and building bare-bones functional prototypes. You won't find a lot of advanced web best-practices here - there is no MVC or separation of concerns, there is very little error-checking or escaping of user input, the HTML is un-styled, bare-bones links and forms, there are variables in global scope, etc. As such, the recipes are not really suitable for production use.But for the purposes of the book - demonstrating the core functionality of the Twilio system - stripping out all those considerations is actually beneficial, resulting in a clear exposition without any of those potentially distracting (though definitely necessary) aspects of general app-development.In summary, _Twilio Cookbook_ successfully does what it sets out to do. It demonstrates how to implement a wide range of telephony functionality using PHP and Twilio.
Amazon Verified review Amazon
Aaron Oct 22, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Some people hear about Twilio and immediately think of all the custom code that they can write.Other people just have a quick problem that they want to solve. This is the book for those types of people.It's a great guide for anyone that's heard about Twilio but doesn't quite know where to begin.I thought that the chapter on building an SMS survey app could easily save thousands of dollars in development costs. Grabbing the author's code as a foundation and then building on top of it is a great way to ship a minimal viable product.Advanced Twilio developers will probably have their own set of "recipes" so this book won't be as useful to them.Overall, the Twilio Cookbook is a very practical, hands-on guide to quickly building some of the most common Twilio use cases. If you want to get your feet wet with some real-world Twilio applications, definitely grab this book.
Amazon Verified review Amazon
Roy Buyuksimkesyan Oct 06, 2013
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
For all of you who are lazy and who do not want to read the full review here is a resume:If you need a crash course on Twilio and if you keep in mind that code you will see in the book is for education purposes only, that's a good book that contain solid, tested-and-true recipes. But if you have some spare time to look around the Twilio API and some expertise with PHP I don't think this book will give you a lot and it might even frustrate you in some points (I especially hated the first two steps in every recipe which are the same).Now let's go on with a little bit of detailed review.Book contains 60 recipes to do simple tasks to complex ones. Source codes for all the recipes are given and they are actually easy to follow. But this book does not contain an overview of the Twilio API only methods used in the recipes. An overview of how the Twilio API works, how the authentication is done, how the library communicates with the actual API or what are the most used classes and functions could have been included. Even if it's a cookbook I think I expected such a part that contained basics should have existed.Source codes could definitely have been better. I would understand writing HTMLs and PHP codes together to keep simplicity but executing queries without escaping parameters is not acceptable for me. That wouldn't have added complexity to the source codes but also provided newcomers who just copy and paste things some kind of awareness and security. I have even noticed the usage of "extract" function which might be very harmful for a novice who is not aware what it does.The idea of tested and true functions is good and it's definitely the main difference between the code you find from the Internet and the the code you will find from this book. It will also give you some insight on what can be done and how but that's all. Some of the recipes caused some sense of unease for me. The recipe containing the Bulk SMS could really be harmful when you want to send an sms to hundreds of people. I think such a warning could have been nice.I'm not really fond of cookbooks. The source code used in the books tend to become oudated pretty fast and when the source code is outdated book is not useful at all. There aren't any basics in the book which will give you a cause to keep the book in your library. To keep the source codes as short as possible and simple as possible, the practices used in the book are not state of the art etiher which might have been a use case for the book to give you an idea of the best practices to use the Twilio API etc.I would have liked a part which included what you cannot do with Twilio, or what kind of workarounds you need to do to overcome a problem. But this is a cookbook so it's not actually the purpose of this book.Returning to the resume, if you don't forget that you can't just copy paste the code used in this book for your production environment, this book will definitely give you a good idea on what Twilio can do. It will be a crash course for a seasoned PHP developer. It will definitely be helpful for anyone who wants to implement some simple tasks with Twilio which will be used by themselves and not by some end user. This book will definitely give you an "idea" on how to implement things but that's it.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.