WhatsApp has become one of the most popular messaging platforms in the world, with over 2 billion active users. Many businesses are leveraging WhatsApp to engage with customers in a more personal way through conversational commerce.
One common use case for WhatsApp in business is to send one-time passwords (OTPs) to customers for authentication or verification purposes. For example, when a customer signs up for an account on your platform, you can send the OTP needed to activate their account directly via WhatsApp.
This guide will walk through the steps to get started with using the WhatsApp Business API to programmatically send OTPs to customers over WhatsApp.
Prerequisites
Before you can start sending OTPs over WhatsApp, there are a few prerequisites:
- A WhatsApp Business account
- The WhatsApp Business API
- A way to generate OTP tokens
- A server to integrate the API and send messages
Let’s go through each of these in more detail:
WhatsApp Business Account
First, you need a WhatsApp Business account for your business. This is required to get API access from WhatsApp. You can sign up for a business account through the WhatsApp Business app on your smartphone.
WhatsApp Business API
Next, you need access to the WhatsApp Business API. This allows you to programmatically send messages at scale. The API provides REST endpoints to send text messages, media, templates and more.
To get API access, you need to apply on the WhatsApp Business API site. WhatsApp will review your application and provide API credentials if approved.
OTP Token Generation
You’ll need a way to programmatically generate OTP tokens that are random and unique each time. These 6-8 digit codes will be sent in the WhatsApp messages.
There are many libraries and modules available for different languages and frameworks to generate OTP codes. For example, pyotp for Python or jwt for Node.js.
Server for Integration
Finally, you need a server to bring all the pieces together. This server will have the logic to:
- Generate OTP tokens
- Integrate with the WhatsApp Business API to send messages
- Handle incoming WhatsApp messages to validate OTPs
The server can be built with any technology like Node.js, Python, PHP, etc. The WhatsApp API uses HTTP REST so it can integrate with any programming language.
Generate an OTP
When a user needs an OTP, the first step is to programmatically generate a random 6 digit numeric token.
Here is example code to generate an OTP in Python:
“`python
import random
import string
def generate_otp():
# Generate 6 random digits
otp = ”.join(random.choices(string.digits, k=6))
return otp
“`
This will return a 6 character OTP token like “253891”.
Store this OTP along with the user ID or phone number it’s associated with. You will need to verify it when the user sends back the OTP.
Send OTP via WhatsApp API
Once the OTP is generated, you can send it via the WhatsApp Business API.
The API provides a messages endpoint to send text messages to users.
Here is sample code to send an OTP text message:
“`python
import requests
api_url = ‘https://api.whatsapp.com/v1/messages’
phone = ‘+1234567890’
otp = ‘253891’
text = f’Your OTP is {otp}’
data = {
‘messaging_product’: ‘whatsapp’,
‘to’: phone,
‘type’: ‘text’,
‘text’: {
‘body’: text
}
}
headers = {
‘Authorization’: ‘Bearer YOUR_API_KEY’
}
response = requests.post(api_url, json=data, headers=headers)
“`
This will send a WhatsApp text message containing the OTP code to the user’s phone number.
You can similarly send OTPs to multiple users in parallel using the API.
Verify OTP
To complete the OTP verification flow, you need to check the OTP received back from the user against the one you originally sent.
The WhatsApp API provides a webhook to receive and respond to incoming messages. Set up a webhook endpoint on your server.
When the user replies back with the OTP code, your webhook endpoint will receive the message. Parse the OTP from the text, fetch the original OTP you generated earlier, and verify if they match.
Here is sample Python code to verify the OTP:
“`python
from flask import Flask, request
app = Flask(__name__)
@app.route(‘/webhook’)
def handle_message():
if request.args.get(‘text’):
text = request.args[‘text’]
otp = text[-6:] # Extract last 6 digits
if otp == stored_otp[phone]:
return “OTP verified!”
else:
return “Invalid OTP!”
return “OTP not received”
“`
On successful verification, you can allow the user access or approve their transaction.
This completes the full OTP flow over WhatsApp using the WhatsApp Business API.
Benefits
Here are some benefits of using WhatsApp for OTP instead of SMS:
- Higher delivery success rate compared to SMS
- Lower costs than traditional SMS services
- Native WhatsApp user experience
- Two-way conversational messaging
- Automated analytics and reporting
WhatsApp business messaging drives higher user engagement and satisfaction scores compared to other channels.
Best Practices
Here are some best practices when sending OTPs over WhatsApp:
- Only send OTPs in response to a user request
- Provide a way to opt-out of receiving OTPs
- Set proper expectations on OTP validity duration
- Follow WhatsApp guidelines for business messaging
- Ensure proper security controls around OTP generation and storage
- Implement rate limiting to prevent API abuse
- Monitor performance metrics andlogs for improvements
Conclusion
The WhatsApp Business API provides a simple and convenient way to send OTPs to customers at scale. By following WhatsApp best practices, you can build secure and useful OTP experiences keeping the end user in mind.
This results in more efficient authentications, faster transactions, and happier customers. WhatsApp business messaging opens up native conversational experiences not possible with traditional channels.
Pros | Cons |
---|---|
Higher delivery rates | Requires business verification |
Lower cost | Extra integration work |
Better user experience | Rate limits apply |