This tutorial implements phone number verification using the Twilio Verify API in Python, covering sending a one-time code and validating the code a user enters in your application. It targets developers building registration flows, two-factor authentication, or account recovery features. You will build a two-step Python flow: send an OTP to a phone number, then verify the code against Twilio's platform, which handles code generation, expiry, and attempt limits for you.
Prerequisites and Setup
You need Python 3.7 or higher, the Twilio SDK, and a Verify Service created in the Twilio Console under Verify. Install the SDK with pip install twilio python-dotenv and note your Verify Service SID, which starts with VA. Store your Account SID, Auth Token, and Verify Service SID as environment variables in a .env file. Twilio Verify handles code generation, SMS delivery, expiry (10 minutes by default), and retry limits without any additional configuration on your side.
pip install twilio python-dotenv flask
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_VERIFY_SERVICE_SID=VAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
The Complete Code
The Verify API exposes two operations: create a verification (send the code) and create a verification check (validate the code). Both calls go through client.verify.v2.services(SERVICE_SID), keeping the service context consistent. The verification check returns a VerificationCheckInstance whose status field is "approved" on success and "pending" or "canceled" on failure or expiry. Catch TwilioRestException with error code 60200 to handle invalid codes gracefully without raising an unhandled exception.
import os
from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException
from dotenv import load_dotenv
load_dotenv()
client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])
SERVICE_SID = os.environ["TWILIO_VERIFY_SERVICE_SID"]
def send_otp(phone_number: str) -> bool:
try:
verification = client.verify.v2.services(SERVICE_SID).verifications.create(
to=phone_number,
channel="sms",
)
print(f"Verification status: {verification.status}")
return True
except TwilioRestException as e:
print(f"Error sending OTP: {e.msg}")
return False
def check_otp(phone_number: str, code: str) -> bool:
try:
check = client.verify.v2.services(SERVICE_SID).verification_checks.create(
to=phone_number,
code=code,
)
return check.status == "approved"
except TwilioRestException as e:
if e.code == 60200:
print("Invalid or expired code.")
else:
print(f"Verify error {e.code}: {e.msg}")
return False
# Usage
phone = "+15551234567"
send_otp(phone)
user_input = input("Enter the code you received: ")
if check_otp(phone, user_input):
print("Phone verified successfully.")
else:
print("Verification failed.")
Testing and Debugging
Run the script and enter the code sent to your phone to confirm the happy path works end to end. Test the failure path by entering a wrong code and verifying your application handles the False return gracefully without crashing. Error code 60203 from Twilio means the maximum number of check attempts has been reached; the code is now permanently invalid, and the user must request a new one. Use Twilio's magic test numbers in the Console to test without consuming verification credits during development.
Taking It Further
Set the channel parameter to "call" instead of "sms" to deliver the OTP as an automated voice call for users who cannot receive SMS. Customize the code length (4 or 8 digits) and expiry window in the Verify Service settings in the Twilio Console. Add rate limiting in your application layer to prevent abuse, limiting OTP requests per phone number to a small number per hour. For silent verification without user interaction, explore Twilio Verify's Silent Device Approval and Push verification channels.
Speak with Telphi Consulting about implementing phone verification as part of a secure onboarding or authentication system.
Ready to Transform Your Business Communications?
Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.
Comments (0)
Join the discussion and share your thoughts (AI-moderated for quality)
Be the first to comment
No comments yet. Share your thoughts below.