Retrieving Phone Number Pricing for Twilio Programmable Voice using Laravel

August 28, 2020
Written by
Ugendu Ositadinma
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Retrieving Phone Number Pricing for Twilio Programmable Voice using Laravel

The foremost issue when building solutions with third-party services is estimating the cost implications of consuming the API. This tutorial is a guide through the process of understanding the costs of Twilio’s phone number services using a Laravel application.

Installation Requirements

To begin with a Laravel project, all relevant modules required for proper functionality need to be installed. The modules are:

Having installed Laravel on your machine, proceed to create a new project using the Laravel CLI:  

$ laravel new project_name

Or using the Composer create-project command:

$ composer create-project --prefer-dist laravel/laravel project_name

Next, install Twilio’s PHP SDK to call the APIs needed. To make this happen, use Composer to install the dependency with the command:

$ composer require twilio/sdk

After the installation is done, add your Twilio API credentials in the .env file as that will be used to authenticate the API requests.

TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXX
TWILIO_AUTH_TOKEN=your_auth_token

Once the configuration above is completed, create a controller where the functions to retrieve the cost of phone numbers can be written.

$ php artisan make:controller PricingController

Next, import the Twilio PHP SDK into the controller by declaring the namespace at  the top of the controller file:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Exception;
use Twilio\Rest\Client;

class PricingController extends Controller
{
   //
}

Initialize a Constructor

Next, create a constructor to initialize the Twilio client, so that the appropriate APIs can be used. This is done to avoid repeating a block of code across all controller methods following the KISS principle.

The code for the constructor is as follows:

 
 protected $twilio;

 public function __construct() {
   // Your Account SID and Auth Token from twilio.com/console
   $this->sid = getenv('TWILIO_ACCOUNT_SID');
   $this->token = getenv('TWILIO_AUTH_TOKEN');

   /** Initialize the Twilio client so it can be used */
   $this->twilio = new Client($this->sid, $this->token);
 }

Create the View

A visual interface for testing all the code is important. For this guide, we will create one and call it pricing.blade.php.  It is also important to be aware that all Laravel views are stored in the resources/views/ directory of the Laravel project. Add this code to the newly created view:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
 <head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

   <!-- Bootstrap CSS -->
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
   <title>Laravel + Twilio Phone Number Prices</title>

   <style>
     .container {
       padding-top: 50px;
     }
     p {
       font-size: 30px;
       font-weight: 700;
       text-align: center
     }
     .row {
       padding-top: 50px
     }
   </style>
 </head>
 <body>
   <div class="container">
     <div class="row">
       <div class="col-6">
         <p>PHONE NUMBERS</p>
         <div class="card">
           <h5 class="card-header">Phone number prices</h5>
           <div class="card-body">
             <form method="POST" action="{{ route('phone_number_price') }}">
               @csrf
               <div class="form-group">
                 <label for="phone_number">Country</label>
                 <select class="form-control" name="iso2">
                   @foreach($phoneCountries as $country)
                     <option value="{{ $country->isoCountry }}">{{ $country->country }}</option>
                   @endforeach
                 </select>
                 <small id="numberHelp" class="form-text text-muted">Select the country of choice.</small>
               </div>
               <button type="submit" class="btn btn-primary">Submit</button>
             </form>
           </div>
         </div>
       </div>
     </div>
   </div>
   <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
   <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
 </body>
</html>

Phone Numbers UI form

Get Phone Number Prices

This API can also be used to find the cost of phone numbers for different countries depending on the options. Add the following function to the PricingController class:

/** PHONE NUMBERS */
 public function phoneNumbers(Request $request) {
   $this->validate($request, [
     'iso2' => 'required'
   ]);

   try {
     $country = $request->iso2;
     /** Retrieve the cost of phone numbers in the given country. */
     $price = $this->twilio->pricing->v1->phoneNumbers
                                       ->countries($country)
                                       ->fetch();
     if($price) {
       dd($price);
     } else {
       print 'Retrieving the pricing information failed. Please try again';
     }
   } catch (Exception $e) {
     print 'Error: ' . $e->getMessage();
   }
 }

List Countries with Twilio Phone Numbers

The Pricing API offers solutions to determine the list of countries where Twilio services are available. Add this code to the PricingController to retrieve the list of countries with the available support for Twilio phone numbers:

public function index() {
   /** Retrieve a list of countries where Twilio phone number services are available */
   $phoneCountries = $this->twilio->pricing->phoneNumbers->countries->read();
   return view('pricing', ['phoneCountries' => $phoneCountries]);
 }

Update the Routes

We will now create the routes responsible for returning the view and for calling the methods to retrieve the pricing information in the routes/web.php file.

The route file should look like this:

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', 'PricingController@index');

Route::post('/phone_number_price', 'PricingController@phoneNumbers')->name('phone_number_price');

Final Controller Code

Now lets review the completed controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Twilio\Rest\Client;
use Exception;

class PricingController extends Controller
{
 protected $twilio;

 public function __construct() {
   // Your Account SID and Auth Token from twilio.com/console
   $this->sid = getenv('TWILIO_ACCOUNT_SID');
   $this->token = getenv('TWILIO_AUTH_TOKEN');

   /** Initialize the Twilio client so it can be used */
   $this->twilio = new Client($this->sid, $this->token);
 }

 public function index() {
   /** Retrieve a list of countries where Twilio phone number services are available */
   $phoneCountries = $this->twilio->pricing->phoneNumbers->countries->read();
   return view('pricing', ['phoneCountries' => $phoneCountries]);
 }

/** PHONE NUMBERS */
 public function phoneNumbers(Request $request) {
   $this->validate($request, [
     'iso2' => 'required'
   ]);

   try {
     $country = $request->iso2;
     /** Retrieve the cost of phone numbers in the given country. */
     $price = $this->twilio->pricing->v1->phoneNumbers
                                       ->countries($country)
                                       ->fetch();
     if($price) {
       dd($price);
     } else {
       print 'Retrieving the pricing information failed. Please try again';
     }
   } catch (Exception $e) {
     print 'Error: ' . $e->getMessage();
   }
 }
}

Testing

To see the application in action, start up your development server using this command in the terminal of your local machine:

$ php artisan serve

Finally, use the web browser of your choice and visit http://localhost:8000. Fill in the forms and submit to get the expected response.

Conclusion

After completing all the enlisted steps, you can successfully retrieve account-specific pricing for Twilio phone numbers in a Laravel application.

I can’t wait to see what you build!

Ugendu Martins Ositadinma is a software developer at filerskeepers. He is passionate about problem solving with the aid of codes and programs. He is also pretty familiar with PHP, Javascript and a couple of frameworks and cloud services. You can always reach him via any of the channels below.

  • Email: ugendu04@gmail.com
  • Twitter: https://twitter.com/ohssie_
  • Github: https://github.com/ohssie