Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Twilio Cookbook: Second Edition
Twilio Cookbook: Second Edition

Twilio Cookbook: Second Edition: Over 70 easy-to-follow recipes, from exploring the key features of Twilio to building advanced telephony apps

eBook
$9.99 $32.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

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

Twilio Cookbook: Second Edition

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 passwordis ".$password."To repeat that, your passwordis ".$password;
        $item = $client->account->$method->create(
          $fromNumber,
          $phoneNum,
          $content
        );
        $message = "A new password has been generated and sentto 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 andpassword 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 users 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 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: 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, pleaseenter the extension now, followed by the pound sign.To search the directory, press star. Otherwise, stay onthe line for the receptionist.");
      $r->say("Connecting you to the operator, please stay onthe 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 ofthe party you wish to reach, followed by the poundsign");
      $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 echohtmlspecialchars($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
Estimated delivery fee Deliver to Ukraine

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 26, 2014
Length: 334 pages
Edition :
Language : English
ISBN-13 : 9781783550654
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Ukraine

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Mar 26, 2014
Length: 334 pages
Edition :
Language : English
ISBN-13 : 9781783550654
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 142.97
Twilio Cookbook
$54.99
Twilio Cookbook: Second Edition
$54.99
Twilio Best Practices
$32.99
Total $ 142.97 Stars icon
Banner background image

Table of Contents

13 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
Sending and Receiving Picture Messages Chevron down icon Chevron up icon
Call Queuing Chevron down icon Chevron up icon
Working with Twilio Client Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
kewlking Oct 28, 2014
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
So, got started this cookbook with excitement and high hopes since I needed to get ramped up on Twilio as quickly as possible for a project and come on, you are programming with phone calls and texts - so direct, so much fun!Unfortunately, it takes so long to work around the inaccuracies that it is much much faster to work through the online documentation and quickstarts on the Twilio site - which btw, is beyond awesome!Case in point re: the absurdity of this book, the VERY FIRST SAMPLE will not work. The author sends in a plain text greeting that needs to be played on a call whereas the service expects a URL pointing to a well-formed greeting. You will only realize that after combing through the documentation on the Twilio site.After that rather auspicious start, you will move on to the second recipe where the goal is to do the same thing as before, but do it using SMS instead. Again, you will be stymied with the same errors as earlier, except here, you will realize that in the code downloads, the author simply copied the earlier folder into this one without changing any of the code to shift the functionality from voice to SMS.After a start like this, I gave up trying to grind through the rest of the book and am following the online quickstarts on the Twilio site instead. Now, I don't know if there is a school of thought that believes that stumbling around and groping for answers is the best way to learn, but if you are on a tight schedule and need something focused and *ACCURATE*, then, this is definitely not the book for you.Before you purchase it, try and use the "Look Inside" feature on Amazon to read the first few pages on chapter 1 and you will quickly realize that neither the author nor the publisher has put in any thought around making the content user-friendly. Huge code-sections followed by a 2 line commentary - which would not be the end of the world if it would at least run as intended. And oh btw, needless to say after all the above experiences, don't even bother looking for an errata on the publishers' site - it simply doesn't exist.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela