Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 12 min read

WhatsApp OTP in Production: Authentication Templates, Autofill, Time-to-Live and SMS Fallback

Sending a login code over WhatsApp looks like one API call. Getting it right in production is a dozen small decisions: which template button to use and on which phones it works, how long Meta should keep trying to delive

Sending a login code over WhatsApp looks like one API call. Getting it right in production is a dozen small decisions: which template button to use and on which phones it works, how long Meta should keep trying to deliver a code that expires in ten minutes, what happens when the user isn't on WhatsApp or the message never arrives, how to store the code so a database leak doesn't hand out logins, and how to stop one number being used to burn through your messaging budget.

This post covers the Meta side (authentication templates, autofill, time-to-live, pricing) and builds the server side in TypeScript: code generation, hashed storage, attempts and rate limits, a send that falls back to SMS, and single-use verification that holds up when two tabs submit the same code.

The code was run with node --experimental-strip-types and 10 tests. Meta facts are from its developer docs as of November 2026.

The template: what you can and can't control

OTPs on WhatsApp go through authentication templates, and Meta is strict about it: "Only authentication templates can be used to send a one-time passcode for identity verification." You don't write the text. The body is "Fixed, non-customizable preset text": <VERIFICATION_CODE> is your verification code. You choose two optional extras:

  • add_security_recommendation: true adds For your security, do not share this code.
  • A footer with code_expiration_minutes (1 to 90) adds This code expires in <NUM_MINUTES> minutes.

"URLs, media, and emojis are not allowed for authentication template content or parameters", and the code parameter is limited to 15 characters.

Three button types

The template's button decides how the code gets from the message into your app:

  • Copy code (otp_type: copy_code): the user taps a button and pastes. Works everywhere, needs nothing from your app.
  • One-tap autofill (one_tap): the user taps and WhatsApp hands the code to your Android app.
  • Zero-tap (zero_tap): no tap at all; your Android app receives the code automatically. It needs zero_tap_terms_accepted: true at creation, or "the template will not be created".

One-tap and zero-tap are Android only, and only if your app did a handshake with WhatsApp first; otherwise "the delivered message will display a copy code button" instead. They also need supported_apps: your app's package name and an 11-character signing-key hash, for up to 5 apps. If you use the older PendingIntent-based handshake, note Meta's deadline: "We will extend the migration deadline until January 31, 2027", after which that method is deprecated.

On iOS there's no button-level autofill, but iOS 26 added keyboard suggestions: the OS offers the code from the notification. Meta's docs say "This feature works automatically with your existing authentication templates", but "iOS only detects numeric codes of 3 to 8 digits." So keep codes numeric and 6 digits unless you have a reason not to.

Two delivery rules worth knowing before you design the flow: "authentication messages are only delivered to a user's primary WhatsApp device", and "WhatsApp disables forwarding of authentication messages." The second one is a feature: it blocks the classic "please forward me the code you just got" scam.

Sending one

For a copy-code template, the code goes into the payload twice, once for the body and once for the button, because the button copies its own parameter:

// The send payload for a copy-code authentication template: the code goes in the body
// parameter and again as the button's parameter, which is what the copy button copies.
export const otpTemplatePayload = (to: string, template: { name: string; language: string }, code: string) => ({
  messaging_product: "whatsapp",
  to,
  type: "template",
  template: {
    name: template.name,
    language: { code: template.language },
    components: [
      { type: "body", parameters: [{ type: "text", text: code }] },
      { type: "button", sub_type: "url", index: "0", parameters: [{ type: "text", text: code }] },
    ],
  },
});

Meta's docs are explicit: "Note that this value must appear twice in the payload."

Send it to a phone number. Since WhatsApp usernames arrived, many webhooks identify users by a business-scoped user ID, but "Authentication templates must be sent to a phone number. Sending them to a BSUID with recipient returns error 131062."

Time-to-live: the setting that prevents late codes

A code that arrives 20 minutes late is worse than one that never arrives: the user has already given up, and now has a code that doesn't work. Authentication templates have their own time-to-live, message_send_ttl_seconds. From Meta's TTL docs:

  • The default for authentication templates is 10 minutes, or 30 days for templates created before October 23, 2024. If yours is older than that, check it.
  • The range is 30 to 900 seconds.
  • "The system drops messages that cannot be delivered within the default or customized TTL."
  • "If you do not receive a delivered message webhook before the TTL is exceeded, assume the message was dropped."

Meta charges only for delivered messages, so a dropped code isn't billed. The design that follows: set a short TTL on the template (60 seconds works well for login), and if no delivered status arrives by then, send the code another way.

Storing the code

import { createHmac, randomInt, timingSafeEqual } from "node:crypto";

// One login attempt: what you store. Never the code itself, only its HMAC.
export type Challenge = {
  id: string;
  phone: string;
  codeHash: string;
  expiresAt: number;
  attempts: number;
  usedAt: number | null;
  wamid: string | null;
  deliveredAt: number | null;
  fallbackSentAt: number | null;
  createdAt: number;
};

export type OtpConfig = {
  pepper: string; // server secret, so a leaked table doesn't reveal codes
  digits: number;
  ttlMs: number; // keep in line with the template's code_expiration_minutes
  maxAttempts: number;
  maxSendsPerWindow: number;
  sendWindowMs: number;
  // No "delivered" by then β†’ SMS. Match it to the template's TTL (message_send_ttl_seconds), so Meta
  // has dropped the WhatsApp message by the time the SMS goes out, instead of delivering it late.
  fallbackAfterMs: number;
};

export const DEFAULTS: OtpConfig = {
  pepper: "",
  digits: 6,
  ttlMs: 10 * 60_000,
  maxAttempts: 5,
  maxSendsPerWindow: 3,
  sendWindowMs: 15 * 60_000,
  fallbackAfterMs: 60_000,
};

// Numeric, 3 to 8 digits: what iOS keyboard suggestions can autofill.
export const newCode = (digits: number): string => String(randomInt(0, 10 ** digits)).padStart(digits, "0");

export const hashCode = (code: string, challengeId: string, pepper: string): string =>
  createHmac("sha256", pepper).update(`${challengeId}:${code}`).digest("hex");

The choices:

  • Never store the code. Store an HMAC of the code, the challenge ID and a server-side secret (the "pepper"). A leaked table then reveals nothing usable, and a 6-digit code can't be brute-forced offline without the pepper.
  • randomInt for codes, not Math.random.
  • Expiry matches the template's code_expiration_minutes, so the message and the server agree on when the code dies.
  • Five attempts, then locked. A 6-digit code has a million values; unlimited guesses make it a matter of time.
  • Three sends per number per 15 minutes. Every send costs money and a code request is an unauthenticated endpoint. Rate-limit per IP and per device as well in your API layer.

Starting a challenge, with SMS fallback

export type Store = {
  recentFor: (phone: string, since: number) => Promise<Challenge[]>;
  save: (c: Challenge) => Promise<void>;
  byId: (id: string) => Promise<Challenge | null>;
  byWamid: (wamid: string) => Promise<Challenge | null>;
  // Conditional update (UPDATE ... SET used_at = ? WHERE id = ? AND used_at IS NULL): false if already used.
  markUsed: (id: string, at: number) => Promise<boolean>;
  undeliveredSince: (before: number) => Promise<Challenge[]>;
};

export type Senders = {
  whatsapp: (phone: string, code: string) => Promise<{ wamid: string } | { error: string }>;
  sms: (phone: string, code: string) => Promise<void>;
};

export class TooManySends extends Error {}

export const startChallenge = async (
  phone: string,
  deps: { store: Store; senders: Senders; cfg: OtpConfig; now: () => number; newId: () => string },
): Promise<{ challengeId: string; channel: "whatsapp" | "sms" }> => {
  const { store, senders, cfg, now } = deps;
  const t = now();
  const recent = await store.recentFor(phone, t - cfg.sendWindowMs);
  if (recent.length >= cfg.maxSendsPerWindow) throw new TooManySends("Too many codes requested. Try again later.");

  // A new code replaces any open one: only the latest code for a number can be used.
  for (const old of recent) if (!old.usedAt && old.expiresAt > t) await store.save({ ...old, expiresAt: t });

  const id = deps.newId();
  const code = newCode(cfg.digits);
  const challenge: Challenge = {
    id, phone, codeHash: hashCode(code, id, cfg.pepper), expiresAt: t + cfg.ttlMs, attempts: 0,
    usedAt: null, wamid: null, deliveredAt: null, fallbackSentAt: null, createdAt: t,
  };
  const sent = await senders.whatsapp(phone, code);
  if ("error" in sent) {
    // Not on WhatsApp, template paused, account problem: go straight to SMS.
    await senders.sms(phone, code);
    await store.save({ ...challenge, fallbackSentAt: t });
    return { challengeId: id, channel: "sms" };
  }
  await store.save({ ...challenge, wamid: sent.wamid });
  return { challengeId: id, channel: "whatsapp" };
};

What it handles:

  • A new request cancels the previous code. Only the latest code for a number works, so a user who requested twice can't be confused by the first one.
  • If WhatsApp refuses the send (the number isn't on WhatsApp, the template is paused, the account has a problem), the code goes by SMS immediately. The user waits for nothing.
  • Delivery is tracked by wamid. The send stores the message ID, and status webhooks mark the challenge delivered.

Then a small job, run every few seconds, sends the SMS fallback for codes WhatsApp hasn't delivered by the TTL:

// Status webhooks: "delivered" (or "read") means the code reached the phone.
export const onStatus = async (store: Store, wamid: string, status: string, at: number) => {
  const c = await store.byWamid(wamid);
  if (!c || c.deliveredAt) return;
  if (status === "delivered" || status === "read") await store.save({ ...c, deliveredAt: at });
};

// Run every few seconds: codes that WhatsApp hasn't delivered in time go out by SMS once.
// The SMS carries a fresh code, because the WhatsApp one may still arrive late.
export const sendFallbacks = async (deps: { store: Store; senders: Senders; cfg: OtpConfig; now: () => number }) => {
  const t = deps.now();
  const due = await deps.store.undeliveredSince(t - deps.cfg.fallbackAfterMs);
  let sent = 0;
  for (const c of due) {
    if (c.usedAt || c.deliveredAt || c.fallbackSentAt || c.expiresAt <= t) continue;
    const code = newCode(deps.cfg.digits);
    await deps.store.save({ ...c, codeHash: hashCode(code, c.id, deps.cfg.pepper), fallbackSentAt: t });
    await deps.senders.sms(c.phone, code);
    sent++;
  }
  return sent;
};

The fallback SMS carries a fresh code and replaces the stored hash, which means the WhatsApp code stops working. That's deliberate: we never stored the original code, so we can't resend it, and with the template's TTL equal to the fallback delay, Meta has already dropped the undelivered WhatsApp message. The user gets exactly one working code.

Verifying: once, and only once

export type VerifyResult = "ok" | "wrong" | "expired" | "locked" | "used";

export const verify = async (store: Store, challengeId: string, code: string, cfg: OtpConfig, now: number): Promise<VerifyResult> => {
  const c = await store.byId(challengeId);
  if (!c) return "expired";
  if (c.usedAt) return "used";
  if (c.expiresAt <= now) return "expired";
  if (c.attempts >= cfg.maxAttempts) return "locked";
  const given = Buffer.from(hashCode(code.trim(), c.id, cfg.pepper));
  const expected = Buffer.from(c.codeHash);
  if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
    await store.save({ ...c, attempts: c.attempts + 1 });
    return c.attempts + 1 >= cfg.maxAttempts ? "locked" : "wrong";
  }
  // Two tabs submitting the same code at once: only one of them may log in.
  return (await store.markUsed(c.id, now)) ? "ok" : "used";
};

The detail most implementations miss is the last line. Two browser tabs, or a double-tapped button, can submit the same correct code at the same moment. Reading the challenge, checking usedAt, then writing it is a race; both requests pass the check. markUsed is a conditional update (UPDATE … SET used_at = ? WHERE id = ? AND used_at IS NULL), and only the request that actually changed the row logs in. The test for this fires two verifications in parallel and expects exactly one ok.

Comparisons use timingSafeEqual on the hashes, so response timing doesn't leak how close a guess was.

What the user should see

The server logic only works if the screen matches it:

  • Say where the code went. "We sent a code to your WhatsApp" or "We sent a code by SMS", from the channel the start call returns. A user staring at their SMS inbox while the code sits in WhatsApp is the most common support ticket for OTP over WhatsApp.
  • A resend button with a countdown, disabled until the fallback delay has passed. It maps to a new challenge, which cancels the old code, and the server's three-per-15-minutes limit backs it up.
  • A distinct message for each verification result. "Wrong code, try again", "This code has expired, request a new one", "Too many attempts, request a new code". verify returns exactly those states so the UI doesn't have to guess.
  • A one-field input that accepts paste, and autocomplete="one-time-code" on the web, so copy code and keyboard suggestions both land in the right place.

Meta is also rolling out an "I didn't request a code" button on copy-code messages. It's "currently in beta and is being rolled out incrementally", and a tap arrives as a button webhook with the payload DID_NOT_REQUEST_CODE. When you get one, cancel that challenge and treat the number as a possible takeover target: someone typed it into your login form who wasn't its owner. Logging these per IP is a cheap way to spot people trying many numbers.

What it costs, especially in India

Authentication messages are priced per delivered message, by the user's country. Meta's India list rates as of November 2026: β‚Ή0.115 per authentication message, the same as utility, with volume tiers that go lower at high volume.

There's one more category to know about: authentication-international. It exists in 18 markets (India's rate started in July 2024). A business becomes eligible when it sends more than 750,000 messages outside customer service windows, in a moving 30 days, to unique users in those markets combined. Meta then sets its start time 30 days out for each country, and from then on authentication messages to users in a market other than its home country cost the international rate: β‚Ή2.4971 per message in India. Meta says "eligibility is permanent", and "You will always be charged the domestic rate for your primary business location." An Indian business sending OTPs to Indian users pays the domestic rate; a foreign app with a big Indian user base may not. You can check with GET /{WABA_ID}?fields=auth_international_rate_eligibility.

If you read pricing from status webhooks, match both spellings: Meta's reference lists the category as authentication-international in one place and authentication_international in another.

What WAPGROWAI does today, and what it doesn't

  • We create copy-code authentication templates with the security line and code expiry. We leave the button label out, so Meta fills in its own localised default ("Copy code" in English).
  • We don't build one-tap or zero-tap templates. Copy code only, so Android users don't get autofill through us.
  • We don't expose the template TTL in our builder, so our authentication templates use Meta's default (10 minutes).
  • We don't run an OTP service. No code storage, attempts, rate limits or SMS fallback: a business sending codes through our API does that on its side, ideally like this post.

One thing we learned the hard way: Meta can block a WhatsApp account from creating authentication templates at all, with error code 10 and subcode 2388185, while marketing and utility templates still work. It fails in WhatsApp Manager too, so it's not a payload problem. Check for it before you debug your template JSON.

Checklist

  • Use an authentication template; don't send codes in utility or marketing templates.
  • Add the security line and a code_expiration_minutes that matches your server-side expiry.
  • Copy code works everywhere; one-tap and zero-tap need Android, a handshake and supported_apps.
  • Keep codes numeric, 6 digits, so iOS keyboard suggestions can fill them.
  • Put the code in the payload twice: body and button.
  • Send to a phone number, never a BSUID.
  • Set the template TTL short (around 60 seconds), and fall back to SMS when no delivered status arrives by then.
  • Store an HMAC of the code, never the code.
  • Limit attempts per code and sends per number; rate-limit the request endpoint too.
  • Make "mark used" a conditional update, so a code logs in exactly once.
  • Tell the user which channel the code went to, and handle DID_NOT_REQUEST_CODE taps as a fraud signal.
  • Check auth_international_rate_eligibility if you're based outside a market you send codes to.

WAPGROWAI is built by DI Solutions, a custom software and AI development company. This series covers what we've learned building WAPGROWAI on the WhatsApp Cloud API. Related: Why WhatsApp template sends fail silently and WhatsApp usernames will break your phone-keyed contacts.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.