A static WhatsApp Flow is a form that lives entirely on the customer's phone: screens, fields, a submit button, and one message back to you at the end. That covers most lead forms. It stops covering them the moment a screen needs live data: which batches still have seats, which time slots are free, whether this coupon is valid. Then the Flow has to call your server between screens, and that server has rules that most HTTP endpoints don't: every request is encrypted to your key, every response must be encrypted back, Meta pings it to check it's alive, and if it's slow or failing for long enough, Meta can throttle or block the Flow for every customer.
This post builds that endpoint in TypeScript for a real use case, a demo-class booking form for a coaching institute: pick a course, see the batches that still have seats, enter the student's name, book. It covers the encryption, the request actions, the HTTP status codes Meta acts on, and the health monitoring. In an earlier post on shipping WhatsApp Flows we said we ship static Flows only; this is the part we'd build next.
The code uses only node:crypto, and was run with node --experimental-strip-types and 11 tests, including a fake WhatsApp client that encrypts requests the way the real one does. Meta facts are from the Flows docs as of November 2026.
How a data exchange works
- You send a Flow message (or a template with a Flow button) with a
flow_tokenyou generated. - The customer opens it. If the first screen needs data, the client sends your endpoint an
INITrequest. - On each Next that's wired to
data_exchange, the client sends the screen's form values; you answer with the next screen and its data, or an error to show on the current screen. - On the last screen, you answer with the reserved
SUCCESSscreen. The Flow closes, and a completion message with yourparamsarrives at your webhook.
Between those, the client may send BACK (if the screen asks for a refresh), and Meta sends ping health checks on its own schedule.
For the booking form, the Flow JSON has two screens: COURSE, with a dropdown whose options come from data.courses, and BATCH, with a dropdown fed by data.batches and a text field for the student's name. Each screen's footer button runs data_exchange with the form values. Everything else happens on the server.
Step 1: keys
The endpoint needs an RSA key pair. Meta's encryption guide asks for a 2048-bit key; you upload the public half per phone number:
openssl genrsa -out flows_private.pem 2048
openssl rsa -in flows_private.pem -pubout -out flows_public.pem
curl -X POST "https://graph.facebook.com/<VERSION>/<PHONE_NUMBER_ID>/whatsapp_business_encryption" \
-H "Authorization: Bearer $TOKEN" \
--data-urlencode "business_public_key=$(cat flows_public.pem)"
Meta signs the key on upload. Two operational notes: the key belongs to the phone number, so each number using the endpoint needs it, and you have to upload it again if the number is re-registered. Put the upload in the same runbook as registration, or the endpoint breaks the next time someone re-registers a number.
Step 2: decrypting the request, encrypting the response
Every request body is three base64 strings: encrypted_flow_data, encrypted_aes_key and initial_vector. Per Meta's endpoint guide:
- The AES key is encrypted with your public key using RSA OAEP with SHA-256 ("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"). It's a 128-bit key.
- The payload is AES-GCM with a 128-bit IV, and the 16-byte authentication tag is appended to the ciphertext.
- The response is encrypted with the same key and the IV with every byte flipped, the tag appended again, and the result sent back base64-encoded as the plain-text body.
import { constants, createCipheriv, createDecipheriv, privateDecrypt, type KeyObject } from "node:crypto";
// What Meta POSTs to your endpoint: three base64 strings.
export type EncryptedRequest = { encrypted_flow_data: string; encrypted_aes_key: string; initial_vector: string };
export type Decrypted = { body: any; aesKey: Buffer; iv: Buffer };
export class FlowDecryptError extends Error {}
const TAG_LENGTH = 16;
export const decryptRequest = (req: EncryptedRequest, privateKey: KeyObject): Decrypted => {
let aesKey: Buffer;
try {
aesKey = privateDecrypt(
{ key: privateKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
Buffer.from(req.encrypted_aes_key, "base64"),
);
} catch {
// Usually a stale public key on Meta's side: answering 421 makes the client re-fetch it.
throw new FlowDecryptError("could not decrypt the AES key");
}
const iv = Buffer.from(req.initial_vector, "base64");
const data = Buffer.from(req.encrypted_flow_data, "base64");
const decipher = createDecipheriv(`aes-${aesKey.length * 8}-gcm`, aesKey, iv);
decipher.setAuthTag(data.subarray(-TAG_LENGTH));
try {
const plain = Buffer.concat([decipher.update(data.subarray(0, -TAG_LENGTH)), decipher.final()]);
return { body: JSON.parse(plain.toString("utf8")), aesKey, iv };
} catch {
throw new FlowDecryptError("could not decrypt the flow data");
}
};
// During a key rotation, requests can arrive encrypted to either key: try the newest first.
export const decryptWithAny = (req: EncryptedRequest, privateKeys: KeyObject[]): Decrypted => {
for (const key of privateKeys) {
try {
return decryptRequest(req, key);
} catch (e) {
if (!(e instanceof FlowDecryptError)) throw e;
}
}
throw new FlowDecryptError("no key could decrypt the request");
};
// The response uses the same key, with every bit of the IV flipped, and goes back as base64 text.
export const encryptResponse = (payload: unknown, aesKey: Buffer, iv: Buffer): string => {
const flipped = Buffer.from(iv.map((b) => ~b & 0xff));
const cipher = createCipheriv(`aes-${aesKey.length * 8}-gcm`, aesKey, flipped);
const out = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final(), cipher.getAuthTag()]);
return out.toString("base64");
};
Two details that cost people hours:
-
The tag is the last 16 bytes of
encrypted_flow_data, not a separate field. Forget to split it off and every decryption fails with an authentication error that tells you nothing. - The response IV is the request IV inverted, byte by byte. Reusing the same IV, or generating a new one, produces a response the client can't read, and the customer just sees a generic error.
Rotating keys without breaking open forms
Keys get rotated: someone leaves, a secret leaks, a policy says yearly. Meta documents one part of this: on a 421, "The WhatsApp client will re-fetch a public key and re-send the request." It doesn't document how long clients keep a key they already fetched, so as we read it, a request encrypted to the old key can still arrive after you upload a new one. If the endpoint only knows the new private key, that request fails.
The fix is the 421 path plus a short overlap. Keep both private keys for a while and try the newest first, which is what decryptWithAny above does. Requests for the old key still decrypt, and anything neither key can open gets a 421, which tells the client to fetch the current public key and try again. Drop the old key once requests for it stop arriving, which you can see by logging which key decrypted each request.
Step 3: status codes Meta acts on
Your HTTP status code isn't just logging; the client reacts to three of them. From Meta's Flows error codes:
- 421: "The payload cannot be decrypted". The client re-fetches your public key and re-sends the request. That's the documented recovery path for a key mismatch, so return 421 for decryption failures, not 500.
- 432: "The request signature authentication fails". A generic error is shown.
-
427: "The Flow token is no longer valid". The client shows an error and disables the Flow's button. You can include
{"error_msg": "..."}in the body to say why, for example that the form has expired or the booking was already made.
Requests carry an X-Hub-Signature-256 header, a SHA-256 signature of the body with your app secret, in the same sha256= form as Cloud API webhooks. Meta's guide says you can verify it; I'd treat it as required, and check it before spending CPU on RSA.
Step 4: the actions
With crypto and status codes handled in one place, the business logic is a plain function of a decrypted request. The imports at the top cover all the endpoint snippets below:
import { createHmac, randomBytes, timingSafeEqual, type KeyObject } from "node:crypto";
import { decryptWithAny, encryptResponse, FlowDecryptError, type EncryptedRequest } from "./crypto.ts";
export class FlowTokenError extends Error {}
export type FlowRequest = {
version: string;
action: "ping" | "INIT" | "BACK" | "data_exchange";
screen?: string;
data?: Record<string, any>;
flow_token?: string;
};
export type ScreenResponse =
| { screen: string; data: Record<string, any> }
| { screen: "SUCCESS"; data: { extension_message_response: { params: Record<string, any> } } };
// Your side of a demo-class booking: sessions keyed by flow_token, live batches, bookings.
export type Booking = { course: string; batchId: string; name: string };
export type Deps = {
session: (flowToken: string) => Promise<{ contactId: string } | null>;
courses: () => Promise<{ id: string; title: string }[]>;
batches: (course: string) => Promise<{ id: string; title: string; seatsLeft: number }[]>;
book: (contactId: string, booking: Booking) => Promise<{ ok: true } | { ok: false; reason: string }>;
};
export const verifySignature = (rawBody: string, header: string | undefined, appSecret: string): boolean => {
if (!header?.startsWith("sha256=")) return false;
const expected = Buffer.from(createHmac("sha256", appSecret).update(rawBody).digest("hex"));
const given = Buffer.from(header.slice(7));
return given.length === expected.length && timingSafeEqual(given, expected);
};
const courseScreen = async (deps: Deps, error?: string): Promise<ScreenResponse> => ({
screen: "COURSE",
data: { courses: (await deps.courses()).map((c) => ({ id: c.id, title: c.title })), ...(error ? { error_message: error } : {}) },
});
const batchScreen = async (deps: Deps, course: string, error?: string): Promise<ScreenResponse> => {
const open = (await deps.batches(course)).filter((b) => b.seatsLeft > 0);
if (!open.length) return courseScreen(deps, "That course is full this month. Pick another one.");
return {
screen: "BATCH",
data: {
course,
batches: open.map((b) => ({ id: b.id, title: `${b.title} (${b.seatsLeft} seats left)` })),
...(error ? { error_message: error } : {}),
},
};
};
// The business logic: plain request in, plain response out. No crypto here.
export const route = async (req: FlowRequest, deps: Deps): Promise<Record<string, any>> => {
if (req.action === "ping") return { data: { status: "active" } };
if (req.data?.error) return { data: { acknowledged: true } }; // Meta reporting a client-side error
const session = req.flow_token ? await deps.session(req.flow_token) : null;
if (!session) throw new FlowTokenError("This form has expired. Send us a message and we'll share a new one.");
if (req.action === "INIT") return courseScreen(deps);
if (req.action === "BACK") return courseScreen(deps); // refresh the first screen with live data
const data = req.data ?? {};
if (req.screen === "COURSE") return batchScreen(deps, String(data.course ?? ""));
if (req.screen === "BATCH") {
// Re-check on the server: the seat count the customer saw may be minutes old.
const batches = await deps.batches(String(data.course ?? ""));
const batch = batches.find((b) => b.id === data.batch);
if (!batch || batch.seatsLeft < 1) return batchScreen(deps, String(data.course ?? ""), "That batch just filled up. Please pick another.");
const name = String(data.name ?? "").trim();
if (name.length < 2) return batchScreen(deps, String(data.course), "Please enter the student's name.");
const result = await deps.book(session.contactId, { course: String(data.course), batchId: batch.id, name });
if (!result.ok) return batchScreen(deps, String(data.course), result.reason);
return { screen: "SUCCESS", data: { extension_message_response: { params: { flow_token: req.flow_token, batch: batch.id } } } };
}
return courseScreen(deps, "Something went wrong. Let's start again.");
};
The rules behind it:
-
pinganswers{"data": {"status": "active"}}, encrypted like everything else. Meta's health check verifies the response decrypts properly, so a plain-text "OK" fails the check even though your server is up. -
Error notifications get
{"data": {"acknowledged": true}}. When something fails on the client side, Meta sends the error to your endpoint and expects that acknowledgement. -
The
flow_tokenis your session. Meta calls it "similar to a session identifier" and says it "should not be predictable", and recommends setting its expiry to 2 to 3 days. Look it up on every request and refuse unknown or expired ones with 427. Don't put the contact ID or anything meaningful in it. -
Re-check everything on the last step. The seat count shown on the batch screen may be minutes old by the time the customer taps Book. The
BATCHhandler re-reads seats, validates the name, and only then books. If the batch filled up meanwhile, the customer stays in the Flow with anerror_message, or goes back to the course list if the whole course is full. -
SUCCESScloses the Flow. Theextension_message_response.paramsmust include theflow_token, and whatever else you put there arrives in the completion message, so you can match it to the booking.
And the HTTP layer that ties it together, in the order the checks should run: signature, decryption, routing, encryption:
// The HTTP layer: signature, decryption, status codes, encryption.
export const handle = async (
http: { rawBody: string; signature?: string },
keys: { privateKeys: KeyObject[]; appSecret: string },
deps: Deps,
): Promise<{ status: number; body: string; contentType?: string }> => {
if (!verifySignature(http.rawBody, http.signature, keys.appSecret)) return { status: 432, body: "" };
let decrypted;
try {
decrypted = decryptWithAny(JSON.parse(http.rawBody) as EncryptedRequest, keys.privateKeys);
} catch (e) {
if (e instanceof FlowDecryptError || e instanceof SyntaxError) return { status: 421, body: "" };
throw e;
}
try {
const response = await route(decrypted.body as FlowRequest, deps);
return { status: 200, body: encryptResponse(response, decrypted.aesKey, decrypted.iv) };
} catch (e) {
// 427 disables the form's button; error_msg is what the customer sees instead.
if (e instanceof FlowTokenError) return { status: 427, body: JSON.stringify({ error_msg: e.message }), contentType: "application/json" };
throw e;
}
};
Generate the token when you send the Flow, store it with the contact and an expiry, and pass it in the Flow message:
// Unguessable, single-purpose: store it with the contact and an expiry (Meta suggests 2-3 days).
export const newFlowToken = (): string => randomBytes(24).toString("base64url");
Testing it without a phone
You don't need a real Flow on a real phone to test any of this. The client's half of the protocol is a few lines of node:crypto: make a random AES key and IV, encrypt the request, wrap the key with your public key, sign the body with the app secret, and decrypt the reply with the inverted IV:
// Plays Meta's part: encrypt a request the way the client does, and read the reply.
const metaClient = (payload: unknown, opts: { key?: typeof publicKey; secret?: string } = {}) => {
const aesKey = randomBytes(16);
const iv = randomBytes(16);
const cipher = createCipheriv("aes-128-gcm", aesKey, iv);
const data = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final(), cipher.getAuthTag()]);
const rawBody = JSON.stringify({
encrypted_flow_data: data.toString("base64"),
encrypted_aes_key: publicEncrypt({ key: opts.key ?? publicKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" }, aesKey).toString("base64"),
initial_vector: iv.toString("base64"),
});
const signature = "sha256=" + createHmac("sha256", opts.secret ?? appSecret).update(rawBody).digest("hex");
const read = (body: string) => {
const buf = Buffer.from(body, "base64");
const d = createDecipheriv("aes-128-gcm", aesKey, Buffer.from(iv.map((b) => ~b & 0xff)));
d.setAuthTag(buf.subarray(-16));
return JSON.parse(Buffer.concat([d.update(buf.subarray(0, -16)), d.final()]).toString("utf8"));
};
return { rawBody, signature, read };
};
With that, every rule in this post becomes a test: ping returns an encrypted active; a request encrypted to an old public key gets 421; a wrong signature gets 432 before any decryption; a forged token gets 427 with an error_msg; a batch that fills up between screens sends the customer back with an error instead of booking a seat that doesn't exist. Run them in CI, because the failure mode in production is a customer staring at "Something went wrong" while your logs show nothing but 200s.
Step 5: staying healthy
An endpoint Flow is only as available as your endpoint. Meta's limits:
- Requests time out after 10 seconds, and Meta's target for responses is under one second. Do the slow work (sending a confirmation, syncing a CRM) after you respond, not before.
- Meta can throttle or block a Flow when its endpoint metrics "deteriorate significantly". A throttled Flow can be sent only 10 times an hour. A blocked Flow can't be sent at all, and even Flows already delivered can't be opened. Meta doesn't publish the exact thresholds for these.
-
Alerts come first. Subscribe to the
flowswebhook field. Meta sends warnings when the endpoint error rate crosses 5%, 10% or 50% over 30 minutes, when p90 latency passes 1, 5 or 7 seconds over 30 minutes, and when availability drops below 90% over 10 minutes. Those are warning levels, not the block rules, but they're your chance to fix things before customers notice.
Practical consequences: keep the endpoint on infrastructure that doesn't scale to zero (a cold start can eat most of your 10 seconds), give it its own alerting, and keep Flow handlers free of calls to slow third-party APIs in the request path.
Versions to watch
The endpoint request has a version field. The endpoint guide still says it must be 3.0, while the Flows changelog announced data API version 4.0 in November 2025 as the recommended version, with an optional signed flow_token_signature (a JWT signed with your app secret) when the Flow JSON is 7.3 or later and the data API version is 4.0 or later. The two pages haven't caught up with each other. The code above handles 3.0; check the changelog before you move a Flow to 4.0.
Flow JSON versions also freeze and expire on a schedule. The earlier post covers that in detail.
What WAPGROWAI does today, and what it doesn't
- Our Flows are static. The Flow builder publishes Flows with no endpoint, sent from a chatbot's WhatsApp Flow block, and the answers come back in the completion message. For lead forms and simple bookings that's enough, and there's no endpoint to keep healthy.
- We don't run a data endpoint, so a Flow can't show live seats, slots or prices. Anything that changes between sending and answering has to be checked after the form comes back.
-
We match a completed chatbot Flow to its conversation, not to its
flow_token. A random token per send, as above, is the sturdier design. - Our checkout address form uses a readable token built from the order ID. That's harmless while the Flow is static, because nothing calls an endpoint with it, but it's exactly what this post says not to do once one does.
-
We don't read Flow health or the
flowswebhook. A throttled or blocked Flow shows up for us as a published Flow that customers can't open.
Checklist
- Use an endpoint only for screens that need live data; keep the rest of the Flow static.
- Generate a 2048-bit key, upload the public key per phone number, and re-upload after re-registering.
- Rotate keys with an overlap: keep the old private key until clients have re-fetched.
- Decrypt with RSA OAEP SHA-256, AES-128-GCM, tag in the last 16 bytes.
- Encrypt the response with the same key and the inverted IV, base64 in a plain-text body.
- Return 421 for decryption failures, 432 for signature failures, 427 for bad tokens.
- Verify
X-Hub-Signature-256before decrypting. - Answer
pingwith an encrypted{"data":{"status":"active"}}, and acknowledge error notifications. - Make
flow_tokenrandom, store it server-side with an expiry, and refuse unknown ones. - Re-check availability and validate input on the final step, not just on the screen that showed it.
- Respond in under a second; do slow work afterwards.
- Subscribe to the
flowswebhook and alert on error rate, latency and availability.
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: Shipping WhatsApp Flows: the JSON version that expires and Handling WhatsApp Cloud API webhooks in Node.js.
Top comments (0)