SMS Verify API - Tutorial: Get Started with the SDK

This tutorial teaches you how to use the SMS Verify SDK, by walking you step-by-step through the creation of an integration where you send your own verification code to an end-user. Skip to the end of this page to see the full, completed sample code.

📘

NOTE:

This tutorial includes CLI examples using a bash shell in Mac Terminal, please modify accordingly if you are using a different system.

Before You Begin

Make sure you have the following before you start:

  • Authentication Credentials: Your Customer ID and API Key. If you need help finding these items, go to the support article How do I find my Customer ID and API Key.
  • Testing Device: A mobile phone on which you can receive SMS.

Python

📘

NOTE:

This tutorial uses Python 3.8.1. Please modify accordingly if you are using a different version of Python.

Step 1: Download the SDK

  1. Create a directory on your machine where you want to download the TeleSign Python SDK. This should not be in the same directory as where you build your integration.
cd ~/code/local
mkdir telesign_sdks
cd telesign_sdks
  1. In the new directory you created, clone the SDK from GitHub. A new directory should appear called python_telesign_enterprise:
git clone https://github.com/TeleSign/python_telesign_enterprise.git

Step 2: Create Code to Send the SMS

  1. Create another directory (must be outside of the SDK directory you just created) where you want your SMS Verify integration to go.
cd ~/code/local/telesign_integrations
mkdir sms_verify_integration
cd sms_verify_integration
  1. Install the SDK in this new directory using the CLI command below. It references the path to where you downloaded the SDK. Once the SDK is installed, you should see Successfully installed telesignenterprise in the terminal:
pip install -e ~/code/local/telesign_sdks/python_telesign_enterprise/
  1. Create a new file in your integration folder called verify_with_own_code.py and open it in your editor:
touch verify_with_own_code.py
  1. Add code to import dependencies from the TeleSign SDK:
from telesignenterprise.verify import VerifyClient
from telesign.util import random_with_n_digits
  1. Define variables to store your authentication credentials:
customer_id = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890"
api_key = "TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=="
  1. Define a variable to hold the end-user's phone number you want to send a verification code to. For this tutorial, hardcode the phone number to one for a device you can use for testing:
phone_number = "15558675309"

📘

NOTE:

In your production integration, have phone_number pull from your recipient database instead of hardcoding it.

  1. Randomly generate your verification code. We will use a TeleSign SDK utility for this. The parameter value 5 specifies the number of digits generated:
verify_code = random_with_n_digits(5)
  1. Instantiate a verification object with your authentication credentials.
verify = VerifyClient(customer_id, api_key)
  1. Send a verification SMS to the end-user and store the response. Behind the scenes, this sends an HTTP request to the TeleSign SMS Verify API. TeleSign then sends an SMS with the code to the end-user:
response = verify.sms(phone_number, verify_code=verify_code)
  1. Collect the potential verification code entered by the end-user in your application. In this tutorial, we will simulate this by prompting for input from the command line.
user_entered_verify_code = input("Please enter the verification code you were sent: ")

📘

NOTE:

In your production implementation, you will listen for input from your website or other application where the end-user is trying to log in.

  1. Determine if the user-entered code matches your verification code, and resolve the login attempt accordingly. In this tutorial, we just report whether the codes match.
if verify_code == user_entered_verify_code.strip():
    print("Your code is correct.")
else:
    print("Your code is incorrect.")

📘

NOTE:

In your production implementation, you will add code here to log the user in when the codes match.

Step 3: Test Your Integration

  1. Switch from your editor to the terminal and run verify_with_own_code.py.
python verify_with_own_code.py
  1. You should receive an SMS on your phone that looks like this:
11251125
  1. In the terminal, you should see a prompt to enter a code. Enter the code from your phone to test a successful verification:
Please enter the verification code you were sent: 82139
Your code is correct.
  1. Now let's test an unsuccessful verification. Run verify_with_own_code.py again:
python verify_with_own_code.py
  1. You should receive a new and different SMS code on your phone. Enter something else though in the command prompt, and you should get a message that verification failed.
Please enter the verification code you were sent: 55555
Your code is incorrect.

Complete Sample Code

Here is the complete sample code for this tutorial:

from telesignenterprise.verify import VerifyClient
from telesign.util import random_with_n_digits

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

phone_number = "15558675309"
verify_code = random_with_n_digits(5)

verify = VerifyClient(customer_id, api_key)
response = verify.sms(phone_number, verify_code=verify_code)

user_entered_verify_code = 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.")

Node.js

📘

NOTE:

This tutorial uses Node 13.8.0. Please modify accordingly if you are using a different version of Node.

Step 1: Download the SDK

  1. Create a directory on your machine where you want to download the TeleSign Node SDK. This should not be in the same directory as where you build your integration.
cd ~/code/local
mkdir telesign_sdks
cd telesign_sdks
  1. In the new directory you created, clone the SDK from GitHub. A new directory should appear called node_telesign_enterprise:
git clone https://github.com/TeleSign/node_telesign_enterprise.git

Step 2: Create Code to Send the SMS

  1. Create another directory (must be outside of the SDK directory you just created) where you want to create your SMS Verify integration.
cd ~/code/local/telesign_integrations
mkdir sms_verify_integration
cd sms_verify_integration
  1. Install the SDK in this new directory using the CLI command below. It references the path to where you downloaded the SDK. Once the SDK is installed, you should see + [email protected] in the terminal:
npm install ~/code/local/telesign_sdks/node_telesign_enterprise -save
  1. Create a new file in your integration folder called verify_with_own_code.js and open it in your editor:
touch verify_with_own_code.js
  1. Add code to import dependencies, including the TeleSign SDK:
const readline = require('readline');
const TelesignSDK = require('../../telesign_sdks/node_telesign_enterprise');
  1. Define variables to store your authentication credentials:
const customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
const apiKey = "TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";
  1. Define a variable to hold the end-user's phone number you want to send a verification code to. For this tutorial, hardcode the phone number to one for a device you can use for testing:
const phoneNumber = "15558675309";

📘

NOTE:

In your production integration, have phoneNumber pull from your recipient database instead of hardcoding it.

  1. Randomly generate your verification code, convert it to a string, and add it as a property to a parameters object. To generate a code with a different number of digits, change 99999 to, for example, 999.
const optionalParams = {verify_code: Math.floor(Math.random() * 99999).toString()};

🚧

Caution:

The method used above to generate a code is actually pseudo-random. In your production implementation, you might want to use a more robust method for randomizing.

  1. Instantiate a verification object with your authentication credentials.
const client = new TelesignSDK(customerId, apiKey);
  1. Define a callback function to output the response from the service, including any errors. The sample code below includes reference to two functions (prompt and verify) that we will define in some later steps:
function smsCallback(error, responseBody) {
    if (error === null) {
        console.log(`\nMessaging response for messaging phone number: ${phoneNumber}\n` +
            `  code: ${responseBody['status']['code']}\n` +
            `  description: ${responseBody['status']['description']}`);
    } else {
        console.error("Unable to send SMS. Error:\n\n" + error);
    }
    prompt('\nEnter the verification code you received:\n', verify);
}
  1. Define a function that collects the potential verification code entered by the end-user in your application. In this tutorial, we will simulate this by prompting for input from the command line:
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. Define a function that collects the potential verification code entered by the end-user in your application. Determine if the user-entered code matches your verification code, and resolve the login attempt accordingly. In this tutorial, we just report whether the codes match. Since the program needs to end after this is run, we'll also add a statement here to exit the process:
function verify(input) {
    if (input === optionalParams['verify_code']) {
        console.log('\nYour code is correct.');
    } else {
        console.log('\nYour code is incorrect.');
    }
    process.exit();
}

📘

NOTE:

In your production implementation, you will add code here to log the user in when the codes match.

  1. Send a verification SMS to the end-user and pass the response to the callback. Behind the scenes, this sends an HTTP request to the TeleSign SMS Verify API. TeleSign then sends an SMS with the code to the end-user:
client.verify.sms(smsCallback, phoneNumber, optionalParams);

Step 3: Test Your Integration

  1. Switch from your editor to the terminal and run verify_with_own_code.js.
node verify_with_own_code.js
  1. A message appears in the terminal giving you the response from the TeleSign API. Unless there was a problem you should get a 290 code:
Messaging response for messaging phone number: 15558675309
   code: 290
   description: Message in progress
  1. You should receive an SMS on your phone that looks like this:
11251125
  1. In the terminal, you should see a prompt to enter a code:
Enter the verification code you received:
  1. Enter the code from your phone to test a successful verification. You should see this response:
Your code is correct.
  1. Now let's test an unsuccessful verification. Run verify_with_own_code.py again:
node verify_with_own_code.js
  1. You should receive a new and different SMS code on your phone. Enter something else though in the command prompt, and you should get a message that verification failed.
Your code is incorrect.

Complete Sample Code

Here is the complete sample code for this tutorial:

verify_with_own_code.js

const readline = require('readline');
const TelesignSDK = require('../../telesign_sdks/node_telesign_enterprise');

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

const phoneNumber = "15558675309";

const optionalParams = {verify_code: Math.floor(Math.random() * 99999).toString()};

const client = new TelesignSDK(customerId, apiKey);

function smsCallback(error, responseBody) {
    if (error === null) {
        console.log(`\nMessaging response for messaging phone number: ${phoneNumber}\n` +
            `  code: ${responseBody['status']['code']}\n` +
            `  description: ${responseBody['status']['description']}`);
    } else {
        console.error("Unable to send SMS. Error:\n\n" + error);
    }
    prompt('\nEnter the verification code you received:\n', verify);
}

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

function verify(input) {
    if (input === optionalParams['verify_code']) {
        console.log('\nYour code is correct.');
    } else {
        console.log('\nYour code is incorrect.');
    }
    process.exit();
}

client.verify.sms(smsCallback, phoneNumber, optionalParams);

Ruby

📘

NOTE:

This tutorial uses Ruby 2.7.1. Please modify accordingly if you are using a different version of Ruby.

Step 1: Download the SDK

  1. Create a directory on your machine where you want to download the TeleSign Ruby SDK. This should not be in the same directory as where you build your integration.
cd ~/code/local
mkdir telesign_sdks
cd telesign_sdks
  1. In the new directory you created, clone the SDK from GitHub. A new directory should appear called ruby_telesign_enterprise:
git clone https://github.com/TeleSign/ruby_telesign_enterprise.git

Step 2: Create Code to Send the SMS

  1. Create another directory (must be outside of the SDK directory you just created) where you want to create your SMS Verify integration.
cd ~/code/local/telesign_integrations
mkdir sms_verify_integration
cd sms_verify_integration
  1. Install the SDK in this new directory using the CLI commands below. After running the first command, you should see output including a line similar to Successfully installed telesign-2.2.3 in the terminal. After running the second, you should see output similar to Successfully installed telesignenterprise-2.2.1:
gem install telesign
gem install telesignenterprise
  1. Create a new file in your integration folder called verify_with_own_code.rb and open it in your editor:
touch verify_with_own_code.rb
  1. Add code to import dependencies from the TeleSign SDK:
require 'telesign'
require 'telesignenterprise'
  1. Define variables to store your authentication credentials:
customer_id = 'FFFFFFFF-EEEE-DDDD-1234-AB1234567890'
api_key = 'TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw=='
  1. Define a variable to hold the end-user's phone number you want to send a verification code to. For this tutorial, hardcode the phone number to one for a device you can use for testing:
phone_number =  "15558675309"

📘

NOTE:

In your production integration, have phone_number pull from your recipient database instead of hardcoding it.

  1. Randomly generate your verification code. We will use a TeleSign SDK utility for this. The parameter value 5 specifies the number of digits generated:
verify_code = Telesign::Util.random_with_n_digits(5)
  1. Instantiate a verification object with your authentication credentials.
verify_client = TelesignEnterprise::VerifyClient.new(customer_id, api_key)
  1. Send a verification SMS to the end-user and store the response. Behind the scenes, this sends an HTTP request to the TeleSign SMS Verify API. TeleSign then sends an SMS with the code to the end-user:
response = verify_client.sms(phone_number, verify_code: verify_code)
  1. Collect the potential verification code entered by the end-user in your application. In this tutorial, we will simulate this by prompting for input from the command line.
print 'Please enter the verification code you were sent: '
user_entered_verify_code = gets.strip

📘

NOTE:

In your production implementation, you will listen for input from your website or other application where the end-user is trying to log in.

  1. Determine if the user-entered code matches your verification code, and resolve the login attempt accordingly. In this tutorial, we just report whether the codes match.
if verify_code == user_entered_verify_code
  puts 'Your code is correct.'
else
  puts 'Your code is incorrect.'
end

📘

NOTE:

In your production implementation, you will add code here to log the user in when the codes match.

Step 3: Test Your Integration

  1. Switch from your editor to the terminal and run verify_with_own_code.rb.
ruby verify_with_own_code.rb
  1. You should receive an SMS on your phone that looks like this:
11251125
  1. In the terminal, you should see a prompt to enter a code. Enter the code from your phone to test a successful verification:
Please enter the verification code you were sent: 82139
Your code is correct.
  1. Now let's test an unsuccessful verification. Run verify_with_own_code.rb again:
ruby verify_with_own_code.rb
  1. You should receive a new and different SMS code on your phone. Enter something else though in the command prompt, and you should get a message that verification failed.
Please enter the verification code you were sent: 55555
Your code is incorrect.

Complete Sample Code

Here is the complete sample code for this tutorial:

require 'telesign'
require 'telesignenterprise'

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

phone_number =  "15558675309"
verify_code = Telesign::Util.random_with_n_digits(5)

verify_client = TelesignEnterprise::VerifyClient.new(customer_id, api_key)
response = verify_client.sms(phone_number, verify_code: verify_code)

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

Java

📘

NOTE:

This tutorial uses Java 14.0.1, Gradle 6.6.1, and IntelliJ CE 2020.3. Install Gradle before beginning this tutorial.

Step 1: Download the SDK

  1. Create a directory on your machine where you want to download the TeleSign Enterprise Java SDK. This should not be in the same directory as where you build your integration.
cd ~/code/local
mkdir telesign_sdks
cd telesign_sdks
  1. In this new directory, clone the SDK from GitHub. A new directory is created called "java_telesign_enterprise".
git clone https://github.com/TeleSign/java_telesign_enterprise.git

Step 2: Set Up Your Project

  1. Create another directory (must be outside of the SDK directory you just created) where you want to create your SMS Verify integration.
cd ~/code/local/telesign_integrations
mkdir smsVerifyIntegration
cd smsVerifyIntegration
  1. Create a new Gradle project.
gradle init
  1. Enter the following details for the new Gradle project.:
    • Select type of project to generate — 2: application
    • Select implementation language — 3: Java
    • Select build script DSL — 2: Kotlin
    • Select test framework — 1: JUnit 4
    • Project Name — Press return key to use the default project name.
    • Source package — VerifyWithOwnCode
28062806
  1. Once you see "BUILD SUCCESSFUL" in the terminal, copy all the .java source files from the Enterprise SDK into your project.
cp -r ~/code/local/telesign_sdks/java_telesign_enterprise/src/main/java/com ~/code/local/Java/smsVerifyIntegration/src/main/java/
  1. Open IntelliJ, select File > Open, and open the directory for your integration. For now you just have the skeleton of a project, we will fill in more details soon. Notice that in the file tree in the Project pane the Enterprise SDK files are visible in src > main > java > com > telesign > enterprise.
702702
  1. Next we need to add some dependencies to your project. Open the file "build.gradle.kts".
  2. In the repositories block, add mavenCentral() below jcenter() so the project can load dependencies from this repository.
repositories {
    // Use jcenter for resolving dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
    mavenCentral()
}
  1. In the dependencies block, add the following dependencies below the one that is already there. The com.telesign:telesign:2.3.0 dependency pulls in the TeleSign self-service SDK, which contains methods also used by the TeleSign Enterprise SDK.
dependencies {
    // This dependency is used by the application.
    implementation("com.google.guava:guava:29.0-jre")
    implementation("com.google.code.gson:gson:2.2.+")
    implementation ("com.squareup.okio:okio:2.9.0")
    implementation("com.telesign:telesign:2.3.0")


    // Use JUnit test framework
    testImplementation("junit:junit:4.13")
}
  1. Now open the main .java source file in your project, under src > main > java > VerifyWithOwnCode > App.java. You will see some starter code here, which we are going to replace later with the code to send your SMS messages.
27702770
  1. The filename "App" isn't very descriptive, so lets rename it to "SendSMSWithVerificationCode". Right-click on src > main > java > VerifyWithOwnCode > App.java in the Project file tree, then select Refactor > Rename and give it the new name.
902902
  1. A prompt appears asking if you want to also rename the default test in the project from "AppTest" to "SendSMSWithVerificationCodeTest". It's a good idea to have descriptive test names too, so select the test and then OK.
17791779

Step 3: Modify Default Unit Test

  1. Now we're going to modify that test class that you just renamed. Open src > test > java > VerifyWithOwnCode.SendSMSWithVerificationCodeTest.java. You should see this class declaration.
public class SendSMSWithVerificationCodeTest {
    @Test public void testAppHasAGreeting() {
        SendSMSWithVerificationCode classUnderTest = new SendSMSWithVerificationCode();
        assertNotNull("app should have a greeting", classUnderTest.getGreeting());
    }
}
  1. This simple test is perfectly fine, but let's just change the text that the getGreeting method is expected to return to something more informative.
public class SendSMSWithVerificationCodeTest {
    @Test public void testAppHasAGreeting() {
        SendSMSWithVerificationCode classUnderTest = new SendSMSWithVerificationCode();
        assertNotNull("The class SendSMSWithVerificationCode is present.", classUnderTest.getGreeting());
    }
}
  1. Now we're ready to start editing the main .java source file for the application. Open src > main > java > VerifyWithOwnCode > SendSMSWithVerificationCode.java. The default contents of the file include two methods. Modify the getGreeting method so it returns the string we defined in our test.
public class SendSMSWithVerificationCode {
    public String getGreeting() {
        return "The class SendSMSWithVerificationCode is present.";
    }

    public static void main(String[] args) {
        System.out.println(new SendSMSWithVerificationCode().getGreeting());
    }
}

Step 4: Create Messaging Functionality

With all that setup out of the way, now we're ready to start coding the main functionality of the application.

  1. Add the imports below between the package declaration and the class declaration in that same file. Imports starting with com.telesign reference the TeleSign self-service SDK, while those starting with com.telesign.enterprise reference the Enterprise SDK.
package VerifyWithOwnCode;

import com.telesign.RestClient;
import com.telesign.Util;
import com.telesign.enterprise.VerifyClient;
import java.util.HashMap;
import java.util.Scanner;
  1. Now we need to add to the main method. Define variables to store your authentication credentials:
    public static void main(String[] args) {

                String customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
                String apiKey = "TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";
  1. Define a variable to hold the end-user's phone number you want to send a verification code to. For this tutorial, hardcode the phone number to one for a device you can use for testing:
String phoneNumber = "15558675309";

📘

NOTE:

In your production integration, have phone_number pull from your recipient database instead of hardcoding it.

  1. Randomly generate your verification code. We will use a TeleSign SDK utility for this. The parameter value 5 specifies the number of digits generated.
String verifyCode = Util.randomWithNDigits(5);
  1. Create a new hash map, and use it to store the params you are going to send to the TeleSign SMS Verify API. The only param included in this tutorial is the verification code.
HashMap<String, String> params = new HashMap<>();
params.put("verify_code", verifyCode);
  1. Create a try/catch block. We'll use this to enclose the rest of the functionality for the application, and if anything goes wrong when you run it you'll get some useful troubleshooting output.
try {
  
} catch (Exception e) {
    e.printStackTrace();
}
  1. Inside the try block, instantiate a verification object with your authentication credentials.
VerifyClient verifyClient = new VerifyClient(customerId, apiKey);
  1. Send a verification SMS to the end-user and store the response. Behind the scenes, this sends an HTTP request to the TeleSign SMS Verify API. TeleSign then sends an SMS with the code to the end-user.
RestClient.TelesignResponse telesignResponse = verifyClient.sms(phoneNumber, params);
  1. Collect the potential verification code entered by the end-user in your application. In this tutorial, we will simulate this by prompting for input from the command line.
Scanner s = new Scanner(System.in);
System.out.println("Please enter your verification code:");
String code = s.next();

📘

NOTE:

In your production implementation, you will listen for input from your website or other application where the end-user is trying to log in.

  1. Determine if the user-entered code matches your verification code, and resolve the login attempt accordingly. In this tutorial, we just report whether the codes match.
if (verifyCode.equalsIgnoreCase(code)) {
    System.out.println("Your code is correct.");
} else {
    System.out.println("Your code is incorrect.");
}

📘

NOTE:

In your production implementation, you will add code here to log the user in when the codes match.

  1. We've finished writing the code, so the next step is to build the application. Select Build > Build Project from the main menu in IntelliJ. You should see "BUILD SUCCESSFUL" in the Build Output pane.
27272727

Step 5: Test Your Integration

  1. Make sure you have the class src > main > java > VerifyWithOwnCode > SendSMSWithVerificationCode selected in the file tree in the Project pane. Select Run > Run from the main menu in IntelliJ. You should receive an SMS on your phone that looks like this:
11251125
  1. In the Run pane in IntelliJ, you should see a prompt to enter a code. Enter the code from your phone to test a successful verification:
26832683
  1. Now let's test an unsuccessful verification. Run the application again in IntelliJ. You should receive a new and different SMS code on your phone. Enter something else though in the command prompt, and you should get a message that verification failed.
26842684

Complete Sample Code

Here is the complete sample code for this tutorial:

SendSMSWithVerificationCode.java

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
package VerifyWithOwnCode;

import com.telesign.RestClient;
import com.telesign.Util;
import com.telesign.enterprise.VerifyClient;
import java.util.HashMap;
import java.util.Scanner;

public class SendSMSWithVerificationCode {
    public String getGreeting() {
        return "The class SendSMSWithVerificationCode is present.";
    }

    public static void main(String[] args) {
        String customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
        String apiKey = "TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";

        String phoneNumber = "15558675309";
        String verifyCode = Util.randomWithNDigits(5);

        HashMap<String, String> params = new HashMap<>();
        params.put("verify_code", verifyCode);

        try {
            VerifyClient verifyClient = new VerifyClient(customerId, apiKey);
            RestClient.TelesignResponse telesignResponse = verifyClient.sms(phoneNumber, params);

            Scanner s = new Scanner(System.in);
            System.out.println("Please enter your verification code:");
            String code = s.next();

            if (verifyCode.equalsIgnoreCase(code)) {
                System.out.println("Your code is correct.");
            } else {
                System.out.println("Your code is incorrect.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

SendSMSWithVerificationCodeTest.java

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
package VerifyWithOwnCode;

import org.junit.Test;
import static org.junit.Assert.*;

public class SendSMSWithVerificationCodeTest {
    @Test public void testAppHasAGreeting() {
        SendSMSWithVerificationCode classUnderTest = new SendSMSWithVerificationCode();
        assertNotNull("The class SendSMSWithVerificationCode is present.", classUnderTest.getGreeting());
    }
}

build.gradle.kts

/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * User Manual available at https://docs.gradle.org/6.6.1/userguide/tutorial_java_projects.html
 */

plugins {
    // Apply the java plugin to add support for Java
    java

    // Apply the application plugin to add support for building a CLI application.
    application
}

repositories {
    // Use jcenter for resolving dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
    mavenCentral()
}

dependencies {
    // This dependency is used by the application.
    implementation("com.google.guava:guava:29.0-jre")
    implementation("com.google.code.gson:gson:2.2.+")
    implementation("com.squareup.okio:okio:2.9.0")
    implementation("com.telesign:telesign:2.3.0")

    // Use JUnit test framework
    testImplementation("junit:junit:4.13")
}

application {
    // Define the main class for the application.
    mainClassName = "VerifyWithOwnCode.App"
}

C#

📘

NOTE:

This tutorial uses Visual Studio for Mac 8.8.4 and .NET 4.7.2.

Step 1: Create Your Project in Visual Studio

Visual Studio isn't required to use the TeleSign SDK, but we're going to use it in this tutorial to keep things simple.

  1. Open Visual Studio.
  2. Select New to create a new project. A prompt appears to choose a template for the project.
  3. Select Other > .NET > Console Project. In your production integration you will likely choose a different project type, but in this tutorial we're going to simulate user input through the command-line.
  4. Select Next.
  5. Enter smsVerifyIntegration for Project Name.
  6. For Location, browse to select your desired directory to create the project. This should be outside of any TeleSign SDK directories you may have already installed on your machine.
  7. Select Create. A skeleton project is created.
  8. "Program.cs" is where we will create your main method for sending an SMS.
  9. Rename this file “verifyWithOwnCode.cs”. This doesn't affect the functionality, it's just a more descriptive name.
800800

Step 2: Add Dependencies

Next we're going to add all the external dependencies needed for the project, including the TeleSign SDK.

  1. Right-click Packages in the file-tree in the Solution pane.
  2. Select Manage NuGet Packages...
  3. Make sure "nuget.org" is selected in the source menu in the upper left.
  4. Enter “Telesign” in the search field in the upper-right to narrow down the list of packages shown.
  5. Select the packages named "Telesign" and "TelesignEnterprise".
800800
  1. Select Add Packages. Three packages are added in the file-tree. "TelesignEnterprise" is the Enterprise SDK and "Telesign" is the self-service SDK (some features of this SDK are used even in Enterprise integrations). The third package, "Newtonsoft.Json", is a dependency used by the SDK for handling JSON.

Step 3: Create Messaging Functionality

With all that setup out of the way, now we're ready to start coding the main functionality of the application.

  1. Add the imports below after the one that is already there in the template-generated code. The Telesign import references the TeleSign self-service SDK and the TelesignEnterprise one references the Enterprise SDK.
using System;
using System.Collections.Generic;
using Telesign;
using TelesignEnterprise;
  1. Rename the class MainClass to something more descriptive like SendSMSWithVerificationCode.
using System;
using System.Collections.Generic;
using Telesign;
using TelesignEnterprise;

namespace smsVerifyIntegration
{
    class SendSMSWithVerificationCode
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}
  1. Now we need to add to the Main method. You can overwrite the template-generated Console.WriteLine statement. Define variables to store your authentication credentials:
string customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
string apiKey = "TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";
  1. Define a variable to hold the end-user’s phone number you want to send a verification code to. For this tutorial, hardcode the phone number to one for a device you can use for testing:
string phoneNumber = "15558675309";

📘

NOTE:

In your production integration, have phoneNumber pull from your recipient database instead of hardcoding it.

  1. Randomly generate your verification code.
Random random = new Random();
int num = random.Next(100000);
string verifyCode = num.ToString();

🚧

CAUTION:

The method used above to generate a code is actually pseudo-random. In your production implementation, you might want to use a more robust method for randomizing.

  1. Create a dictionary, and use it to store the params you are going to send to the TeleSign SMS Verify API. The only param included in this tutorial is the verification code.
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("verify_code", verifyCode);
  1. Create a try/catch block. We’ll use this to enclose the rest of the functionality for the application, and if anything goes wrong when you run it you’ll get some useful troubleshooting output.
try
{
}
catch (Exception e)
{
    Console.WriteLine(e);
}
  1. Inside the try block, instantiate a verification object with your authentication credentials.
VerifyClient verifyClient = new VerifyClient(customerId, apiKey);
  1. Send a verification SMS to the end-user and store the response. Behind the scenes, this sends an HTTP request to the TeleSign SMS Verify API. TeleSign then sends an SMS with the code to the end-user.
RestClient.TelesignResponse telesignResponse = verifyClient.Sms(phoneNumber, parameters);
  1. Collect the potential verification code entered by the end-user in your application. In this tutorial, we will simulate this by prompting for input from the command line.
Console.WriteLine("Please enter your verification code:");
string code = Console.ReadLine().Trim();

📘

NOTE:

In your production implementation, you will listen for input from your website or other application where the end-user is trying to log in.

  1. Determine if the user-entered code matches your verification code, and resolve the login attempt accordingly. In this tutorial, we just report whether the codes match.
if (verifyCode == code)
{
    Console.WriteLine("Your code is correct.");
}
else
{
    Console.WriteLine("Your code is incorrect.");
}

📘

NOTE:

In your production implementation, you will add code here to log the user in when the codes match.

  1. We’ve finished writing the code, so the next step is to build the application. Select Build > Build All from the main menu in Visual Studio. You should see “Build succeeded.” in the Build Output pane.
10001000

Step 4: Test Your Integration

  1. Select the Run button in Visual Studio. You should receive an SMS on your phone that looks like this:
11251125
  1. In the Terminal pane in IntelliJ, you should see a prompt to enter a code. Enter the code from your phone to test a successful verification:
16021602
  1. Now let’s test an unsuccessful verification. Run the application again in Visual Studio. You should receive a new and different SMS code on your phone. Enter something else though in the command prompt, and you should get a message that verification failed.
15981598

Complete Sample Code

Here is the complete sample code for this tutorial:

using System;
using System.Collections.Generic;
using Telesign;
using TelesignEnterprise;

namespace smsVerifyIntegration
{
    class SendSMSWithVerificationCode
    {
        public static void Main(string[] args)
        {
            string customerId = "FFFFFFFF-EEEE-DDDD-1234-AB1234567890";
            string apiKey = "TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==";

            string phoneNumber = "15558675309";
            Random random = new Random();
            int num = random.Next(100000);
            string verifyCode = num.ToString();

            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("verify_code", verifyCode);

            try
            {
                VerifyClient verifyClient = new VerifyClient(customerId, apiKey);
                RestClient.TelesignResponse telesignResponse = verifyClient.Sms(phoneNumber, parameters);

                Console.WriteLine("Please enter your verification code:");
                string code = Console.ReadLine().Trim();

                if (verifyCode == code)
                {
                    Console.WriteLine("Your code is correct.");
                }
                else
                {
                    Console.WriteLine("Your code is incorrect.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

Did this page help you?