Verifying Accounts
Learn how to add user verification to our applications using Twilio's Verify API.
We'll cover the following
Twilio's Verify API makes it easy to add user verification to our web application. It supports codes sent via SMS, voice, and email.
This lesson will discuss the following three steps required to implement a basic verification service:
Create a verification service.
Send a verification token.
Check the verification token.
Create a verification service
We first need to set up a verification service to send a verification token. To do this, we’ll use the Service API available in Twilio.
The base URL to create the verification service is as follows:
https://verify.twilio.com/v2/Services
We need to provide some mandatory request parameters to create a verification service. The following table gives details about these parameters:
Request parameters
Name | Type | Category | Description |
| String | Mandatory | The description of our verification service. Its length should not be more than 30. |
| Integer | Optional | The length of the code to be generated. Minimum value is 4 and maximum is 10. |
| Boolean | Optional | If set to |
| Boolean | Optional | If set to |
| Boolean | Optional | If set to |
Press the “Run” button in the following widget to create a verification service. Make sure to save the ServiceSid
.
import fetch from "node-fetch";//header parametersconst header = {'Authorization': 'Basic ' + Buffer.from('{{ACCOUNT_SID}}'+':'+'{{AUTH_TOKEN}}').toString('base64'),'Content-Type': 'application/x-www-form-urlencoded',};//Base urlconst url = new URL('https://verify.twilio.com/v2/Services');//Define the body parametersconst body = 'FriendlyName=My First Verify Service';//Set the API call optionsconst options = {method: 'POST',headers: header,body: body};async function VerificationService() {try {const response = await fetch(url, options);// Custom function for printing the API responseprintResponse(response);} catch (error) {console.log(`Error: ${err}`);}}VerificationService();
In the code above:
Lines 4–7: We define the
header
parameter, which includes the access tokens.Line 10: We define the endpoint URL and provide the
ACCOUNT_SID
.Line 13: We define the
body
parameters and set theFriendlyName
.Lines 16–20: We define the
options
parameters to make the API call and set the request type asPOST
.Lines 22–30: We define the
VerificationService
function, which calls the endpoint.Line 32: We call the
VerificationService
function.
Note: We can use a verification service to send multiple verification tokens. Creating a new service each time is not necessary.
The following table gives details about the attributes found in the response object.
Response fields
Name | Type | Description |
| String | The last date the service was updated. |
| String | The URL of the service, relative to Twilio. |
| String | The SID of the account that created the service. |
| Boolean | If this is `true`, a security warning is sent along with the verification code. |
| Boolean | If this is |
| String | The date on which the service was created. |
| String | The ID associated with the service. |
| Integer | The length of the code that will be generated. |
| String | The description of the verification service sent as input. |
| Object | Contains the links related to our service. |
Send a verification token
After creating a verification service, the next step is to send a verification token to the end user. The base URL to create a verification token is as follows:
https://verify.twilio.com/v2/Services/{ServiceSid}/Verifications
The following table details the request parameters required to call this endpoint.
Request parameters
Name | Type | Category | Description |
| String | Mandatory | The SID of the service used to generate a token. |
| String | Mandatory | The phone number or email to which we send the verification token. The phone number must be in the form “%2B [country code] [phone number].” Here, “%2B” is the code for the plus (+) sign. |
| String | Mandatory | Defines the method to send the verification token. Accepted input is |
| String | Optional | Overwrites the current friendly name. |
| String | Optional | The locale is updated automatically based on the country code provided with the phone number. This field can be used to override the locale. |
| String | Optional | Used to generate a customized code. |
| String | Optional | The App Hash value that is appended at the end of the message body. |
| String | Optional | Overrides the default message template. |
| String | Optional | A stringified JSON object where the keys are special variables used in the template. |
Let’s send a verification token to the To
phone number using the specified channel (SMS). Once we create the verification and send a token, it shows the pending status.
Note: Make sure that the phone number is in the form “%2B [country code] [phone number].”
import fetch from "node-fetch";const header = {'Authorization': 'Basic ' + Buffer.from('{{ACCOUNT_SID}}'+':'+'{{AUTH_TOKEN}}').toString('base64'),'Content-Type': 'application/x-www-form-urlencoded',};const url = new URL('https://verify.twilio.com/v2/Services/{{ServiceSid}}/Verifications');const body = 'To={{YOUR_PHONE_NUMBER}}&Channel=whatsapp';const options = {method: 'POST',headers: header,body: body};async function VerificationCode() {try {const response = await fetch(url, options);// Custom function for printing the API responseprintResponse(response);} catch (error) {console.log(`Error: ${err}`);}}VerificationCode();
In the code above:
Line 8: We define the endpoint URL and provide the
ACCOUNT_SID
.Line 10: We define the body parameters and set the channel type to
whatsapp
.Lines 18–26: We define the function
VerificationCode
, which calls the endpoint.Line 28: We call the
VerificationCode
function.
The following table gives details about the attributes found in the response object.
Response fields
Name | Type | Description |
| String | The ID associated with the verification resource. |
| String | The ID associated with the service used in the verification resource. |
| String | The SID of the account that created the service. |
| String | The phone number that received the verification token. |
| String | The channel used to send the verification token. Expected output is |
| String | The status of the verification. Expected output is |
| Object | Includes information about the destination phone number. |
| Object | Includes information about the attempts made to send the verification code. |
| String | The date on which the service was created. |
| String | The last date the service was updated. |
| String | The URL of the service, relative to Twilio. |
Check the verification token
After sending a verification token, the user will receive it. The final step on our end is to check whether the user-provided token is correct. Depending upon the user-provided token’s value, the following responses are generated:
Token | Status in response |
Correct |
|
Incorrect |
|
The following base URL is used to check a verification token:
https://verify.twilio.com/v2/Services/{ServiceSid}/VerificationCheck
The following table details the request parameters required to call this endpoint.
Request parameters
Name | Type | Category | Description |
| String | Mandatory | The SID of the service used to verify a token. |
| String | Mandatory | The phone number or email which we want to verify. The phone number must be in the form “%2B [country code] [phone number].” Here, “%2B” is the code for the plus (+) sign. |
| String | Mandatory | The verification code sent to our phone number. |
| String | Optional | The SID of the verification resource. |
In the following code widget, let’s verify the code we received on our phone number. Click “Edit” to enter the verification code, and don’t forget to click “Save” when you’re done.
import fetch from "node-fetch";const header = {'Authorization': 'Basic ' + Buffer.from('{{ACCOUNT_SID}}'+':'+'{{AUTH_TOKEN}}').toString('base64'),'Content-Type': 'application/x-www-form-urlencoded',};const url = new URL('https://verify.twilio.com/v2/Services/{{ServiceSid}}/VerificationCheck');const body = 'To={{YOUR_PHONE_NUMBER}}&Code={{Verification_Code}}';const options = {method: 'POST',headers: header,body: body};async function Verify() {try {const response = await fetch(url, options);// Custom function for printing the API responseprintResponse(response);} catch (error) {console.log(`Error: ${err}`);}}Verify();
In the code above:
Line 8: We define the endpoint URL and provide the
ACCOUNT_SID
.Line 10: We provide the verification token in the body parameter.
Lines 18–26: We define the function
Verify
, which calls the endpoint.Line 28: We call the
Verify
function.
The following table contains details about the attributes in the response
object.
Response fields
Name | Type | Description |
| String | The ID associated with the verification resource. |
| String | The ID associated with the service used in the verification resource. |
| String | The SID of the account that created the service. |
| String | The phone number that received the verification token. |
| String | The channel used to send the verification token. Expected output is |
| String | The status of the verification. Expected output is |
| String | The date on which the service was created. |
| String | The last date the service was updated. |
Twilio deletes the verification security identifier (SID) once it’s either approved, expired (after 10 minutes), or locked. This happens when the maximum number of attempts to check a code is reached (the maximum number of attempts is five).
Therefore, if we try to recheck the verification token once we have gotten the approved status, we will get the following response: