Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Twilio Functions With the Phone Verification API

DZone's Guide to

Using Twilio Functions With the Phone Verification API

When building and running Twilio apps, consider Twilio Functions for a serverless environment. Here, we use Twilio Functions with the Phone Verification API.

· Cloud Zone
Free Resource

See how the beta release of Kubernetes on DC/OS 1.10 delivers the most robust platform for building & operating data-intensive, containerized apps. Register now for tech preview.

Twilio Functions, a serverless environment to build and run Twilio applications, was released back in May 2017 and allows you to use Node.js code for handling communications events such as a text message, an incoming voice call or HTTP requests, ensuring that you can leverage the benefits of the platform like security, no infrastructure requirements, auto-scaling, native integration with Twilio's REST Helper Library in a familiar environment powered by Node (6.10.x).

We could use a simple Hello World example to show you the power of Twilio Functions, but instead, we are going to use the Twilio Phone Verification API (formerly known as Authy) to demonstrate how easy to use and simple the Twilio Functions interfaces are.

The Twilio Phone Verification API allows you to verify that a given phone number is accurate and it's in the user's possession. The Phone Verification API is absolutely simple to use, one API call to request the code to be sent to the user (SMS or Voice call) and one API call to verify the code provided by the user is valid.

The Phone Verification API is deployed on top of Twilio's Super Network, so it has global reach by default, it's localized in +35 languages, and it offers lots of customizations from the length of the code to the message template to be sent to the user.

Typical use cases for the Phone Verification API are fraud prevention and transaction verification.

To get started with our simple example here, head over to the Twilio Console (https://www.twilio.com/console), select All Products & Services on the left side menu and then Runtime under Developer Tools.

From the Runtime Overview page, select Functions.

Hit the plus (+) sign to create a new Function and select JSON Response. Click Create when you're ready.

Your recently created Function has been created and it's ready to be developed.

Give it a name, for example, Phone Verification Start, set the path to /start, and add the following code to the Function:

exports.handler = function(context, event, callback) {
    const request = require('request');
    console.log("Phone Number: " + event.phone_number);
    console.log("Country Code: " + event.country_code);
    var options = {
        url: 'https://api.authy.com/protected/json/phones/verification/start',
        method: 'POST',
        form: {
            'api_key': context.AUTHY_API_KEY,
            'country_code': event.country_code,
            'phone_number': event.phone_number,
            'via': 'sms'
        }
    }
    request(options, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log("Phone Information: " + body);
        } else {
            console.log("ERROR: " + error);
        }
        callback(null, body);
    })
};


The code above will receive an HTTP request with two parameters (phone_number and country_code) showed on lines 3 and 4.

These parameters are going to be available in the code in the event object upon the request.

The context object will hold environment variables, and that's what we are going to need next (line 8).

Then, we are going to make a request to the Phone Verification API (line 13) and send the response back to the client using the callback object (line 19).

You should end up with something similar to the following Twilio Function:

Press Save.

Finally, we need an AUTHY_API_KEY (line 8 above) to make everything work.

If you don't have an Authy application created already, go back to All Products & Services menu in the Twilio Console and then select Authy under Engagement Cloud.

Create a new Authy application, give it a name, go to Settings, and grab the Production API Key

Go back to your Twilio Function, select Configure and then create a new Environment Variable called AUTHY_API_KEY. Set the value to be the Production API Key you grabbed above after creating the Authy application.

Click on Manage, select your Twilio Function, and copy the full URL where your Function is going to be available.

You are now ready to test the start of your Phone Verification Function.

Send an HTTP request to the URL you just copied, add the phone_number and country_code you want to send the verification code to, and your Twilio Account SID and Twilio Auth Token as the credentials.

As an example, I'm using Postman, but you are free to use anything you want.

Send your request, and you should have a response from the Phone Verification API back to you as well as an SMS message sent to the phone number you specified.

You can also watch the console messages under the Logs section of the Twilio Function you have created. Here is an example of the expected output:

Now that you have received the verification code on your phone, we need to verify that code against the Phone Verification API. To do that, let's go back to the Twilio Console, create another Function using the JSON Response template, and call it Phone Verification Check.

Set the PATH to /check and add the following code to the Function:

exports.handler = function(context, event, callback) {
    const request = require('request');
    console.log("Phone Number: " + event.phone_number);
    console.log("Country Code: " + event.country_code);
    console.log("Verification Code: " + event.verification_code);
    var options = {
        url: 'https://api.authy.com/protected/json/phones/verification/check',
        method: 'GET',
        form: {
            'api_key': context.AUTHY_API_KEY,
            'country_code': event.country_code,
            'phone_number': event.phone_number,
            'verification_code': event.verification_code
        }
    }
    request(options, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log("Phone Information: " + body);
        } else {
            console.log("ERROR: " + error);
        }
        callback(null, body);
    })
};


The code above will receive an HTTP request with three parameters (phone_number, country_code, and verification_code) showed on lines 3, 4, and 5.

These parameters are going to be available in the code in the event object upon the request.

The context object will hold environment variables, and that's what we are going to retrieve on line 9.

Then, we are going to make a request to the Phone Verification API (line 14) and send the response back to the client using the callback object (line 20).

You should end up with something similar to the following Twilio Function:

Press Save.

Grab the Phone Verification Check

Twilio Function URL:

You are now ready to test your Phone Verification Function for checking the provided code.

Go back to Postman, or whatever testing tool you are using, and then populate the phone_number, country_code, and verification_code required parameters that you received when calling the Phone Verification Start Function, as well as the required credentials to invoke the Twilio REST call.

Send the HTTP request, and your Twilio Function (Phone Verification Check) should process that and respond with the Phone Verification API information about the scenario you just tested.

You can also watch the log messages in the Logs section of your Twilio Function, and you should see something similar to this:

New Mesosphere DC/OS 1.10: Production-proven reliability, security & scalability for fast-data, modern apps. Register now for a live demo.

Topics:
cloud ,serverless ,twilio functions ,phone verification api ,tutorial ,authy

Published at DZone with permission of Marcelo Jabali, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}