Most WhatsApp OTP failures in Indian Python codebases are not caused by Meta's API. They come from the gap between the moment a code is issued and the moment a webhook confirms delivery — a gap many teams leave unhandled until their first incident.
This guide walks through the design decisions behind a reliable OTP flow: generating codes, sending them, verifying them, and handling the failure modes that matter. It avoids framework-specific assumptions so the structure works with FastAPI, Flask, or a background worker.
Understand the two parts of a WhatsApp OTP flow
A complete OTP system has two independent flows that meet at a shared store:
- The send flow — your application generates a code, stores it with an expiry and attempt counter, then asks a provider to deliver it over WhatsApp.
- The verification flow — the user submits the code, your application checks it against the store, and either accepts, rejects, or invalidates it.
WhatsApp adds a third, asynchronous concern: delivery status. A template message can be accepted by the provider and still fail to arrive — for example, if the recipient has not opted in, the template is paused, or the number is unreachable. A well-designed integration treats "sent" and "delivered" as separate states.
Before writing code, confirm the current message template rules, opt-in requirements, and rate limits from Meta's official WhatsApp Business documentation and your provider's docs. These change, and exact limits are not something to hardcode from a blog post. If you are evaluating EmacronAI's WhatsApp OTP module, the current behaviour is documented at crm.emacronai.com/docs/whatsapp-otp — verify details there rather than assuming them.
Model the OTP state before writing handlers
A common mistake is storing only phone -> code. That cannot answer "how many times has this been tried?" or "was this code ever delivered?" A more useful record looks like this:
from dataclasses import dataclass
from datetime import datetime
@dataclass
class OtpRecord:
phone: str
code_hash: str # store a hash, not the raw code
created_at: datetime
expires_at: datetime
attempts: int = 0
max_attempts: int = 5
status: str = "pending" # pending | sent | delivered | failed | verified | expired
Design notes that matter in practice:
- Hash the code. OTPs are short, so a hash alone is weak against brute force, but storing plaintext is worse. Pair the hash with a per-record salt, or use an HMAC keyed with a server secret.
- Set expiry explicitly. Five to ten minutes is a common range, but choose based on your risk model and state it in your UX copy.
- Track attempts. Lock the record after a fixed number of failures rather than allowing unlimited guesses.
- Keep status. This lets you answer support questions ("did it send?") without guessing.
Redis with a TTL is a natural fit for this record because expiry can be enforced by the store itself. A relational table works if you prefer auditability; add a cleanup job either way.
Send the code: keep the request path thin
The send endpoint should do three things: validate the phone number format (E.164 with the country code), write the OTP record, and hand off delivery. It should not block on the WhatsApp API call.
import secrets
import hashlib
from datetime import datetime, timedelta, timezone
def issue_otp(store, phone: str, secret: bytes) -> str:
code = f"{secrets.randbelow(1_000_000):06d}"
now = datetime.now(timezone.utc)
record = {
"phone": phone,
"code_hash": hashlib.sha256(secret + code.encode()).hexdigest(),
"created_at": now.isoformat(),
"expires_at": (now + timedelta(minutes=5)).isoformat(),
"attempts": 0,
"status": "pending",
}
store.set(phone, record, ttl=300)
enqueue_whatsapp_send(phone, code) # background job
return "queued"
Two details to get right:
- Normalise the number first. Store and compare in one canonical format so
+91 98765 43210and919876543210do not become two identities. - Rate limit per phone and per IP. Without this, an OTP endpoint becomes a free SMS/WhatsApp relay for abuse. Apply a short cooldown between resends (for example, 30–60 seconds) and a daily cap per number. Choose the actual numbers from your provider's guidance and your abuse data.
The background worker calls your provider's send API with the approved authentication template. Log the provider's message ID against the phone record so webhook events can be matched later.
Verify without leaking information
The verification handler is where subtle bugs live. A few rules keep it safe:
- Return the same error for wrong code, expired code, and unknown number. Distinguishing them tells an attacker which numbers are registered.
- Increment attempts before comparing, so a crash mid-check cannot reset the counter.
- Delete the record on success. A verified OTP must not be reusable.
- Use constant-time comparison for the hash check (
hmac.compare_digest).
import hmac, hashlib
def verify_otp(store, phone: str, submitted: str, secret: bytes) -> bool:
record = store.get(phone)
if not record:
return False
if record["attempts"] >= 5:
return False
record["attempts"] += 1
expected = record["code_hash"]
actual = hashlib.sha256(secret + submitted.encode()).hexdigest()
if not hmac.compare_digest(expected, actual):
store.set(phone, record, ttl=300)
return False
store.delete(phone)
return True
Note the ordering: attempts are incremented and persisted on failure, and the record is removed only on success. If you store records in a database, wrap the read-modify-write in a transaction or a conditional update to avoid race conditions under concurrent requests.
Handle delivery events and resends
WhatsApp delivery is asynchronous. Your integration should accept status webhooks and update the OTP record from sent to delivered or failed. This unlocks two useful behaviours:
- Resend only when it helps. If the provider reports a failure (for example, template paused or number not on WhatsApp), retrying the same template will not fix it. Surface a fallback channel or a clear error instead.
- Support can see reality. When a user says "I never got the code", the record tells you whether it was sent, delivered, or bounced.
If you use EmacronAI's WhatsApp OTP module, the webhook event shapes and retry behaviour are described in the documentation, and the broader product overview is at crm.emacronai.com. Check current pricing and message rates at crm.emacronai.com/pricing rather than relying on figures quoted elsewhere.
Test the failure paths, not just the happy path
The happy path takes ten minutes to build. The failure paths decide whether the integration survives real users. Cover at least these in tests:
- Expired code rejected.
- Sixth attempt rejected even with the correct code.
- Correct code accepted exactly once.
- Resend within cooldown refused.
- Webhook for an unknown message ID ignored safely.
- Numbers with and without a leading
+treated as the same user.
Use a fake store and a fake provider client so tests run without network calls. For provider behaviour itself — template approval, opt-in enforcement, delivery receipts — test against the provider's sandbox where one exists, and read the current rules on Meta's official documentation.
One more design point: keep the OTP module behind a small interface (issue, verify, on_status) so you can swap providers or add a second channel without rewriting handlers. Indian teams often need an SMS fallback for numbers not on WhatsApp, and that is much easier when the OTP logic is not tangled with one provider's SDK.
Key takeaway: A WhatsApp OTP integration is mostly state management: hash the code, expire it, count attempts, delete on success, and track delivery separately from sending. Get those five behaviours right and the provider choice becomes a detail you can change.