How to Add WhatsApp Notifications to a Web App
· 27 min read
Letting users get your app's notifications on WhatsApp sounds like a single API call. In practice, the API call is the easy part. Most of the work is proving that a phone number belongs to the person who typed it, and then only messaging that number in the ways Meta allows. I recently built this feature for a web app, and almost every design decision came from those rules rather than from the code.
This guide walks through the whole feature, from the settings screen to the server. We'll cover:
- How WhatsApp's business platform works, and the rules that shape the design.
- What the browser, your server and Meta are each responsible for.
- The flow for connecting, verifying, managing and disconnecting a number.
- The implementation, with code for each step.
- The edge cases that only show up once real people use it.
You don't need any WhatsApp experience to follow along. The front-end examples use Vue 3 (inside Nuxt), but the ideas carry over to any framework. The server examples use Node.js with Express and Postgres, and since they're plain HTTP calls, the same requests work from any language.
There's one rule you need to understand before anything else: a business can only send free-form messages to someone after that person has messaged the business. Every other message has to use a template that Meta approved in advance, and it can only go to someone who opted in.
To send messages from code, you need four things, all created in Meta's developer dashboard:
- A Meta app. It holds your credentials, including the app secret that Meta uses to sign the webhooks it sends you.
- A WhatsApp Business Account (WABA). It owns your templates and phone numbers. You create templates against its ID.
- A business phone number. This is the number your messages come from. Each one has a phone number ID, which is what you send messages through.
- An access token. In production, use a long-lived token for a system user (a non-human account in Meta Business Manager). Your personal developer token expires, so it isn't suitable.
Your code talks to all of this through the Cloud API, which is a set of HTTPS endpoints on graph.facebook.com hosted by Meta. There's no SDK to install and no Meta server for you to run.
When a user sends your business a message, a 24-hour customer service window opens, and inside it you can reply with any text. Outside that window, you can only send template messages. These are pre-written messages with placeholders like {{1}}, and Meta reviews each one before you're allowed to use it.
Notifications are business-initiated by nature. Your app decides when to message someone, usually long after they last wrote to you, if they ever did. So you should plan on almost every message being a template.
| Category |
What it's for |
Role in this feature |
Billing |
| Authentication |
One-time codes and nothing else |
Verifying the user's number |
Charged per delivered message, even inside an open window |
| Utility |
Updates about something the user did or asked for |
The notifications themselves |
Charged per delivered message, but free inside an open customer service window |
| Marketing |
Promotions, offers and re-engagement |
Optional, and needs separate consent |
Charged per delivered message |
Since July 1, 2025, Meta has charged per delivered template message, at a rate that depends on the template's category and the recipient's country (Meta's pricing docs). Meta can also re-categorise a template it thinks is mislabelled, so a "utility" message that reads like an advert may end up billed as marketing.
Meta requires a person's opt-in before you send them business-initiated messages. The opt-in has to say that the person agrees to receive WhatsApp messages from you, and it has to name your business (Get opt-in for WhatsApp). Meta also recommends a separate opt-in for each kind of message, with a clear way to opt out of each one.
It also affects you directly. People who receive messages they didn't expect tend to block or report the sender, and those reports count against your number's quality rating.
That's why the design in this guide is a "Connect WhatsApp" option in the user's notification settings, followed by the user proving they own the number. The user picks the channel themselves, and you get a record of when they did.
The browser only talks to your API, and only your server talks to Meta. The access token, the app secret and the hashed verification codes never leave the server.
How the browser, your server, Meta and the user's phone connect
Two flows share this setup:
- Verification. The browser asks your server for a code. The server generates it, stores a hash of it and sends it through the Cloud API as an authentication template. The user types the code back into the browser, and the server compares the hashes.
- Notifications. When something happens in your app, a worker picks the event off a queue and sends a utility template to the user's stored WhatsApp ID.
For both flows, delivery results come back to your server through a signed webhook. That's how you find out that a code never arrived, or that a number has stopped working.
The linking flow does three jobs at once. It collects consent, proves the user controls the number, and proves the number can receive WhatsApp messages. The third job is the reason to send the verification code over WhatsApp instead of SMS: if the code arrives, your notifications will too.
The whole feature fits in one card on the notification settings page and three small modals:
- The settings card. It shows either "Not connected" with a Connect WhatsApp button, or "Connected as +44 ******0123" with Manage connection and Change number. The line under the title describes what the user will receive, so the card doubles as the opt-in.
- Connect modal, step 1. A phone input with a country code picker and a Send code button. The copy tells the user what happens next: "Enter your WhatsApp number and we'll send a code to it."
- Connect modal, step 2. Six single-digit boxes, a countdown before the code can be resent, a Change number link back to step 1, and Verify.
- Manage modal. The number, its status and the date it was connected, plus a Disconnect button. Disconnecting asks for confirmation and states the consequence: "You'll stop getting updates on WhatsApp until you reconnect."
Change number reuses the connect modal instead of getting its own flow. Changing a number is really the same as connecting a new one, because the new number has to be verified before it replaces the old one.
- Collect the country code separately. A country picker plus a local number avoids the most common input mistake, which is a missing or wrong international prefix. The server still normalises the result to E.164 (for example,
+447700900123), the format WhatsApp expects.
- Mask the number wherever it's shown in passing. Show the country code and the last four digits. Keep the full number for the manage modal, which the user opens on purpose.
- Match the countdown to the code's lifetime. If a code expires after five minutes, Resend should unlock after five minutes. A user who resends early cancels a code that may still be on its way.
- Support pasting. Most people copy the code from WhatsApp, often with the template's Copy code button, so one paste should fill all six boxes.
- Use a bottom sheet on phones and a dialog on desktop. On a phone, the user switches between WhatsApp and your app, and a bottom sheet keeps the code boxes within reach of their thumb.
- Treat the server as the source of truth. The card should always show the connection state from your API, never a flag stored in the browser. Otherwise, a second device, or a number that was disconnected because messages kept failing, will show the wrong state.
The server owns everything that touches Meta. The browser only calls four endpoints on your own API: read the status, send a code, confirm a code, and disconnect.
The examples use Express, Postgres and the fetch built into Node 20. Keep these values in environment variables on the server, never in front-end code:
GRAPH_VERSION=vXX.X
WABA_ID=...
WHATSAPP_PHONE_NUMBER_ID=...
WHATSAPP_TOKEN=...
META_APP_SECRET=...
WHATSAPP_VERIFY_TOKEN=...
OTP_PEPPER=...
Authentication templates have fixed wording that you can't change: "{{1}} is your verification code." You only choose the extras, which are a security line ("For your security, do not share this code."), an expiry footer and the button. Copy code is the button type that works on every platform. URLs, media and emoji aren't allowed (Copy code authentication templates).
curl -X POST "https://graph.facebook.com/$GRAPH_VERSION/$WABA_ID/message_templates" \
-H "Authorization: Bearer $WHATSAPP_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "verify_number",
"language": "en_US",
"category": "authentication",
"message_send_ttl_seconds": 300,
"components": [
{ "type": "body", "add_security_recommendation": true },
{ "type": "footer", "code_expiration_minutes": 5 },
{ "type": "buttons", "buttons": [
{ "type": "otp", "otp_type": "copy_code", "text": "Copy code" }
]}
]
}'
message_send_ttl_seconds tells WhatsApp to drop the message if it can't be delivered within five minutes. A code that shows up after it has already expired only confuses people.
Next, create one utility template for each kind of notification you send. Specific, transactional templates are the ones that get approved. A catch-all template like "You have an update: {{1}}" tends to be rejected or re-categorised as marketing. You also have to provide a sample value for every placeholder:
{
"name": "payment_received",
"language": "en_US",
"category": "utility",
"components": [
{
"type": "body",
"text": "We received your payment of {{1}} for order {{2}}. You can view the receipt in your account.",
"example": { "body_text": [["$42.00", "#4821"]] }
},
{ "type": "footer", "text": "Turn off WhatsApp updates in Settings anytime." }
]
}
New templates start as PENDING and can't be used until they're APPROVED, so create them well before you launch.
A verification is short-lived and holds a secret. A link is long-lived and holds the user's consent. If you keep them in separate tables, a half-finished verification can never be mistaken for a connected number:
CREATE TABLE whatsapp_links (
user_id uuid PRIMARY KEY REFERENCES users(id),
phone_e164 text NOT NULL,
wa_id text NOT NULL,
status text NOT NULL,
consecutive_failures int NOT NULL DEFAULT 0,
consented_at timestamptz NOT NULL,
verified_at timestamptz NOT NULL,
disconnected_at timestamptz
);
CREATE TABLE whatsapp_verifications (
id uuid PRIMARY KEY,
user_id uuid NOT NULL UNIQUE REFERENCES users(id),
phone_e164 text NOT NULL,
code_hash text NOT NULL,
attempts int NOT NULL DEFAULT 0,
expires_at timestamptz NOT NULL,
message_id text,
wa_id text,
failed_code int
);
Every message, whether it's a verification code or a notification, goes through the same endpoint, so one function covers both:
const GRAPH = `https://graph.facebook.com/${process.env.GRAPH_VERSION}`
export async function sendTemplate (to, name, components = [], lang = 'en_US') {
const res = await fetch(`${GRAPH}/${process.env.WHATSAPP_PHONE_NUMBER_ID}/messages`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.WHATSAPP_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
messaging_product: 'whatsapp',
recipient_type: 'individual',
to,
type: 'template',
template: { name, language: { code: lang }, components }
})
})
const body = await res.json()
if (!res.ok) {
const err = new Error(body.error?.message ?? 'WhatsApp send failed')
err.code = body.error?.code
throw err
}
return { waId: body.contacts?.[0]?.wa_id, messageId: body.messages?.[0]?.id }
}
export function sendVerificationCode (to, code) {
return sendTemplate(to, 'verify_number', [
{ type: 'body', parameters: [{ type: 'text', text: code }] },
{ type: 'button', sub_type: 'url', index: '0', parameters: [{ type: 'text', text: code }] }
])
}
Notice that the code is sent twice, once for the body and once for the button. If you leave out the button parameter, the send fails. Codes can be up to 15 characters long.
import crypto from 'node:crypto'
import { parsePhoneNumberFromString } from 'libphonenumber-js'
import { sendVerificationCode } from './whatsapp.js'
const CODE_TTL_SECONDS = 300
const hashCode = (code, verificationId) =>
crypto.createHmac('sha256', process.env.OTP_PEPPER)
.update(`${verificationId}:${code}`)
.digest('hex')
app.post('/me/whatsapp/verification', requireUser, limitCodeRequests, async (req, res) => {
const phone = parsePhoneNumberFromString(String(req.body.phone ?? ''))
if (!phone?.isValid()) {
return res.status(422).json({ message: 'Enter a valid phone number.' })
}
const e164 = phone.number
const id = crypto.randomUUID()
const code = crypto.randomInt(0, 1_000_000).toString().padStart(6, '0')
await db.query('DELETE FROM whatsapp_verifications WHERE user_id = $1', [req.user.id])
await db.query(
`INSERT INTO whatsapp_verifications (id, user_id, phone_e164, code_hash, expires_at)
VALUES ($1, $2, $3, $4, now() + make_interval(secs => $5))`,
[id, req.user.id, e164, hashCode(code, id), CODE_TTL_SECONDS]
)
try {
const { messageId, waId } = await sendVerificationCode(e164, code)
await db.query(
'UPDATE whatsapp_verifications SET message_id = $1, wa_id = $2 WHERE id = $3',
[messageId, waId, id]
)
} catch (err) {
await db.query('DELETE FROM whatsapp_verifications WHERE id = $1', [id])
return res.status(502).json({ message: 'We couldn’t send a code to that number. Check it and try again.' })
}
res.status(202).json({ expiresInSeconds: CODE_TTL_SECONDS })
})
A few details in this handler are worth pointing out:
- The code comes from
crypto.randomInt, not Math.random(), because it's a secret.
- The database stores an HMAC of the code, combined with the verification ID. If a row ever leaks, nobody can check it against all one million six-digit codes offline without also having the pepper.
limitCodeRequests stands in for whatever rate limiter you use. Limit by user and by destination number, for example five codes per user per hour and three per number per hour. Authentication messages cost money, and an endpoint without limits lets anyone run up your bill.
const MAX_ATTEMPTS = 5
app.post('/me/whatsapp/verification/confirm', requireUser, async (req, res) => {
const { rows: [v] } = await db.query(
'SELECT * FROM whatsapp_verifications WHERE user_id = $1', [req.user.id]
)
if (!v || v.expires_at < new Date()) {
return res.status(410).json({ message: 'That code has expired. Request a new one.' })
}
const { rowCount } = await db.query(
`UPDATE whatsapp_verifications SET attempts = attempts + 1
WHERE id = $1 AND attempts < $2`, [v.id, MAX_ATTEMPTS]
)
if (rowCount === 0) {
return res.status(429).json({ message: 'Too many attempts. Request a new code.' })
}
const expected = Buffer.from(v.code_hash, 'hex')
const actual = Buffer.from(hashCode(String(req.body.code ?? ''), v.id), 'hex')
if (!crypto.timingSafeEqual(expected, actual)) {
return res.status(422).json({ message: 'That code isn’t right. Check it and try again.' })
}
const { rows: [link] } = await db.query(
`INSERT INTO whatsapp_links (user_id, phone_e164, wa_id, status, consented_at, verified_at)
VALUES ($1, $2, $3, 'active', now(), now())
ON CONFLICT (user_id) DO UPDATE SET
phone_e164 = EXCLUDED.phone_e164, wa_id = EXCLUDED.wa_id, status = 'active',
consecutive_failures = 0, consented_at = now(), verified_at = now(), disconnected_at = NULL
RETURNING phone_e164, status, verified_at`,
[req.user.id, v.phone_e164, v.wa_id ?? v.phone_e164.slice(1)]
)
await db.query('DELETE FROM whatsapp_verifications WHERE id = $1', [v.id])
res.json({ connected: true, phone: link.phone_e164, status: link.status, connectedSince: link.verified_at })
})
The upsert at the end is what makes Change number work without any extra code. Verifying a new number overwrites the old link, resets its failure count and records fresh consent in a single statement.
app.get('/me/whatsapp', requireUser, async (req, res) => {
const { rows: [link] } = await db.query(
`SELECT phone_e164, status, verified_at FROM whatsapp_links
WHERE user_id = $1 AND status <> 'disconnected'`, [req.user.id]
)
res.json(link
? { connected: true, phone: link.phone_e164, status: link.status, connectedSince: link.verified_at }
: { connected: false })
})
app.delete('/me/whatsapp', requireUser, async (req, res) => {
await db.query(
`UPDATE whatsapp_links SET status = 'disconnected', disconnected_at = now()
WHERE user_id = $1`, [req.user.id]
)
res.status(204).end()
})
Disconnecting updates the row instead of deleting it. That way you keep a record of when consent was given and when it was withdrawn, and the code that sends messages only has to check one thing: status = 'active'.
A small service wraps the four endpoints. This one uses Nuxt's $fetch, but any HTTP client works:
export interface WhatsappStatus {
connected: boolean
phone?: string
status?: 'active' | 'failing'
connectedSince?: string
}
export const WHATSAPP_SERVICE = {
STATUS: () => $fetch<WhatsappStatus>('/api/me/whatsapp'),
SEND_CODE: (phone: string) =>
$fetch<{ expiresInSeconds: number }>('/api/me/whatsapp/verification', { method: 'POST', body: { phone } }),
VERIFY_CODE: (code: string) =>
$fetch<WhatsappStatus>('/api/me/whatsapp/verification/confirm', { method: 'POST', body: { code } }),
DISCONNECT: () => $fetch('/api/me/whatsapp', { method: 'DELETE' })
}
The connect modal moves between two steps, phone and then otp. Notice that the countdown gets its length from the server's response, not from a number hard-coded in the browser:
const step = ref<'phone' | 'otp'>('phone')
const dialCode = ref('')
const phoneNumber = ref('')
const otp = ref<string[]>(Array(6).fill(''))
const boxes = ref<HTMLInputElement[]>([])
const timeLeft = ref(0)
const loading = ref(false)
const error = ref('')
const fullPhone = computed(() => `${dialCode.value}${phoneNumber.value}`.replace(/[^\d+]/g, ''))
let timer: ReturnType<typeof setInterval> | undefined
function startCountdown (seconds: number) {
clearInterval(timer)
timeLeft.value = seconds
timer = setInterval(() => { if (--timeLeft.value <= 0) clearInterval(timer) }, 1000)
}
onBeforeUnmount(() => clearInterval(timer))
async function sendCode () {
loading.value = true
error.value = ''
try {
const { expiresInSeconds } = await WHATSAPP_SERVICE.SEND_CODE(fullPhone.value)
otp.value = Array(6).fill('')
step.value = 'otp'
startCountdown(expiresInSeconds)
await nextTick()
boxes.value[0]?.focus()
} catch (e: any) {
error.value = e?.data?.message ?? 'Something went wrong. Try again.'
} finally {
loading.value = false
}
}
async function verify () {
if (loading.value || otp.value.join('').length < 6) return
loading.value = true
error.value = ''
try {
emit('connected', await WHATSAPP_SERVICE.VERIFY_CODE(otp.value.join('')))
} catch (e: any) {
error.value = e?.data?.message ?? 'Something went wrong. Try again.'
otp.value = Array(6).fill('')
boxes.value[0]?.focus()
} finally {
loading.value = false
}
}
function onDigit (i: number) {
otp.value[i] = (otp.value[i] ?? '').replace(/\D/g, '').slice(-1)
if (otp.value[i] && i < 5) boxes.value[i + 1]?.focus()
if (otp.value.every(Boolean)) verify()
}
function onBackspace (i: number) {
if (!otp.value[i] && i > 0) boxes.value[i - 1]?.focus()
}
function onPaste (e: ClipboardEvent) {
const digits = (e.clipboardData?.getData('text') ?? '').replace(/\D/g, '').slice(0, 6)
if (!digits) return
e.preventDefault()
digits.split('').forEach((d, i) => { otp.value[i] = d })
boxes.value[Math.min(digits.length, 5)]?.focus()
if (digits.length === 6) verify()
}
The six boxes are plain inputs, and three attributes handle most of the accessibility and mobile behaviour:
<input
v-for="(_, i) in otp"
:key="i"
:ref="el => (boxes[i] = el as HTMLInputElement)"
v-model="otp[i]"
inputmode="numeric"
autocomplete="one-time-code"
maxlength="1"
:aria-label="`Digit ${i + 1} of 6`"
@input="onDigit(i)"
@keydown.backspace="onBackspace(i)"
@paste="onPaste"
>
inputmode="numeric" opens the number pad on phones.
autocomplete="one-time-code" lets the operating system offer the code from the keyboard, where it supports that. According to Meta, iOS 26 and later suggest codes from WhatsApp authentication templates by default (Authentication templates).
- The paste handler is on every box, not just the first, so pasting works wherever the cursor is.
The settings card loads its state from the server when it mounts, and shows a masked version of the number. The API returns the number in E.164, so the mask uses libphonenumber-js to split off the country code:
import { parsePhoneNumber } from 'libphonenumber-js'
const wa = ref<WhatsappStatus>({ connected: false })
onMounted(async () => { wa.value = await WHATSAPP_SERVICE.STATUS() })
function onConnected (status: WhatsappStatus) {
wa.value = status
toast.success('WhatsApp connected')
}
function maskPhone (e164: string): string {
const { countryCallingCode, nationalNumber } = parsePhoneNumber(e164)
const hidden = '*'.repeat(Math.max(0, nationalNumber.length - 4))
return `+${countryCallingCode} ${hidden}${nationalNumber.slice(-4)}`
}
When wa.status is 'failing', say so on the card, for example: "We couldn't reach this number. Reconnect to keep getting updates." That way the user knows they need to do something, instead of wondering why the messages stopped.
Don't call the Cloud API inside the request that triggered the event. If you put the message on a queue instead, a slow or failing call to Meta won't fail the user's action, and retries all happen in one place. This example uses BullMQ:
import { Queue, Worker } from 'bullmq'
import { sendTemplate } from './whatsapp.js'
const whatsappQueue = new Queue('whatsapp')
export async function notifyOnWhatsApp (userId, template, params) {
const { rows: [link] } = await db.query(
`SELECT wa_id FROM whatsapp_links WHERE user_id = $1 AND status = 'active'`, [userId]
)
if (!link) return
await whatsappQueue.add('send', { to: link.wa_id, template, params }, {
attempts: 5,
backoff: { type: 'exponential', delay: 10_000 }
})
}
new Worker('whatsapp', async (job) => {
const { to, template, params } = job.data
await sendTemplate(to, template, [
{ type: 'body', parameters: params.map(text => ({ type: 'text', text: String(text) })) }
])
})
await notifyOnWhatsApp(order.userId, 'payment_received', ['$42.00', '#4821'])
notifyOnWhatsApp is also the right place to check the user's preferences for each category of notification. Only sending the categories a user has turned on is how you follow Meta's recommendation of a separate opt-in for each kind of message.
A 200 response from the send endpoint only means Meta accepted the message. Whether it was actually delivered arrives later, at your webhook. Register the webhook URL in the app dashboard and subscribe to the messages field. The URL has to use HTTPS with a valid certificate, because self-signed certificates are rejected.
When you register the URL, Meta sends a single GET request with a challenge. If the verify token matches, echo the challenge back:
app.get('/webhooks/whatsapp', (req, res) => {
const ok = req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === process.env.WHATSAPP_VERIFY_TOKEN
return ok ? res.status(200).send(req.query['hub.challenge']) : res.sendStatus(403)
})
Every POST after that is signed. The X-Hub-Signature-256 header is sha256= followed by an HMAC-SHA256 of the raw request body, keyed with your app secret (Create a webhook endpoint). You have to hash the raw bytes. If you hash JSON that a body parser has already parsed and turned back into a string, the signature won't match. In Express, that means registering this route before any global app.use(express.json()), so the JSON parser doesn't consume the body first:
const webhookQueue = new Queue('whatsapp-webhooks')
app.post('/webhooks/whatsapp', express.raw({ type: 'application/json' }), async (req, res) => {
const received = Buffer.from(req.get('X-Hub-Signature-256') ?? '')
const expected = Buffer.from('sha256=' +
crypto.createHmac('sha256', process.env.META_APP_SECRET).update(req.body).digest('hex'))
if (received.length !== expected.length || !crypto.timingSafeEqual(received, expected)) {
return res.sendStatus(401)
}
await webhookQueue.add('event', JSON.parse(req.body.toString('utf8')))
res.sendStatus(200)
})
Meta retries failed deliveries for up to seven days and can batch up to 1,000 updates into one request. So the worker has to expect duplicates, and more than one event per request:
new Worker('whatsapp-webhooks', async ({ data }) => {
for (const entry of data.entry ?? []) {
for (const change of entry.changes ?? []) {
if (change.field !== 'messages') continue
for (const s of change.value.statuses ?? []) await handleStatus(s)
for (const m of change.value.messages ?? []) await handleInbound(m)
}
}
})
async function handleStatus (s) {
if (!(await markSeen(`${s.id}:${s.status}`))) return
if (s.status === 'delivered' || s.status === 'read') {
await db.query('UPDATE whatsapp_links SET consecutive_failures = 0 WHERE wa_id = $1', [s.recipient_id])
return
}
if (s.status !== 'failed') return
const code = s.errors?.[0]?.code
await db.query('UPDATE whatsapp_verifications SET failed_code = $1 WHERE message_id = $2', [code, s.id])
await db.query(
`UPDATE whatsapp_links
SET consecutive_failures = consecutive_failures + 1,
status = CASE WHEN consecutive_failures + 1 >= 3 THEN 'failing' ELSE status END
WHERE wa_id = $1 AND status = 'active'`, [s.recipient_id]
)
}
async function handleInbound (m) {
if (m.type === 'button' && m.button?.payload === 'DID_NOT_REQUEST_CODE') {
await db.query('DELETE FROM whatsapp_verifications WHERE wa_id = $1', [m.from])
await logSecurityEvent('whatsapp_code_not_requested', { waId: m.from })
return
}
if (m.type === 'text' && /^\s*stop\s*$/i.test(m.text?.body ?? '')) {
await db.query(
`UPDATE whatsapp_links SET status = 'disconnected', disconnected_at = now() WHERE wa_id = $1`, [m.from]
)
}
}
markSeen() is a small helper that records each event key and returns false if it has already seen it. A Redis SET key 1 NX EX 604800 works well for this, since its seven-day expiry matches how long Meta keeps retrying.
The I didn't request a code button is a beta feature that Meta is rolling out gradually. Handling it only takes a few lines, and it's the clearest signal you'll get that someone entered a number that isn't theirs. Meta's status webhook reference also notes that some webhooks may carry a business-scoped user ID instead of a phone number, so match events on the IDs you stored, and log any event you can't match.
You can get the happy path working fairly quickly. The cases below take longer, and none of them show up in a demo.
If you send a message to a number that isn't on WhatsApp, the API still returns 200 and a message ID. The failure shows up a few seconds later as a failed status webhook, usually with error 131026, "Message undeliverable". That error covers several causes: the number isn't on WhatsApp, the recipient's app is out of date, or they haven't accepted WhatsApp's latest terms (Meta error codes).
If you don't handle this, the user waits five minutes for a code that's never coming. The webhook handler in Step 9 already records failed_code on the verification. Have the OTP step poll a small status endpoint every few seconds, and when it sees a failure, tell the user: "We couldn't deliver a code to this number. Check that it's the number you use for WhatsApp."
Authentication messages are only delivered to the user's primary device. On linked devices, such as WhatsApp Web and the desktop app, they show up masked. Meta enforces this for every Cloud API sender, and you can't turn it off. A user connecting from a laptop with WhatsApp Web open will look there first and see nothing, so add one line to the OTP step: "Check WhatsApp on your phone."
WhatsApp's one-tap and zero-tap code templates only work on Android, and only with a native Android app. In a web app, the copy-code button is what you have. On iOS, keyboard suggestions for these codes need iOS 26 or later. Everyone else copies the code and pastes it, which is why the paste handler in Step 7 matters more than the boxes that move focus automatically.
The send response includes contacts[0].wa_id, which is WhatsApp's own ID for the recipient. In some countries, it doesn't exactly match the number the user typed. Store wa_id next to the E.164 number, send notifications to wa_id, and match status webhooks against it.
Template approval happens asynchronously, so it's possible to ship code for a notification before its template is approved. Meta can also re-categorise a template after approving it, and each language is a separate template that needs its own approval.
I'd treat templates the way you treat database migrations. Keep their definitions in the repository and create them with a script. Then, when the code refers to a template that isn't approved, either fail the deploy or skip the notification and log it.
For a brief moment, the code sits in plain text in the body of the outgoing request. HTTP client debug logging, request-body logging in an API gateway, or an error tracker that captures request payloads will all store it. Redact the template.components field anywhere you log outgoing Cloud API requests.
Build the screens against a stub service that resolves after a short delay. That lets you design every state, including loading, a wrong code, an expired code and a failed delivery, before the backend exists. Then put the real client behind the same interface and switch between the two with an environment variable.
For end-to-end tests, Meta gives you a test business number, but it can only message a short list of recipient numbers that you add in the dashboard. Add your team's phones to that list early.
Once consent, verification and failure handling are right, sending the messages themselves is the simple part. Before you launch, check that:
- The authentication template and every utility template are approved, in every language you send.
- Production uses a system user token, not a personal developer token.
- Tokens, the app secret and the code pepper live only on the server.
- Phone numbers are normalised to E.164 on the server, and
wa_id is stored.
- Codes come from a secure random source, are stored hashed, expire, and allow a limited number of attempts.
- Code requests are rate-limited per user and per destination number.
- The countdown in the UI uses the expiry time the server returns.
- The OTP step shows delivery failures (131026) instead of waiting out the timer.
- The webhook verifies
X-Hub-Signature-256 against the raw body, saves events before returning 200, and ignores duplicates.
- Repeated delivery failures set the link to
failing, and the settings card shows it.
- Disconnecting, replying "stop" and tapping I didn't request a code all stop messages.
- Notifications go through a queue and respect per-category preferences.
- Codes never appear in logs.