Tracking account usage

Tracking your call usage is important if you handle a lot of calls or if you have a site that has multiple users.

My website, theinterviewr.com, looks through hundreds of calls being made each week; this call usage tracking helps me know which users are making which calls so that I can see who's heavily using the network and who is not.

This also helps me analyze things and make sure I'm actually charging users reasonably per call.

Getting ready

The complete source code for this recipe can be found in the Chapter2/Recipe1 folder in the code bundle available at www.packtpub.com/support.

How to do it...

We're going to build a usage tracking system now to let us look at how our Twilio account is being used. Perform the following steps to do so:

  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. Create a file called functions.php with the following content:
    <?php
    function get_usage( $action ){
      global $accountsid;
      $results = array();
      $fields = array();
      $url = "https://api.twilio.com/2010-04-01/Accounts/{$accountsid}/Usage/Records";
      switch($action){
        case 'lm':  //  last month
            $url = $url."/LastMonth.json";
          break;
        case 'custom':
          $startd = $_GET['startd'];
          $endd = $_GET['endd'];
          $startd = date('Y-m-d',strtotime($startd));
          $endd = date('Y-m-d',strtotime($endd));
            $url = $url."/Daily.json";
          $fields = array(
            "Category"=>'calls-inbound',
            "StartDate"=>$startd,
            "EndDate"=>$endd
          );
          break;
        case 'all':
            $url = $url.".json";
          break;
        case 'today':
        default:
          $url = $url."/Today.json";
          break;
      }
      if ( isset($url) ){
          $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);
          if( count($fields) > 0 ){
        foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
        rtrim($fields_string,'&');
                curl_setopt($ch,CURLOPT_POST,count($fields));
                curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
            }
          $results = curl_exec($ch);
          $info = curl_getinfo($ch);
          curl_close($ch);
          return json_decode( $results );
      }
      return array();
    }
    Note

    functions.php is the file that actually handles communicating with Twilio and returning the usage information.

  5. Create a file on your website called call-usage.php, with the following code:
    <?php
      session_start();
      include 'Services/Twilio.php';
      include("config.php");
      include("functions.php");
     
      $client = new Services_Twilio($accountsid, $authtoken);
    
      $action = isset($_GET['action']) ? $_GET['action'] : 'today';
    ?>
      <nav>
        <a href="call-usage.php?action=today">Today</a>
        <a href="call-usage.php?action=lm">Last Month</a>
        <a href="call-usage.php?action=all">All Calls</a>
        <span>Custom Report:</span>
        <form action="" method="GET">
          <input type="hidden" name="action" value="custom" />
          <input type="date" name="startd" placeholder="Start Date" />
          <input type="date" name="endd" placeholder="End Date" />
          <button type="submit">Generate</button>
        </form>
      </nav>
      <hr />
    <?php
      $results = get_usage($action){
    
      if( count($results > 0) ){
    #    echo '<pre>'.print_r($results,true).'</pre>';
    ?>
        <table width=100%>
        <thead>
        <tr>
          <th>Category</th>
          <th>Description</th>
          <th>SID</th>
          <th>Start Date</th>
          <th>End Date</th>
          <th>Usage</th>
          <th>Usage Unit</th>
          <th>Price</th>
          <th>Price Unit</th>
        </tr>
        </thead>
        <tbody>
    <?php  foreach( $results->usage_records as $row ){  ?>
        <tr>
          <td><?= $row->category?></td>
          <td><?= $row->description?></td>
          <th><?= $row->account_sid?></th>
          <td><?= $row->start_date?></td>
          <td><?= $row->end_date?></td>
          <td><?= $row->usage?></td>
          <td><?= $row->usage_unit?></td>
          <td><?= $row->price?></td>
          <td><?= $row->price_unit?></td>
        </tr>
    <?php   }  ?>
        </tbody>
        </table>
    <?php
      }
    ?>

How it works...

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

In step 3, we uploaded config.php, which contains our authentication information to communicate with Twilio's API.

In step 4, we uploaded functions.php, which includes the function get_usage.php file; this function takes your account ID, as well as the criteria you chose to search by, and returns a JSON-encoded document from Twilio.

We then display the usage logs on the site to view. This usage tracker displays the account that performed the call, the number of minutes, and the cost for the call. If you use subaccounts, it is handy for knowing what to bill your users each month.

This recipe also displays reports as per the present day, past week, past month, and also custom dates. This works well for getting an idea of how much usage you actually have.