Tuesday, 30 June, 2020 UTC


Summary

A major factor to consider when building web applications is evaluating the cost of integrating third-party services. If you’re using Twilio, this tutorial will serve as a guide to finding the cost of making SMS/Messaging requests to the Twilio Programmable SMS APIs.
Installation Requirements
To get started with this tutorial, you will need to have the following modules/packages installed on your development machine:
  • PHP 7.2+
  • Composer globally installed
  • A Twilio account
Here is a guide that can be followed to install Composer globally:
  • Unix systems
  • Windows systems
Creating the PHP Project
First, create a folder named smsPricing on your local machine where the code will be housed.
In the folder that was created, create a file named index.php which will contain all the code for this tutorial.
Now, let’s go ahead and install Twilio's PHP SDK in order to call the necessary APIs required to share the functions. To accomplish this, use Composer to install the dependency with the command provided below:
$ composer require twilio/sdk 
We don’t want your private credentials such as your Twilio keys available to the public, so create a .env file to store your environment variables. The .env file will be read using the popular PHP package vlucas/phpdotenv to store those variables.
To install the package, use the command below:
$ composer require vlucas/phpdotenv 
As soon as the installation is complete, set the Twilio API credentials in your .env file, as you will need them to authenticate the API requests. Add the following block below to the file:
TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXX TWILIO_AUTH_TOKEN=your_auth_token 
NOTE: Your Twilio credentials can be retrieved from the Twilio console.
Next, create your index.php file to include the Composer autoloader and the Twilio PHP SDK like so:
<?php // Required if your environment does not handle autoloading  require __DIR__ . '/vendor/autoload.php'; use Twilio\Rest\Client;  $dotenv = Dotenv\Dotenv::createImmutable(__DIR__, '/.env'); $dotenv->load(); 
After doing that, we will initialize the Twilio client so we can have a connection to the Twilio API using the Account SID and Auth Token. Add the following code:
// Your Account SID and Auth Token from twilio.com/console $sid = $_ENV['TWILIO_ACCOUNT_SID']; $token = $_ENV['TWILIO_AUTH_TOKEN']; $twilio = new Client($sid, $token); 
Creating the View
We will need to have an interface to be able to easily communicate with the code. Add the following code to index.php, below the PHP code:
<!DOCTYPE html> <html>  <head>  <meta charset="utf-8">  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">  <!-- Semantic UI CSS -->  <link rel="stylesheet" type="text/css" href="/semantic/semantic.min.css">   <title>PHP + Twilio Messaging Pricing API</title>   <style>  .container {  padding: 50px;  }  p {  font-size: 30px;  font-weight: 700;  text-align: center  }  .row {  padding-top: 50px  }  </style>  </head>  <body>  <div class="container">  <div class="ui right aligned grid">  <div class="left floated left aligned six wide column">  <div class="center ui segment">  <form class="ui form" method="POST">  <h4 class="ui dividing header">Messaging Pricing Information</h4>  <div class="field">  <label>Country</label>  <select class="ui fluid dropdown" name="country" required>  <option>Country</option>  <?php foreach($messagingCountries as $c) { ?>  <option value="<?php echo $c->isoCountry; ?>"><?php echo $c->country ?></option>  <?php } ?>  </select>  </div>  <input class="ui secondary button" type="submit" name="messaging_price" tabindex="0" value="Okay"/>  </form>  </div>  </div>  </div>  </div>  <script  src="https://code.jquery.com/jquery-3.1.1.min.js"  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="  crossorigin="anonymous"></script>  <script src="semantic/semantic.min.js"></script>  </body> </html> 
NOTE: Be sure to close your PHP code with `?>` before the HTML above.
Retrieving Messaging Prices
This block can be used to find the cost of sending and receiving SMS to phone numbers of different countries depending on your country of choice:
/** MESSAGING PRICES */ if(!empty($_POST['messaging_price'])) {  try {  $country = $_POST['country'];    /** Retrieve the prices to send and receive SMS messages to phone numbers in the given country. */  $prices = $twilio->pricing->v1->messaging  ->countries($country)  ->fetch();  if($prices) {   var_dump($prices, true);  } else {  print 'Retrieving the messaging pricing information failed. Please try again';  }  } catch (Exception $e) {  print 'Error: ' . $e->getMessage();  }  } 
Complete Code
Here is the complete code for this tutorial. It is essential that you copy and replace all of the code within your index.php file with the code below:
<?php  // Required if your environment does not handle autoloading  require __DIR__ . '/vendor/autoload.php';  use Twilio\Rest\Client;   $dotenv = Dotenv\Dotenv::createImmutable(__DIR__, '/.env');  $dotenv->load();   // Your Account SID and Auth Token from twilio.com/console  $sid = $_ENV['TWILIO_ACCOUNT_SID'];  $token = $_ENV['TWILIO_AUTH_TOKEN'];  $twilio = new Client($sid, $token);   /** Retrieve a list of countries where Twilio messaging services are available */  $messagingCountries = $twilio->pricing->messaging->countries->stream();   if(!empty($_POST['messaging_price'])) {  try {  $country = $_POST['country'];   /** Retrieve the prices to send and receive SMS messages to phone numbers in the given country. */  $prices = $twilio->pricing->v1->messaging  ->countries($country)  ->fetch();  if($prices) {   var_dump($prices, true);  } else {  print 'Retrieving the messaging pricing information failed. Please try again';  }  } catch (Exception $e) {  print 'Error: ' . $e->getMessage();  }  } ?>  <!DOCTYPE html> <html>  <head>  <meta charset="utf-8">  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">  <!-- Semantic UI CSS -->  <link rel="stylesheet" type="text/css" href="/semantic/semantic.min.css">   <title>PHP + Twilio Messaging Pricing API</title>    <style>  .container {  padding: 50px;  }  p {  font-size: 30px;  font-weight: 700;  text-align: center  }  .row {  padding-top: 50px  }  </style>  </head>  <body>  <div class="container">  <div class="ui right aligned grid">  <div class="left floated left aligned six wide column">  <div class="center ui segment">  <form class="ui form" method="POST">  <h4 class="ui dividing header">Messaging Pricing Information</h4>  <div class="field">  <label>Country</label>  <select class="ui fluid dropdown" name="country" required>  <option>Country</option>  <?php foreach($messagingCountries as $c) { ?>  <option value="<?php echo $c->isoCountry; ?>"><?php echo $c->country ?></option>  <?php } ?>  </select>  </div>  <input class="ui secondary button" type="submit" name="messaging_price" tabindex="0" value="Okay"/>  </form>  </div>  </div>  </div>  </div>  <script  src="https://code.jquery.com/jquery-3.1.1.min.js"  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="  crossorigin="anonymous"></script>  <script src="semantic/semantic.min.js"></script>  </body> </html> 
Testing
To ensure that your code is defect-free and to see the application in action, start up your development server using this command in the terminal:
$ php -S localhost:8000 
Finally, using the web browser of your choice, visit http://localhost:8000. Fill in the form and submit to get the expected response.
Conclusion
Upon completing the steps above, you can easily retrieve account-specific messaging prices for various countries and various telecommunication companies available in those locations.
This tutorial can also be extended to compare messaging prices for various telecommunication companies in the destination country/location.
I am looking forward to seeing what you build. In case you need help or want to say “Hi”, you can reach me through any of the channels provided below.
Ugendu Martins Ositadinma
  • Email: [email protected]com
  • Twitter: https://twitter.com/ohssie_
  • Github: https://github.com/ohssie