Book Image

Twilio Cookbook

By : Roger Stringer
Book Image

Twilio Cookbook

By: Roger Stringer

Overview of 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.
Table of Contents (17 chapters)
Twilio Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

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.