Get Started with Voice OTP using Node.JS

    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 Node.js Dev Environment

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

    Install Node.js

    Operating SystemInstructions
    OS X & LinuxYou would already have Node.js installed, you can check this by running the command node --version in the terminal. If you don't have it installed, you can install it from here .
    WindowsTo install Node.js on Windows you can download it from here and install.

    Install Modules

    • Create a project directory, run the following command:

      $ mkdir mynodeapp
      
    • Change the directory to our project directory in the command line:

      $ cd mynodeapp
      
    • Install the SDK using npm

      $ brew install redis
      $ npm install plivo
      $ npm install redis
      

    Trigger the PHLO

    Once you have created and setup your Node.js 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.

    Code

    Now, create a file called TriggerPhlo.js and paste the below 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
    53
    54
    55
    56
    57
    58
    59
    60
    61
    
    const express = require('express');
    const app = express();
    const redis = require('redis');
    const redisClient = redis.createClient();
    var plivo = require('plivo');
    var PhloClient = plivo.PhloClient;
    
    var authId = "<auth-id>";
    var authToken = "<auth-token>";
    var phloId = "<PHLO_ID>";
    var phloClient = phlo = null;
    
    // Make call to the destination number with OTP.
    app.get('/dispatch_otp/:number', function(req, res) {
        const number = (req.params.number);
        const code = Math.floor(100000 + Math.random() * 900000);
    
        var client = new plivo.Client(auth_id, auth_token);
        var payload = {
            from: '+15671234567',
            to: number,
            otp: code
        }
        phloClient = new PhloClient(authId, authToken);
        phloClient.phlo(phloId).run(payload).then(function(result) {
            console.log('Phlo run result', result);
        }).catch(function(err) {
            console.error('Phlo run failed', err);
        });
        redisClient.set(`number:${number}:code`, code, 'EX', 60);
        res.send(JSON.stringify({
            'status': 'success',
            'message': 'verification initiated'
        }));
    });
    
    // Validate the OTP entered by the user.
    app.get('/verify_otp/:number/:code', function(req, res) {
        const number = (req.params.number);
        const code = (req.params.code);
        redisClient.get(`number:${number}:code`, function(err, OriginalCode) {
            if (OriginalCode == code) {
                redisClient.del(`number:${number}:code`);
                res.send(JSON.stringify({
                    'status': 'success',
                    'message': 'codes match! number verified'
                }));
            } else if (OriginalCode != code) {
                res.send(JSON.stringify({
                    'status': 'failure',
                    'message': 'codes do not match! number not verified'
                }));
            } else {
                res.send(JSON.stringify({
                    'status': 'failure',
                    'message': 'number not found!'
                }));
            }
        });
    });
    app.listen(5000);
    

    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

    Test and Validate

    You can save the file and use the below command to run your code.

    $ node TriggerPhlo.js
    

    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:5000/dispatch_otp/?destination_number=<destination_number>
    http://localhost:5000/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 (5000 in this case):

    ./ngrok http 5000
    

    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://61d8fb8f250c.ngrok.io/dispatch_otp/?destination_number=<destination_number>
    https://61d8fb8f250c.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 Node.js Dev Environment

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

    Install Node.js

    Operating SystemInstructions
    OS X & LinuxYou would already have Node.js installed, you can check this by running the command node --version in the terminal. If you don't have it installed, you can install it from here .
    WindowsTo install Node.js on Windows you can download it from here and install.

    Install Modules

    • Create a project directory, run the following command:

      $ mkdir mynodeapp
      
    • Change the directory to our project directory in the command line:

      $ cd mynodeapp
      
    • Install the SDK using npm

      $ brew install redis
      $ npm install plivo
      $ npm install redis
      

    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.

    Now, create a file called voiceotp.js and paste the below 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
    53
    54
    
    const express = require('express');
    const app = express();
    const redis = require('redis');
    const redisClient = redis.createClient();
    var plivo = require('plivo');
    
    // Make call to the destination number with OTP.
    app.get('/dispatch_otp/:number', function(req, res) {
        const number = (req.params.number);
        const code = Math.floor(100000 + Math.random() * 900000);
    
        var client = new plivo.Client("<auth_id>", "<auth_token>");
        var response = client.calls.create(
            "+14151234567", // from
            number, // to
            "https://twofa-answerurl.herokuapp.com/answer_url/" + code, // answer url
            {
                answerMethod: "GET",
            },
        )
        console.log(response)
        redisClient.set(`number:${number}:code`, code, 'EX', 60);
        res.send(JSON.stringify({
            'status': 'success',
            'message': 'verification initiated'
        }));
    });
    
    // Validate the OTP entered by the user.
    app.get('/verify_otp/:number/:code', function(req, res) {
        const number = (req.params.number);
        const code = (req.params.code);
        redisClient.get(`number:${number}:code`, function(err, OriginalCode) {
            if (OriginalCode == code) {
                redisClient.del(`number:${number}:code`);
                res.send(JSON.stringify({
                    'status': 'success',
                    'message': 'codes match! number verified'
                }));
            } else if (OriginalCode != code) {
                res.send(JSON.stringify({
                    'status': 'failure',
                    'message': 'codes do not match! number not verified'
                }));
            } else {
                res.send(JSON.stringify({
                    'status': 'failure',
                    'message': 'number not found!'
                }));
            }
        });
    });
    
    app.listen(5000);
    
    Note:
    • Replace the placeholders auth_id & auth_token with your credentials from Plivo 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 process.env to store environment variables and fetch them while initializing the client.
    • Replace the placeholder +14151234567 with the Phone number which you have purchased
    • Phone numbers should be in E.164 format

    Test and Validate

    Once you have created the Voice OTP App, You can save the file and use the below command to run your code.

    $ node voiceotp.js
    

    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:5000/dispatch_otp/?destination_number=<destination_number>
    http://localhost:5000/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 (5000 in this case):

    ./ngrok http 5000
    

    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://61d8fb8f250c.ngrok.io/dispatch_otp/?destination_number=<destination_number>
    https://61d8fb8f250c.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.