SMS Verify API - Tutorial: Perform one-time passcode (OTP) verification in Python using a Telesign REST API

This tutorial teaches how to use the Telesign SMS Verify API to send a one-time passcode (OTP) to an end user via SMS. Go to GitHub to see the complete sample code.

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.

📘

NOTE:

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

This tutorial uses a Mac, please modify accordingly if you are using a different system.

Set up your project

  1. Create a new directory for your project. If you plan to create multiple Python projects that use Telesign, we recommend that you group them within a telesign_integrations directory. Create a directory for each Telesign product and, within that, for each use case.
    cd ~/code/local/telesign_integrations
    mkdir sms_verify
  1. Create a "shared" directory and enter it. This is where you download or create utilities that are used across all Telesign projects.
    mkdir shared
    cd shared
  1. Copy the ts_auth.py file from Telesign's GitHub site to this directory. This script handles generating a Basic authentication header for your integration.

  2. Go back up a level and then enter the directory for your project.

    cd ../sms_verify
  1. Create a new file for the script that will send an SMS, and open it in your code editor.
    touch verify_with_own_code.py

Create code to import your dependencies

  1. Import dependencies.
    from requests import Request, Session
    import os
    import sys
  1. Add the directory that contains ts_auth.py to the locations your script pulls dependencies from.
    sys.path.append('../shared/')
  1. Import the ts_auth dependency.
    import ts_auth

Create code to define your request

  1. Define a function to generate a pseudo-random number. You will use this in a later step to create an OTP for each SMS.
    def random_with_n_digits(n):
        return "".join(SystemRandom().choice('123456789') for _ in range(n))
  1. Define variables to store your Telesign authentication credentials. Either replace the defaults below or set these credentials as environment variables.
    customer_id = os.getenv('CUSTOMER_ID', 'ABC1DE23-A12B-1234-56AB-AB1234567890')
    api_key = os.getenv('API_KEY', 'ABC12345yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==')
  1. Set the REST API URL.
    url = "https://rest-ww.telesign.com/v1/verify/sms"
  1. Create variables to store the request inputs. The parameter value 5 below specifies how many digits long the OTP should be. Change the default below to your test phone number or set it as an environment variable.
    phone_number = os.getenv('PHONE_NUMBER', '1234567890')
    verify_code = random_with_n_digits(5)

📘

NOTE:

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

  1. Add all headers except auth headers.
    headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Date': ts_auth.format_current_date()
}
  1. Create the payload for the request.
    payload = f"phone_number={phone_number}&verify_code={verify_code}"

Create code to send the request

  1. Create the session and prepped request.
    s = Session()
    req = Request('POST', url, data=payload, headers=headers)
    prepped_request = req.prepare()
  1. Add the authentication header to the prepped request.
    request_properties = {
        "method": prepped_request.method,
        "headers": prepped_request.headers,
        "body": prepped_request.body,
        "url": prepped_request.url
    }

    prepped_request.headers = ts_auth.add_digest(request_properties, customer_id, api_key)
  1. Make the request and capture the response. If Telesign Verify Plus is enabled for SMS Verify API for your account, Telesign checks the risk recommendation of the phone number before sending the SMS.
    response = s.send(prepped_request)
  1. Display the request and the response in the console for debugging purposes. In your production code, you would likely remove this.
    ts_auth.pretty_print_request(prepped_request)
    print(f"Response:\n{response.text}\n")

Test your integration

Display a prompt in the console to enter the verification code sent via SMS.

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

📘

NOTE:

In your production code, you would instead collect the potential verification code from the end-user in your platform's interface.

Sample code

The complete sample code for this tutorial can be found on GitHub.