Skip to main content

Overview

This guide shows how to use a voice one-time password (OTP) to verify a mobile number. We first make a call to the phone number to be verified and use text-to-speech to read a random sequence of digits to the call recipients. The user then confirms the digits by entering them using dialpad keypresses. Voice OTP is commonly used to verify new user registrations for an app or website. You can send a voice OTP either by using our PHLO visual workflow builder or our APIs and XML documents. Follow the instructions in one of the tabs below.
Here’s how to use Plivo APIs and XML to implement voice OTPs.

Prerequisites

To get started, you need a Plivo account — sign up with your work email address if you don’t have one already. If this is your first time using Plivo APIs, follow our instructions to set up a Python development environment.

Create a voice OTP application

Create a file called voiceotp.py and paste into it this code.
import plivo
import random
import redis

from flask import Flask, jsonify

app = Flask(__name__)

r = redis.StrictRedis()

def generate_code():
    code = random.choice(range(100000, 999999))  # generating 6-digit random code
    return code


# Make call to the destination number with OTP
@app.route("/dispatch_otp/<destination_number>")
def dispatch_otp(destination_number):
    try:
        # generate OTP.
        code = generate_code()

        # Make a call
        client = plivo.RestClient("<auth_id>", "<auth_token>")
        response = client.calls.create(
            from_="<caller_id>",
            to_=destination_number,
            answer_url=f"https://<yourdomain>.com/answer_url/{code}",
            answer_method="GET",
        )
        print(response)
        print(r.setex("number:%s:code" % destination_number, 60, code))
        return (
            jsonify({"status": "success", "message": "verification initiated"}),
            200,
        )
    except:
        return ("Error encountered", 400)

# verify the OTP enetered by the user
@app.route("/verify_otp/<destination_number>/<code>")
def check_code(destination_number, code):
    """
    check_code(number, code) accepts a number and the code entered by the user and
    tells whether the code entered is correct
    """
    # fetch the OTP set for the destination number
    original_code = r.get("number:%s:code" % destination_number)

    if int(original_code) == int(code):  # verification successful, delete the code
        r.delete("number:%s:code" % destination_number)
        return (
            jsonify({"status": "success", "message": "Codes match — number verified"}),
            200,
        )
    elif original_code != code:
        return (
            jsonify(
                {
                    "status": "rejected",
                    "message": "Codes do not match — number not verified",
                }
            ),
            404,
        )
    else:
        return (jsonify({"status": "failed", "message": "Number not found"}), 500)


if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)
Replace the auth placeholders with your authentication credentials from the Plivo console. Replace the phone number placeholder with an actual phone number in E.164 format (for example, +12025551234).
Note: We recommend that you store your credentials in the auth_id and auth_token environment variables, to avoid the possibility of accidentally committing them to source control. If you do this, you can initialize the client with no arguments and Plivo will automatically fetch the values from the environment variables. You can use os module(os.environ) to store environment variables and fetch them when initializing the client.

Test

Save the file and run it, and start Redis.
$ python voiceotp.py
$ redis-server
You should see your basic server application in action as below:
http://localhost:5000/dispatch_otp/destination_number
http://localhost:5000/verify_otp/destination_number/otp