Tutorial: Send an SMS Message with a Verification Code

var TeleSignSDK = require('telesignsdk');

const customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890"; // Todo: find in portal.telesign.com
const apiKey = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=="; // Todo: find in portal.telesign.com
const rest_endpoint = "https://rest-api.telesign.com"; // Todo: Enterprise customer, change this!
const timeout = 10*1000; // 10 secs

const client = new TeleSignSDK( customerId,
    apiKey,
    rest_endpoint,
    timeout // optional
    // userAgent
);

const phoneNumber = "phone_number";
const messageType = "ARN";
const verifyCode = "32658";
const message = "Your code is " + verifyCode;

console.log("## MessagingClient.message ##");

function messageCallback(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 message. " + error);
    }
}

client.sms.message(messageCallback, phoneNumber, message, messageType);

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());
    });
}

prompt('Enter the verification code received:\n', function (input) {
    if (input === verifyCode) {
        console.log('Your code is correct.');
    } else {
        console.log('Your code is incorrect. input: ' + input + ", code: " + verifyCode);
    }
    process.exit();
});
package com.telesign.example.messaging;

import com.telesign.MessagingClient;
import com.telesign.RestClient;
import com.telesign.Util;

public class SendMessageWithVerificationCode {

    public static void main(String[] args) {

        String customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
        String apiKey = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";

        String phoneNumber = "Your test phone number with no special characters or spaces goes here.";
        String messageType = "OTP";

        String verifyCode = Util.randomWithNDigits(5);
        String message = String.format("Your code is %s", verifyCode);



        try {
            MessagingClient messagingClient = new MessagingClient(customerId, apiKey);
            RestClient.TelesignResponse telesignResponse = messagingClient.message(phoneNumber, message, messageType, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
from __future__ import print_function
from telesign.messaging import MessagingClient
from telesign.util import random_with_n_digits

customer_id = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890"
api_key = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=="

phone_number = "Your test phone number with no special characters or spaces goes here."
message_type = "OTP"

verify_code = random_with_n_digits(5)
message = "Your code is {}".format(verify_code)

messaging = MessagingClient(customer_id, api_key)
response = messaging.message(phone_number, message, message_type)

user_entered_verify_code = raw_input("Please enter the verification code you were sent: ")

if verify_code == user_entered_verify_code.strip():
    print("Your code is correct.")
else:
    print("Your code is incorrect.")
require 'telesign'

customer_id = 'FFFFFFFF-EEEE-DDDD-1234-AB1234567890'
api_key = 'EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=='

phone_number = 'Your test phone number with no special characters or spaces goes here.'
message_type = 'OTP'

verify_code = Telesign::Util.random_with_n_digits(5)
message = "Your code is #{verify_code}"

messaging_client = Telesign::MessagingClient.new(customer_id, api_key)
response = messaging_client.message(phone_number, message, message_type)

print 'Please enter the verification code you were sent: '
user_entered_verify_code = gets.strip

if verify_code == user_entered_verify_code
    puts 'Your code is correct.'
else
    puts 'Your code is incorrect.'
end
<?php
require __DIR__ . "/../../vendor/autoload.php";
use telesign\sdk\messaging\MessagingClient;
use function telesign\sdk\util\randomWithNDigits;
$customer_id = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
$api_key = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";
$phone_number = "Your test phone number with no special characters or spaces goes here.";
$message_type = "OTP";
$verify_code = randomWithNDigits(5);
$message = "Your code is $verify_code";
$messaging = new MessagingClient($customer_id, $api_key);
$response = $messaging->message($phone_number, $message, $message_type);
echo "Please enter the verification code you were sent: ";
$user_entered_verify_code = trim(fgets(STDIN));
if ($verify_code == $user_entered_verify_code) {
  echo "Your code is correct.";
}
else {
  echo "Your code is incorrect.";
}
using System;

namespace Telesign.Example.Messaging
{
    class SendMessageWithVerificationCode
    {
        static void Main(string[] args)
        {
            string customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
            string apiKey = "EXAMPLETE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";

            string phoneNumber = "Your test phone number with no special characters or spaces goes here.";
            string messageType = "OTP";
          
            string verifyCode = "12345";
            string message = string.Format("Your code is {0}", verifyCode);


            try
            {
                MessagingClient messagingClient = new MessagingClient(customerId, apiKey);
                RestClient.TelesignResponse telesignResponse = messagingClient.Message(phoneNumber, message, messageType);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("Press any key to quit.");
            Console.ReadKey();
        }
    }
}
curl -X POST https://rest-api.telesign.com/v1/messaging \
-d phone_number=XXXXXXXX \
-d message="Your code is {insert code}." \
-d message_type="OTP" \
-u "CUSTOMER_ID":"API_KEY"

This tutorial describes how to use TeleSign SDKs to send an SMS message with a verification code.

Requirements

For this tutorial, the following is required:

  • Customer ID - Obtain this for your account by logging in to portal.telesign.com
  • API key - Obtain this for your account by logging in to portal.telesign.com
  • SDK - Download the SDK from TeleSign's GitHub repository for your selected language:
  • Language Version
    • Node.js - 6+
    • Java - 7+
    • Python - 2.7+
    • Ruby - 2+
    • PHP - 5.6+
    • C# - 4.5+
  • Purchased Phone Number - You must purchase a phone number in TelePortal to use with this API.

📘

NOTE:

If you do not have a customer ID, sign up for TeleSign's Free Trial.

Install the SDK

  1. Obtain your customer ID and API key.
  2. Log in to GitHub and choose the SDK in your preferred language:
  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:
npm install telesignsdk -save
compile 'com.telesign:telesign:[current_version]'
<dependency>
    <groupId>com.telesign</groupId>
    <artifactId>telesign</artifactId>
    <version>[current_version]</version>
</dependency>
# From a terminal run:
pip install telesign
# From a terminal run:
gem install telesign
# From a terminal run:
composer require telesign/telesign
/* Add this to your packages.config file. */
<package id="Telesign" version="(insert latest version)" targetFramework="(insert framework)" />

Send SMS Message with a Verification Code

This section explains how to send an SMS message containing a verification code using the Messaging API. The sample code is provided as a single block first, and then broken out into pieces and explained below.

In this code sample, you provide your customer ID and API key to authenticate yourself with TeleSign. Then you generate a verification code and insert it into the text of your message. You create a MessagingClient object and use the message method to send an SMS containing your message and verification code. The steps below explain the code sample with more detail.

  1. Begin by adding the appropriate import statements.
var TeleSignSDK = require('telesignsdk');
package com.telesign.example.messaging;

import com.telesign.MessagingClient;
import com.telesign.RestClient;
import com.telesign.Util;
from __future__ import print_function
from telesign.messaging import MessagingClient
from telesign.util import random_with_n_digits

#If you are working with a version of Python 3, you do not need the first import statement (`from __future__ import print_function`).
from __future__ import print_function
from telesign.messaging import MessagingClient
from telesign.util import random_with_n_digits

#If you are working with a version of Python 3, you do not need the first import statement (`from __future__ import print_function`).
<?php
require __DIR__ . "/../../vendor/autoload.php";
use telesign\sdk\messaging\MessagingClient;
use function telesign\sdk\util\randomWithNDigits;
using System;
  1. Insert values for each of the items from customer_id through to message_type.
    • customer_id/customerId - Your TeleSign assigned customer ID, available in your account information in the portal.
    • api_key/apiKey - Your TeleSign assigned API key, available in your account information in the portal.
    • phone_number/phoneNumber - The phone number purchased from TeleSign in TelePortal that you want to use. When you provide the number, it should be a string with no spaces or special characters. Include the complete number; for example, for a US phone number, you would include the country code and the area code with the number, like this:16505551212.
    • message_type/messageType - Label the type of message you are sending. You have three choices (each is a string):
      OTP - One time passwords, ARN - Alerts, reminders, and notifications, and MKT - Marketing traffic

For Node.js, you choose a verification code rather than generating a random one.

const customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890"; // Todo: find in portal.telesign.com
const apiKey = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=="; // Todo: find in portal.telesign.com
const rest_endpoint = "https://rest-api.telesign.com"; // Todo: Enterprise customer, change this!
const timeout = 10*1000; // 10 secs

const client = new TeleSignSDK( customerId,
    apiKey,
    rest_endpoint,
    timeout // optional
    // userAgent
);

const phoneNumber = "Your test phone number with no special characters or spaces goes here.";
const messageType = "ARN";
const verifyCode = "32658";
const message = "Your code is " + verifyCode;
const customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890"; // Todo: find in portal.telesign.com
const apiKey = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=="; // Todo: find in portal.telesign.com
const rest_endpoint = "https://rest-api.telesign.com"; // Todo: Enterprise customer, change this!
const timeout = 10*1000; // 10 secs

const client = new TeleSignSDK( customerId,
    apiKey,
    rest_endpoint,
    timeout // optional
    // userAgent
);

const phoneNumber = "Your test phone number with no special characters or spaces goes here.";
const messageType = "ARN";
const verifyCode = "32658";
const message = "Your code is " + verifyCode;
customer_id = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890"
api_key = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=="

phone_number = "Your test phone number with no special characters or spaces goes here."
message_type = "OTP"
customer_id = 'FFFFFFFF-EEEE-DDDD-1234-AB1234567890'
api_key = 'EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=='

phone_number = 'Your test phone number with no special characters or spaces goes here.'
message_type = 'OTP'
$customer_id = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
$api_key = "EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";
$phone_number = "Your test phone number with no special characters or spaces goes here.";
$message_type = "OTP";
namespace Telesign.Example.Messaging
{
    class SendMessageWithVerificationCode
    {
        static void Main(string[] args)
        {
            string customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
            string apiKey = "EXAMPLETE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";

            string phoneNumber = "Your test phone number with no special characters or spaces goes here.";
            string messageType = "OTP";
  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 do not generate a random code.
//Step does not apply for Node.js example
        String verifyCode = Util.randomWithNDigits(5);
verify_code = random_with_n_digits(5)
verify_code = Telesign::Util.random_with_n_digits(5)
$verify_code = randomWithNDigits(5);
            string verifyCode = "12345";
  1. Insert your verification code into the text of your message. For the node.js example, use this step to set up your console and create a function that will be used to check the results of sending an end user an SMS message with a verification code.
console.log("## MessagingClient.message ##");

function messageCallback(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 message. " + error);
    }
}
        String message = String.format("Your code is %s", verifyCode);
message = "Your code is {}".format(verify_code)
message = 'Your code is {}'.format(verify_code)
$message = "Your code is $verify_code";
            string message = string.Format("Your code is {0}", verifyCode);
  1. Instantiate a MessagingClient object containing your customer_id/customerId and api_key/apiKey. Send an SMS to the phone number containing the message and message type you provided. Store the response in response.
client.sms.message(messageCallback, phoneNumber, message, messageType);
        try {
            MessagingClient messagingClient = new MessagingClient(customerId, apiKey);
            RestClient.TelesignResponse telesignResponse = messagingClient.message(phoneNumber, message, messageType, null);
        } 
messaging = MessagingClient(customer_id, api_key)
response = messaging.message(phone_number, message, message_type)
messaging_client = Telesign::MessagingClient.new(customer_id, api_key)
response = messaging_client.message(phone_number, message, message_type)
$messaging = new MessagingClient($customer_id, $api_key);
$response = $messaging->message($phone_number, $message, $message_type);
            try
            {
                MessagingClient messagingClient = new MessagingClient(customerId, apiKey);
                RestClient.TelesignResponse telesignResponse = messagingClient.Message(phoneNumber, message, messageType);
            }
  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 you how it works.
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());
    });
}
/**Java does not include this step, a print out of the response is provided in the last step.**/
user_entered_verify_code = raw_input("Please enter the verification code you were sent: ")
print 'Please enter the verification code you were sent: '
user_entered_verify_code = gets.strip
echo "Please enter the verification code you were sent: ";
$user_entered_verify_code = trim(fgets(STDIN));
//C# does not include this step, a print out of the response is provided in the last step.
  1. Check the code entered by the end user against the verification code you generated.
prompt('Enter the verification code received:\n', function (input) {
    if (input === verifyCode) {
        console.log('Your code is correct.');
    } else {
        console.log('Your code is incorrect. input: ' + input + ", code: " + verifyCode);
    }
    process.exit();
});
catch (Exception e) {
            e.printStackTrace();
        }
    }
}
if verify_code == user_entered_verify_code.strip():
    print("Your code is correct.")
else:
    print("Your code is incorrect.")
if verify_code == user_entered_verify_code
    puts 'Your code is correct.'
else
    puts 'Your code is incorrect.'
end
if ($verify_code == $user_entered_verify_code) {
  echo "Your code is correct.";
}
else {
  echo "Your code is incorrect.";
}
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("Press any key to quit.");
            Console.ReadKey();
        }
    }
}
  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'll need the following documents:


Did this page help you?