Get Started with Voice OTP using PHP

    Overview

    Voice OTP is used to verify a mobile number. This verification is done by making a call to the mobile number & playing a sequence of digits. In order to verify the mobile number the user needs to confirm the played sequence of digits.

    Voice OTP is commonly used to verify new user registrations in an app or website. Let us see a simple example of sending a Voice OTP.

    Start your Voice OTP implementation with Plivo using PHLO or the traditional API/XML way. PHLO allows you to create and deploy the call flows using its intuitive canvas in few clicks. Refer to the instructions from the respective tabs below to start your integration with PHLO or XML as you wish.

    To implement Voice OTP use-case, you can create and deploy a PHLO with a few clicks on the PHLO canvas. PHLO also lets you visually construct your entire use-case. With PHLO, you only pay for calls you make/receive, and building with PHLO is free. You can refer to the below instructions in the Using PHLO tab to begin your implementation.

    Implementation

    In this section, we will guide you to create a PHLO to implement Voice OTP use-case.

    Prerequisites

    • Plivo Auth Id and Auth Token: You will find your Plivo Auth Id and Auth Token on the home screen of your Plivo Console. Click here to sign-up for a Plivo account if you haven’t already!

      Find Your Auth Credentials on Plivo Console

    • Plivo Phone Number(Optional): You must have a voice-enabled Plivo phone number if you are willing to receive incoming calls. You can purchase numbers from the Numbers section of your Plivo Console. It is also possible to purchase numbers using the Numbers API.

      Buy a New Plivo Number

    Create the PHLO

    You can create a PHLO by referring to the below instructions to implement Voice OTP use-case:

    Create a PHLO for Voice OTP

    • On the side navigation bar, click PHLO. The PHLO page will appear and display your existing PHLOs, if any. If this is your first PHLO, then the PHLO page will be empty.
    • Click Create New PHLO to build a new PHLO.
    • On the Choose your use-case window, click Build my own. The PHLO canvas will appear with the Start node.
      Note: The Start node is the starting point of any PHLO. You can choose between the four available trigger states of the Start node; Incoming SMS, Incoming Call, and API Request. For this PHLO, we will use the API Request trigger state.
    • Click on the Start Node, under API request, fill in the Keys as from,to & otp and then click on Validate.
    • From the list of components, on the left hand side, drag and drop the Initial Call component onto the canvas. This will add a Initial Call node onto the canvas.
    • Connect the Start node with the Initiate Call node, using the API Request trigger state.
    • Configure the Initiate Call node with the {{Start.http.params.from}} using the From field. {{Start.http.params.to}} in the To field.
    • Once you have configured a node, click Validate to save the configurations.
    • Similarly, create a node for the Play Audio component and connect it to the Initiate Call node using the Answered trigger state.
    • Next, configure the Play Audio node to play a specific message to the user. For example, in this case, “Your verification code is <OTP>”.
    • Under Speak Text, click on Amazon Polly and paste the following:
    1
    2
    3
    4
    5
    6
    7
    8
    
    <Speak voice="Polly.Amy">
        <prosody rate="medium">
            Your verification code is
        <break/>
        <break/>
        <say-as interpret-as="spell-out">{{Start.http.params.otp}}</say-as>
        </prosody>
    </Speak>
    

    and click on Validate to save

    • Connect the Initiate Call node with the Play Audio node, using the Answered trigger state.
    • After you complete the configurations, provide a friendly name for your PHLO and click Save. Your PHLO is now ready. You can trigger the PHLO and test it out. For more information, refer to the below section.

    Set up Your PHP Dev Environment

    You must set up and install PHP and Plivo’s PHP SDK to implement Voice OTP use-case. Here’s how.

    Install PHP

    <?xml version=”1.0” encoding=”UTF-8”?>

    Operating SystemInstructions
    OS XYou can install PHP using the official installer . You can also install it from here .
    LinuxTo install PHP on Linux you can find the instructions here .
    WindowsTo instll PHP on Windows you can use the official installer .

    Install Composer

    Composer is a dependency manager for PHP that is used in all modern PHP frameworks, such as Symfony and Laravel. We highly recommend using Composer as the package manager for your web project.

    <?xml version=”1.0” encoding=”UTF-8”?>

    1. Download the latest version of Composer .
    2. Run the following command in Terminal in order to run the composer:

    3. Run the following command to make it executable:

    4. To check if the path has /usr/local/bin , use

      If the path is different, use the following command to update the $PATH:

    5. You can also check the version of Composer by running the following command:

    1. Run the following command:

    2. Run the following command to make the composer.phar file as executable:

    3. Run the following command to make Composer globally available for all system users:

    1. Download and run the Windows Installer for Composer.

      Note: Make sure to allow Windows Installer for Composer to make changes to your php.ini file.

    2. If you have any terminal windows open, close all instances and open a fresh terminal instance.
    3. Run the Composer command.

    Install Laravel & Create a Laravel Project

    • Use the below command to install Laravel:

      $ composer require laravel/installer
      

    As we have Laravel and its dependencies installed, we can use them to create a new Laravel project. As the initial step, using Laravel we can auto-generate code in the Laravel folder structure.

    • Change the directory to our project directory in the command line:

      $ cd mylaravelapp
      
    • Use the below command to start your Laravel project:

      $ composer create-project laravel/laravel quickstart --prefer-dist
      
    • To install the stable release, run the following command in the project directory:

      $ composer require plivo/plivo-php
      

    This will create a quickstart directory with the necessary folders & files for development.

    Install Plivo

    • To install a specific release, run the following command in the project directory:

      $ composer require plivo/plivo-php:4.15.0
      
    • Alternatively, you can download this source and run

      $ composer install
      

    This generates the autoload files, which you can include using the following line in your PHP source code to start using the SDK.

    <?php
    require 'vendor/autoload.php'
    

    Trigger the PHLO

    Once you have created and setup your PHP dev envrironment, you can go to your Plivo Consolse and copy the PHLO_ID. You can integrate a PHLO into your application workflow by making an API request to trigger the PHLO with the required payload.

    Create a Laravel Controller

    Change the directory to our newly created project directory, i.e, quickstart directory and run the below command to create a Laravel controller for outbound call.

    $ php artisan make:controller VoiceController
    

    This will generate a controller named VoiceController in the app/http/controllers/ directory. Now, You have to open the app/http/controllers/voiceController.php file and add the following code:

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    
    <?php
    namespace App\Http\Controllers;
    require '../../vendor/autoload.php';
    use Plivo\RestClient;
    use Illuminate\Support\Facades\Redis;
    
    class VoiceController extends Controller
    {
        public function dispatch_otp()
        {
            $dst_number = $_REQUEST["dst_number"];
            $code = rand(100000, 999999);
    
            $auth_id    = "<auth_id>";
            $auth_token = "<auth_token>";
            $client = new PhloRestClient($auth_id, $auth_token);
            $phlo = $client->phlo->get(<YOUR_PHLO_ID>);
             try {
             $response = $phlo->run(["from" => "+15671234567", "to" => $dst_number,"otp"=>$code]); // These are the fields entered in the PHLO console
             print_r($response);
          } catch (PlivoRestException $ex) {
        print_r($ex);
       }
            Redis::setex($dst_number, 60, $code);
            header('Content-Type: application/json');
            echo json_encode($response);
            echo '{"status": "success", "message": "verification initiated"}';
        }
        
        public function verify_otp()
        {
            $dst_number = $_REQUEST["dst_number"];
            $code = $_REQUEST["otp"];
            
            $value = Redis::get($dst_number);
    
            if ($code==$value)
            {
                Redis::get($dst_number);
                echo '{"status": "success", "message": "codes match! number verified"}';
            }
            elseif($code!=$value)
            {
                Redis::del($dst_number,$code);
                echo '{"status": "failure", "message": "codes do not match! number not verified"}';
            }
            else
            {
                echo '{"status": "failure", "message": "number not found!"}';
            }
        }
    }
    

    You can get your Auth_ID and Auth_token from your dashboard AUTHID

    You can find the PHLO_ID on the PHLO Listing page. PHLO Listing

    Add a Route

    Now, to add a route for the outbound function in the VoiceController class, open the routes/web.php file and add the below line at the end of the file:

    Route::match(['get', 'post'], '/dispatch_otp', 'App\Http\Controllers\VoiceController@dispatch_otp');
    Route::match(['get', 'post'], '/verify_otp', 'App\Http\Controllers\VoiceController@verify_otp');
    

    Navigate to your .env file and the below line

    REDIS_CLIENT=predis
    

    Test & Validate

    Now the VoiceController is ready for your first outbound call, you can use the below command to initiate your first outbound using Laravel and Plivo PHP SDK.

    $ php artisan serve
    

    Run the following command in a new terminal tab to start the redis.

    $ redis-server
    

    And you should see your basic server app in action as below:

    http://localhost:8000/dispatch_otp/?destination_number=<destination_number>
    http://localhost:8000/verify_otp/?destination_number=<destination_number>&otp=<otp>
    

    Expose your local server to the internet

    We recommend using ngrok, which exposes local servers behind NATs and firewalls to the public internet over secure tunnels.

    ngrok block diagram

    Install ngrok and run it on the command line, specifying the port that hosts the application on which you want to receive messages (8000 in this case):

    $ ./ngrok http 8000
    

    Ngrok will display a forwarding link that you can use as a webhook to access your local server over the public network.

    Sample ngrok CLI

    Test and Validate

    You should see your basic server app in action as below:

    https://84b781ed8406.ngrok.io/dispatch_otp/?destination_number=<destination_number>
    https://84b781ed8406.ngrok.io/verify_otp/?destination_number=<destination_number>&otp=<otp>
    
    Note: If you are using a Plivo Trial account for this example, you can only make calls to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

    Common Use Cases for Voice OTP

    You can also use this PHLO structure for other use cases, like:

    • Order notification
    • Booking status
    • Delivery status
    • Flight cancellation/reschedule
    • Two-Factor Authentication/One-Time Password
    • New Offer notification
    • Account balance notification

    To implement Voice OTP use-case in the traditional API/XML way, you can refer to the instructions in the below section to begin your implementation.

    Implementation

    In this section, we will guide you in setting up an app using Plivo’s API/XML to implement Voice OTP use-case. First, let’s make sure you meet these prerequisites before we dive into the code.

    Prerequisites

    This section will guide you through how to use Plivo APIs to make voice calls from your application. First, let’s make sure you meet these prerequisites before we dive into the code.

    • Plivo Auth Id and Auth Token: You will find your Plivo Auth Id and Auth Token on the home screen of your Plivo Console. Click here to sign-up for a Plivo account if you haven’t already!

      Find Your Auth Credentials on Plivo Console

    • Plivo Phone Number(Optional): You can purchase numbers from the Numbers section of your Plivo Console and use the same as the caller ID for the outbound call. This number will also help you receive incoming calls as you must have a voice-enabled Plivo phone number to do the same. Please note that you can also purchase numbers using the Numbers API.

      Buy a New Plivo Number

    • Answer Url: When a call is answered by the destination_number, you can control the call flow with the help of the answer_url set in the API request. Plivo will invoke the answer_url specified as soon as the call is answered and expect a valid XML response with instructions to handle the call. In this example, we’ve removed the need to construct and host an XML. The code snippets below include a pre-hosted URL that will retrun an XML containing the OTP you want to send. Now all you have to do is run the code.

    Set up Your PHP Dev Environment

    You must set up and install PHP and Plivo’s PHP SDK implement Voice OTP use-case. Here’s how.

    Install PHP

    Operating SystemInstructions
    OS XYou can install PHP using the official installer. You can also install it from here.
    LinuxTo install PHP on Linux you can find the instructions here.
    WindowsTo instll PHP on Windows you can use the official installer.

    Install Composer

    Composer is a dependency manager for PHP that is used in all modern PHP frameworks, such as Symfony and Laravel. We highly recommend using Composer as the package manager for your web project.

    1. Download the latest version of Composer.
    2. Run the following command in Terminal in order to run the composer:

       $ php ~/Downloads/composer.phar --version
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make it executable:

       $ cp ~/Downloads/composer.phar /usr/local/bin/composer
       $ sudo chmod +x /usr/local/bin/composer
       $ Make sure you move the file to bin directory.
      
    4. To check if the path has /usr/local/bin, use

       $ echo $PATH
      

      If the path is different, use the following command to update the $PATH:

       $ export PATH = $PATH:/usr/local/bin
       $ source ~/.bash_profile
      

      Note: If your PATH doesn’t include /usr/local/bin directory, we recommend adding it so that you can access it globally.

    5. You can also check the version of Composer by running the following command:

       $ composer --version.       
      

    1. Run the following command:

       $ curl -sS https://getcomposer.org/installer | php
      
    2. Run the following command to make the composer.phar file as executable:

       $ chmod +x composer.phar
      

      Note: PHAR (PHP archive) is an archive format for PHP that can be run on the command line

    3. Run the following command to make Composer globally available for all system users:

       $ mv composer.phar /usr/local/bin/composer
      

    1. Download and run the Windows Installer for Composer.

      Note: Make sure to allow Windows Installer for Composer to make changes to your php.ini file.

    2. If you have any terminal windows open, close all instances and open a fresh terminal instance.
    3. Run the Composer command.

       $ composer -V
      

    Install Laravel & Create a Laravel Project

    • Use the below command to install Laravel:

      $ composer require laravel/installer
      

    As we have Laravel and its dependencies installed, we can use them to create a new Laravel project. As the initial step, using Laravel we can auto-generate code in the Laravel folder structure.

    • Change the directory to our project directory in the command line:

      $ cd mylaravelapp
      
    • Use the below command to start your Laravel project:

      $ composer create-project laravel/laravel quickstart --prefer-dist
      
    • To install the stable release, run the following command in the project directory:

      $ composer require plivo/plivo-php
      

    This will create a quickstart directory with the necessary folders & files for development.

    Install Plivo

    • To install a specific release, run the following command in the project directory:

      $ composer require plivo/plivo-php:4.15.0
      
    • Alternatively, you can download this source and run

      $ composer install
      

    This generates the autoload files, which you can include using the following line in your PHP source code to start using the SDK.

    <?php
    require 'vendor/autoload.php'
    

    Create the Voice OTP App

    Once you have the above prerequisites set, You can follow the below instructions to create an app to implement Voice OTP use-case and redirect the call to an Automated Voice OTP using a GetInput XML once the call recipients answer the call.

    Create a Laravel Controller

    Change the directory to our newly created project directory, i.e, quickstart directory and run the below command to create a Laravel controller for outbound call.

    $ php artisan make:controller VoiceController
    

    This will generate a controller named VoiceController in the app/http/controllers/ directory. Now, You have to open the app/http/controllers/voiceController.php file and add the following code:

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    
    <?php
    namespace App\Http\Controllers;
    require '../../vendor/autoload.php';
    use Plivo\RestClient;
    use Illuminate\Support\Facades\Redis;
    
    class VoiceController extends Controller
    {
        public function dispatch_otp()
        {
            $dst_number = $_REQUEST["dst_number"];
            $code = rand(100000, 999999);
    
            $auth_id    = "<auth_id>";
            $auth_token = "<auth_token>";
            $client     = new RestClient($auth_id, $auth_token);
            $response = $client->calls->create(
                '+14157654321',
                [$dst_number],
                'https://twofa-answerurl.herokuapp.com/answer_url/'.$code,
                'POST'
            );
            Redis::setex($dst_number, 60, $code);
            header('Content-Type: application/json');
            echo json_encode($response);
            echo '{"status": "success", "message": "verification initiated"}';
        }
        
        public function verify_otp()
        {
            $dst_number = $_REQUEST["dst_number"];
            $code = $_REQUEST["otp"];
            
            $value = Redis::get($dst_number);
    
            if ($code==$value)
            {
                Redis::get($dst_number);
                echo '{"status": "success", "message": "codes match! number verified"}';
            }
            elseif($code!=$value)
            {
                Redis::del($dst_number,$code);
                echo '{"status": "failure", "message": "codes do not match! number not verified"}';
            }
            else
            {
                echo '{"status": "failure", "message": "number not found!"}';
            }
        }
    }
    
    Note:
    • Replace the placeholders auth_id & auth_token with your credentials from yourPlivo Console.
    • We recommend that you store your credentials in the auth_id & auth_token environment variables, so as to avoid the possibility of accidentally committing them to source control. If you do this, you can initialize the client with no arguments and it will automatically fetch them from the environment variables
    • You can use $_ENV or putenv/getenv function to store environment variables and fetch them while initializing the client.
    • Replace the placeholder +14157654321 with the Phone number which you have purchased.
    • Both +14157654321 and dst_number should be in E.164 format

    Add a Route

    Now, to add a route for the outbound function in the VoiceController class, open the routes/web.php file and add the below line at the end of the file:

    Route::match(['get', 'post'], '/dispatch_otp', 'App\Http\Controllers\VoiceController@dispatch_otp');
    Route::match(['get', 'post'], '/verify_otp', 'App\Http\Controllers\VoiceController@verify_otp');
    

    Navigate to your .env file and the below line

    REDIS_CLIENT=predis
    

    Test & Validate

    Now the VoiceController is ready for your first outbound call, you can use the below command to initiate your first outbound using Laravel and Plivo PHP SDK.

    $ php artisan serve
    

    Run the following command in a new terminal tab to start the redis.

    $ redis-server
    

    And you should see your basic server app in action as below:

    http://localhost:8000/dispatch_otp/?destination_number=<destination_number>
    http://localhost:8000/verify_otp/?destination_number=<destination_number>&otp=<otp>
    

    Expose your local server to the internet

    We recommend using ngrok, which exposes local servers behind NATs and firewalls to the public internet over secure tunnels.

    ngrok block diagram

    Install ngrok and run it on the command line, specifying the port that hosts the application on which you want to receive messages (8000 in this case):

    $ ./ngrok http 8000
    

    Ngrok will display a forwarding link that you can use as a webhook to access your local server over the public network.

    Sample ngrok CLI

    Test and Validate

    You should see your basic server app in action as below:

    https://84b781ed8406.ngrok.io/dispatch_otp/?destination_number=<destination_number>
    https://84b781ed8406.ngrok.io/verify_otp/?destination_number=<destination_number>&otp=<otp>
    
    Note: If you are using a Plivo Trial account for this example, you can only make calls to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.