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

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.