Verifying Accounts

Learn how to add user verification to our applications using Twilio's Verify API.

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:

  1. Create a verification service.

  2. Send a verification token.

  3. 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

FriendlyName

String

Mandatory

The description of our verification service. Its length should not be more than 30.

CodeLength

Integer

Optional

The length of the code to be generated. Minimum value is 4 and maximum is 10.

LookupEnabled

Boolean

Optional

If set to true, Twilio performs a lookup at each verification and gives information about the phone number.

DoNotShareWarningEnabled

Boolean

Optional

If set to true, a security warning is sent along with the verification message.

CustomCodeEnabled

Boolean

Optional

If set to true, we can generate a customized code instead of a randomly generated code.

Press the “Run” button in the following widget to create a verification service. Make sure to save the ServiceSid.

Press + to interact
import fetch from "node-fetch";
//header parameters
const header = {
'Authorization': 'Basic ' + Buffer.from('{{ACCOUNT_SID}}'+':'+'{{AUTH_TOKEN}}').toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded',
};
//Base url
const url = new URL('https://verify.twilio.com/v2/Services');
//Define the body parameters
const body = 'FriendlyName=My First Verify Service';
//Set the API call options
const options = {
method: 'POST',
headers: header,
body: body
};
async function VerificationService() {
try {
const response = await fetch(url, options);
// Custom function for printing the API response
printResponse(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 the FriendlyName.

  • Lines 16–20: We define the options parameters to make the API call and set the request type as POST.

  • 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

date_updated

String

The last date the service was updated.

url

String

The URL of the service, relative to Twilio.

account_sid

String

The SID of the account that created the service.

do_not_share_warning_enabled

Boolean

If this is `true`, a security warning is sent along with the verification code.

custom_code_enabled

Boolean

If this is true, we can generate a customized code instead of a randomly generated code.

date_created

String

The date on which the service was created.

sid

String

The ID associated with the service.

code_length

Integer

The length of the code that will be generated.

friendly_name

String

The description of the verification service sent as input.

links

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

ServiceSid

String

Mandatory

The SID of the service used to generate a token.

To

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.

Channel

String

Mandatory

Defines the method to send the verification token. Accepted input is email, sms, whatsapp, call, or sna.

CustomFriendlyName

String

Optional

Overwrites the current friendly name.

Locale

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.

CustomCode

String

Optional

Used to generate a customized code.

AppHash

String

Optional

The App Hash value that is appended at the end of the message body.

TemplateSid

String

Optional

Overrides the default message template.

TemplateCustomSubstitutions

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].”

Press + to interact
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 response
printResponse(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

sid

String

The ID associated with the verification resource.

service_sid

String

The ID associated with the service used in the verification resource.

account_sid

String

The SID of the account that created the service.

to

String

The phone number that received the verification token.

channel

String

The channel used to send the verification token.

Expected output is email, sms, whatsapp, call, or sna.

status

String

The status of the verification. Expected output is pending, approved, or canceled.

lookup

Object

Includes information about the destination phone number.

send_code_attempts

Object

Includes information about the attempts made to send the verification code.

date_created

String

The date on which the service was created.

date_updated

String

The last date the service was updated.

url

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

approved

Incorrect

pending

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

ServiceSid

String

Mandatory

The SID of the service used to verify a token.

To

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.

Code

String

Mandatory

The verification code sent to our phone number.

VerificationSid

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.

Press + to interact
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 response
printResponse(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

sid

String

The ID associated with the verification resource.

service_sid

String

The ID associated with the service used in the verification resource.

account_sid

String

The SID of the account that created the service.

to

String

The phone number that received the verification token.

channel

String

The channel used to send the verification token.

Expected output is email, sms, whatsapp, call, or sna.

status

String

The status of the verification. Expected output is pending, approved, or canceled.

date_created

String

The date on which the service was created.

date_updated

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:

Press + to interact