Home Business & Other Twilio Cookbook

Twilio Cookbook

By Roger Stringer
books-svg-icon Book
eBook $32.99 $22.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $32.99 $22.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Into the Frying Pan
About this book
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.
Publication date:
September 2013
Publisher
Packt
Pages
266
ISBN
9781782166061

 

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.

About the Author
  • Roger Stringer

    Roger Stringer has been a PHP developer since 2001 and has been working on projects of all sizes for companies all over the world. He has formed several start-ups over the years and most of them have been powered by Twilio to provide services. When not working on the web, Roger can be found reading, cooking, and spending time with his daughter, Kaitlyn, at the local farmer's markets. Roger is the founder of The Interviewer, a Twilio-powered startup, which makes interviewing more efficient by helping with scheduling, contact management, and conducting and recording interviews.

    Browse publications by this author
Twilio Cookbook
Unlock this book and the full library FREE for 7 days
Start now