Send an SMS with a Verification Code

var TeleSignSDK = require('telesignenterprisesdk');

console.log("## verify.sms ##");

const customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
const apiKey = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";
const phoneNumber = "Your test phone number with no special characters or spaces.";
const optionalParams = {verify_code: "32658"};

const client = new TeleSignSDK(customerId, apiKey);

// Callback for SMS request
function smsCallback(error, responseBody) {
    if (error === null) {
        console.log(`Messaging response for messaging phone number: ${phoneNumber}` +
            ` => code: ${responseBody['status']['code']}` +
            `, description: ${responseBody['status']['description']}`);
    } else {
        console.error("Unable to send SMS. " + error);
    }
}

// Send SMS request
client.verify.sms(smsCallback, phoneNumber, optionalParams);

// Method to handler user input
function prompt(question, callback) {
    const stdin = process.stdin,
        stdout = process.stdout;

    stdin.resume();
    stdout.write(question);

    stdin.once('data', function (data) {
        callback(data.toString().trim());
    });
}

// Ask for user input
prompt('Enter the verification code received:\n', function (input) {
    if (input === optionalParams['verify_code']) {
        console.log('Your code is correct.');
    } else {
        console.log('Your code is incorrect. input: ' + input + ", code: " + optionalParams['verify_code']);
    }
    process.exit();
});

This tutorial describes how to use TeleSign SDKs to send an SMS message with a verification code. You can use this to implement:

  • Two Factor Authentication (2FA) - Ask a user to enter a verification code you send to their phone number in order to enter their password.
  • Password Reset - Ask a user to enter a verification code you send to their phone number and if they enter it correctly, allow the end user to reset their password.
  • Verification - Make sure someone is not entering a fake phone number by sending a verification code to their phone.

This tutorial includes the following sections:

Requirements

For this tutorial, the following is required:

  • customer ID - obtain from your account by logging in to teleportal.telesign.com (referred to as customer_id in this document)
  • API key - obtain from your account by logging in to teleportal.telesign.com (referred to as secret_key in this document)
  • Registration process - this tutorial assumes you already have implemented a way to collect the end user’s log in, password, and phone number, and that you already have a way to store this information after registration
  • SDK - Access to TeleSign’s GitHub repository for your selected language (you must request access from your Technical Account Manager):
  • Language Version
    • Node.js - 6+
    • Java - 7+
    • Python - 2.7+
    • Ruby - 2+
    • PHP - 5.6+
    • C# - 4.5+

Install the SDK

This section describes how to install TeleSign’s latest SDKs.

  1. Obtain your customer ID and API key.
  2. Log in to GitHub and navigate to the SDK in the language of your choice:
  3. Download or clone the repository. If you download it, extract the repository from the .ZIP file.
  4. To install the SDK for use, do the following:

Send an SMS with a Verification Code

This section explains how to send an SMS message containing a verification code that is randomly generated. The sample code provided earlier is broken out into pieces and explained below.

  1. Begin by adding statements for including the appropriate part of the TeleSign SDK and any additional language specific functions you may need.
var TeleSignSDK = require('telesignenterprisesdk');
  1. Insert values for each of the items from customer_id/customerId through to phone_number/phoneNumber.
  • customer_id / customerId - Your TeleSign assigned customer ID, available in your account information in TelePortal.
  • api_key / apiKey - Your TeleSign assigned API key, available in your account information in TelePortal.
  • phone_number / phoneNumber - The phone number you want to use for the example. When you provide the number, it should be a string with no spaces or special characters. Include the complete number. For example, if you are doing a phone number for America, you would include the country code and the area code with the number. For example 16505551212.
console.log("## verify.sms ##");

const customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
const apiKey = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";
const phoneNumber = "Your test phone number with no special characters or spaces.";
  1. Generate a random number to use as a verification code. For SMS verification codes, TeleSign recommends limiting the code to five to seven digits maximum. Here you are generating a random five digit number. For node.js, you choose a code rather than randomly generating it.
const optionalParams = {verify_code: "32658"};
  1. Instantiate a VerifyClient object containing your customer_id/customerId and api_key/apiKey. Send an SMS to the phone containing the verification code. Store the response in response/telesignResponse. For node.js, you use this step to set up a new client and create the smsCallback function, which you will pass into your SMS request.
const client = new TeleSignSDK(customerId, apiKey);

// Callback for SMS request
function smsCallback(error, responseBody) {
    if (error === null) {
        console.log(`Messaging response for messaging phone number: ${phoneNumber}` +
            ` => code: ${responseBody['status']['code']}` +
            `, description: ${responseBody['status']['description']}`);
    } else {
        console.error("Unable to send SMS. " + error);
    }
}

// Send SMS request
client.verify.sms(smsCallback, phoneNumber, optionalParams);
  1. Prompt for the verification code and enter the code you receive via SMS message. You probably will set up the way you prompt the person differently, this is just to show how it works. For node.js, use this step to create a method to handle user input.
// Method to handler user input
function prompt(question, callback) {
    const stdin = process.stdin,
        stdout = process.stdout;

    stdin.resume();
    stdout.write(question);

    stdin.once('data', function (data) {
        callback(data.toString().trim());
    });
}
  1. Check the code entered by the end user against the verification code you generated. For node.js, use this step to ask for and check user input.
// Ask for user input
prompt('Enter the verification code received:\n', function (input) {
    if (input === optionalParams['verify_code']) {
        console.log('Your code is correct.');
    } else {
        console.log('Your code is incorrect. input: ' + input + ", code: " + optionalParams['verify_code']);
    }
    process.exit();
});
  1. If everything works, you should be able to generate and send a verification code via SMS message using this code sample. When you receive the verification code, you are prompted to enter it. If you enter it correctly, you get a message back on your computer saying the code is correct. Otherwise you get a message saying the code is incorrect.

Code it Without the SDK

If you want to write all your own code, you will need to handle authentication yourself. You need the following documents: