Wednesday, September 20, 2017

How to Use Twilio Functions with the Phone Verification API

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 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 APIs (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 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:

1:  exports.handler = function(context, event, callback) {  
2:   const request = require('request');  
3:   console.log("Phone Number: "+event.phone_number);  
4:   console.log("Country Code: "+event.country_code);  
5:   var options = {  
6:            url:    'https://api.authy.com/protected/json/phones/verification/start',  
7:            method: 'POST',  
8:            form: {'api_key':context.AUTHY_API_KEY,  
9:                   'country_code':event.country_code,  
10:                  'phone_number':event.phone_number,  
11:                  'via':'sms'}  
12:       }  
13:   request(options, function(error, response, body){  
14:    if(!error && response.statusCode == 200){  
15:              console.log("Phone Information: " + body);  
16:       }else{  
17:            console.log("ERROR: " + error);  
18:       }  
19:    callback(null, body);  
20:   })  
21:  };  

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 wna 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 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:


1:  exports.handler = function(context, event, callback) {  
2:   const request = require('request');  
3:   console.log("Phone Number: "+event.phone_number);  
4:   console.log("Country Code: "+event.country_code);  
5:   console.log("Verification Code: "+event.verification_code);  
6:   var options = {  
7:            url:   'https://api.authy.com/protected/json/phones/verification/check',  
8:            method:'GET',  
9:            form: {'api_key':context.AUTHY_API_KEY,  
10:                  'country_code':event.country_code,  
11:                  'phone_number':event.phone_number,  
12:                  'verification_code':event.verification_code}  
13:  }  
14:  request(options, function(error, response, body){  
15:     if(!error && response.statusCode == 200){  
16:        console.log("Phone Information: " + body);  
17:     }else{  
18:        console.log("ERROR: " + error);  
19:     }  
20:     callback(null, body);  
21:  })  
22: };  


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 have 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:

 

If you want to learn more about Twilio Functions I'd recommend watching the "Building Serverless Twilio Apps with Twilio Functions" recently presented at Signal London.

There you have it... Twilio Functions interfacing with the Twilio Phone Verification API.




Setting Up Local Environment for Developing Oracle Intelligent Bots Custom Components

Oh the joy of having a local development environment is priceless. For most cloud based solutions the story repeats itself being hard to tr...