A WhatsApp Flows endpoint is an HTTPS server that checks the X-Hub-Signature-256 header and decrypts the POST body with your RSA private key and AES-GCM. It answers with the next screen, encrypted under the bit-inverted IV. It must also answer a ping health check and acknowledge error notifications. The Python server below does all of it with the standard library’s http.server plus the cryptography package. If you haven’t decided whether your Flow needs an endpoint, start with WhatsApp Flows: build forms inside the chat.
What Meta requires before the first request
Meta’s endpoint guide lists four steps (implementing your Flow endpoint, accessed 2026-11-04). They are a key pair, an HTTPS server with a valid TLS certificate, payload encryption, and the Flow JSON settings. The TLS certificate “does not have to be used in payload encryption/decryption”, so the RSA pair is a separate key.
The key is 2048-bit RSA, and you upload it to each registered phone number with a system user token that has whatsapp_business_messaging (business encryption, accessed 2026-11-04). These are Meta’s commands and upload call.
openssl genrsa -des3 -out private.pem 2048
openssl rsa -in private.pem -outform PEM -pubout -out public.pem
curl -X POST \
'https://graph.facebook.com/v26.0/PHONE_NUMBER_ID/whatsapp_business_encryption' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'business_public_key=BUSINESS_PUBLIC_KEY'
-des3 encrypts the private key with the passphrase you type at the prompt. Meta’s Python sample loads the key with password=None, which fails on a key made this way. The server below reads the passphrase from the PASSPHRASE environment variable. Upload the key again after you re-register the number, and after a public-key-missing or public-key-signature-verification alert. Solution Partners should use a dedicated endpoint and key pair for each Messaging account.
Point the Flow at the endpoint
From Flow JSON 3.0, data_channel_uri “is not supported” (Flow JSON, accessed 2026-11-04). You set endpoint_uri through the Flows API or the Builder UI (Flows API, accessed 2026-11-04). The Flow JSON also needs a routing_model and a data_api_version, which the Flow JSON page gives as 3.0. Meta’s changelog of November 11, 2025 recommends 4.0 (Flows changelog, accessed 2026-11-04). Set 3.0 or 4.0.
Publishing needs a verified business with high message quality, plus three checks. “All the flows with endpoints need to have an Application connected to them.” Meta’s error list also blocks publishing until you “upload and sign a public key”. It also requires you to “verify that the endpoint is available and that you’ve implemented a health check” (Flows error codes, accessed 2026-11-04).
When WhatsApp calls your endpoint
The guide names six triggers. The first three are a Flow message sent with flow_action set to data_exchange, an on-click-action named data_exchange, and refresh_on_back set to true. The others are an on-select-action, a previous reply from your endpoint with invalid content, and the “Periodical health check from WhatsApp”.
Every request, the ping included, arrives in one envelope:
{
"encrypted_flow_data": "ENCRYPTED_FLOW_DATA",
"encrypted_aes_key": "ENCRYPTED_AES_KEY",
"initial_vector": "INITIAL_VECTOR"
}
The encryption scheme
Decode all three fields from base64. Decrypt encrypted_aes_key with your private key using RSA-OAEP, with SHA-256 as both the hash and the MGF1 function. The result is a 128-bit AES key. Decrypt encrypted_flow_data with AES-GCM using that key and the decoded IV. The last 16 bytes of the data are the GCM tag.
To answer, invert every bit of the request IV by XOR-ing each byte with 0xFF. Encrypt your JSON with AES-GCM under the same key and the flipped IV, then append the 16-byte tag. Finally, “encode the whole output as base64 string and send it in the HTTP response body as plain text”. RSA-OAEP and AES-GCM aren’t in Python’s standard library, so the server requires pip install cryptography.
The decrypted request and your response
The decrypted JSON carries version, action, screen, data and flow_token. action is INIT when the Flow opens, BACK when the user presses back, and data_exchange when a screen is submitted. For INIT and BACK, screen “may not be populated”, so don’t route those on it. flow_token is the token you generated and sent with the Flow message.
Return {"screen": "NEXT_SCREEN", "data": {...}} to move on. To reject a value, return the same screen with error_message inside data. Meta “redirects the user to <SCREEN_NAME> and triggers a snackbar error”. A route can’t point to the current screen, but “the route can be ‘refreshed’ for validation purposes”.
To finish the Flow, return the SUCCESS screen with flow_token in data.extension_message_response.params. The answers then reach your messages webhook as an nfm_reply message. That payload doesn’t include the Flow ID, so match it on flow_token (Flows webhooks, accessed 2026-11-04). Meta also recommends sending the user a summary message in the chat.
The health check decrypts to {"version": "3.0", "action": "ping"} and expects {"data": {"status": "active"}}. An error notification arrives after you sent a bad response. Its data carries error and error_message, and it expects {"data": {"acknowledged": true}}. Meta’s parameter table calls screen required there, but its sample omits it. The server below tests data.error before any routing, as Meta’s Node sample does (WhatsApp-Flows-Tools basic endpoint, accessed 2026-11-04).
The signature header
“Meta signs all endpoint requests with a SHA256 signature” in X-Hub-Signature-256. The value is sha256= plus an HMAC-SHA256 of the raw body, keyed with your app secret. Answer 432 when it doesn’t match. Webhooks use the same check, explained in verify X-Hub-Signature-256. When you rotate the app secret, Meta suggests accepting either secret for a number of hours it doesn’t specify. The server accepts an optional OLD_APP_SECRET for that window.
Data API 4.0 with Flow JSON 7.3 or later also sends flow_token_signature, an HS256 JWT signed with your app secret. It is optional. The guide doesn’t name the claim inside it, so this server doesn’t verify it.
The endpoint in Python
decrypt_request and encrypt_response keep the logic of Meta’s Django sample, except that the private key loads once at startup with the passphrase. http.server replaces the Django view. Everything else is ours, built from Meta’s guide and error codes: the signature check, the 421, 427 and 432 responses, the ping, the error acknowledgment and the routing. APPOINTMENT and CONFIRM are placeholder screens with routing model {"APPOINTMENT": ["CONFIRM"]}; rename them and the data keys to match your Flow JSON.
# flows_endpoint.py
# pip install cryptography
# APP_SECRET=... PASSPHRASE=... PRIVATE_KEY_PATH=private.pem python3 flows_endpoint.py
import hashlib
import hmac
import json
import os
from base64 import b64decode, b64encode
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.padding import MGF1, OAEP
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.serialization import load_pem_private_key
APP_SECRETS = [s for s in (os.environ["APP_SECRET"], os.environ.get("OLD_APP_SECRET")) if s]
PASSPHRASE = os.environ.get("PASSPHRASE") # the -des3 passphrase
with open(os.environ.get("PRIVATE_KEY_PATH", "private.pem"), "rb") as f:
PRIVATE_KEY = load_pem_private_key(
f.read(), password=PASSPHRASE.encode("utf-8") if PASSPHRASE else None)
SLOTS = ["09:00", "10:00", "11:00"] # placeholder data for the first screen
def decrypt_request(encrypted_flow_data_b64, encrypted_aes_key_b64, initial_vector_b64):
flow_data = b64decode(encrypted_flow_data_b64)
iv = b64decode(initial_vector_b64)
# Decrypt the AES encryption key
encrypted_aes_key = b64decode(encrypted_aes_key_b64)
aes_key = PRIVATE_KEY.decrypt(encrypted_aes_key, OAEP(
mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
# Decrypt the Flow data
encrypted_flow_data_body = flow_data[:-16]
encrypted_flow_data_tag = flow_data[-16:]
decryptor = Cipher(algorithms.AES(aes_key),
modes.GCM(iv, encrypted_flow_data_tag)).decryptor()
decrypted_data_bytes = decryptor.update(
encrypted_flow_data_body) + decryptor.finalize()
decrypted_data = json.loads(decrypted_data_bytes.decode("utf-8"))
return decrypted_data, aes_key, iv
def encrypt_response(response, aes_key, iv):
# Flip the initialization vector
flipped_iv = bytearray()
for byte in iv:
flipped_iv.append(byte ^ 0xFF)
# Encrypt the response data
encryptor = Cipher(algorithms.AES(aes_key),
modes.GCM(flipped_iv)).encryptor()
return b64encode(
encryptor.update(json.dumps(response).encode("utf-8")) +
encryptor.finalize() +
encryptor.tag
).decode("utf-8")
def valid_signature(raw_body, header):
if not header or not header.startswith("sha256="):
return False
received = header[len("sha256="):]
return any(
hmac.compare_digest(received, hmac.new(s.encode(), raw_body, hashlib.sha256).hexdigest())
for s in APP_SECRETS)
def flow_token_is_valid(token):
return bool(token) # replace with a lookup of the tokens you issued
def handle(req):
action = req.get("action")
data = req.get("data") or {}
if action == "ping":
return {"data": {"status": "active"}}
if data.get("error"):
print("client error:", data)
return {"data": {"acknowledged": True}}
if action in ("INIT", "BACK"):
return {"screen": "APPOINTMENT", "data": {"slots": SLOTS}}
if action == "data_exchange" and req.get("screen") == "APPOINTMENT":
if data.get("slot") not in SLOTS:
return {"screen": "APPOINTMENT",
"data": {"slots": SLOTS, "error_message": "Pick one of the listed times."}}
return {"screen": "CONFIRM", "data": {"slot": data["slot"]}}
if action == "data_exchange" and req.get("screen") == "CONFIRM":
return {"screen": "SUCCESS", "data": {"extension_message_response": {
"params": {"flow_token": req["flow_token"], "slot": data.get("slot")}}}}
raise ValueError(f"unhandled action {action!r} on screen {req.get('screen')!r}")
class FlowsEndpoint(BaseHTTPRequestHandler):
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
if not valid_signature(raw, self.headers.get("X-Hub-Signature-256")):
return self.reply(432)
try:
envelope = json.loads(raw)
req, aes_key, iv = decrypt_request(
envelope["encrypted_flow_data"],
envelope["encrypted_aes_key"],
envelope["initial_vector"])
except Exception as exc:
print("decryption failed:", exc)
return self.reply(421) # the client re-fetches the public key and retries
if req.get("action") != "ping" and not flow_token_is_valid(req.get("flow_token")):
return self.reply(427)
try:
body = encrypt_response(handle(req), aes_key, iv)
except Exception as exc:
print("handler failed:", exc)
return self.reply(500)
self.reply(200, body)
def reply(self, status, body=""):
payload = body.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
if __name__ == "__main__":
ThreadingHTTPServer(("", int(os.environ.get("PORT", "3000"))), FlowsEndpoint).serve_forever()
http.server speaks plain HTTP, and Meta requires HTTPS with a valid certificate. Put it behind a TLS reverse proxy, or use a tunnel while testing, as in local webhook testing with ngrok.
Test it without WhatsApp
This client plays the WhatsApp side: it encrypts a request with public.pem, signs it and decrypts the answer.
# test_client.py
# pip install cryptography
# APP_SECRET=... python3 test_client.py INIT
import hashlib
import hmac
import json
import os
import sys
import urllib.request
from base64 import b64decode, b64encode
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric.padding import MGF1, OAEP
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
with open("public.pem", "rb") as f:
public_key = serialization.load_pem_public_key(f.read())
aes_key, iv = os.urandom(16), os.urandom(16)
action = sys.argv[1] if len(sys.argv) > 1 else "ping"
plain = json.dumps({"version": "3.0", "action": action, "flow_token": "test-token", "data": {}})
body = json.dumps({
"encrypted_flow_data": b64encode(AESGCM(aes_key).encrypt(iv, plain.encode(), None)).decode(),
"encrypted_aes_key": b64encode(public_key.encrypt(aes_key, OAEP(
mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))).decode(),
"initial_vector": b64encode(iv).decode(),
}).encode()
signature = "sha256=" + hmac.new(os.environ["APP_SECRET"].encode(), body, hashlib.sha256).hexdigest()
request = urllib.request.Request("http://localhost:3000/", data=body, headers={
"Content-Type": "application/json", "X-Hub-Signature-256": signature})
with urllib.request.urlopen(request) as response:
flipped_iv = bytes(b ^ 0xFF for b in iv)
print(json.loads(AESGCM(aes_key).decrypt(flipped_iv, b64decode(response.read()), None)))
ping should print {'data': {'status': 'active'}}, and INIT the APPOINTMENT screen with its slots. A wrong APP_SECRET gets HTTP 432.
Status codes and error types
| HTTP | When to return it | What the client does |
|---|---|---|
| 421 | The payload can’t be decrypted | “The WhatsApp client will re-fetch a public key and re-send the request”; a second failure shows a generic error |
| 432 | The signature doesn’t match | Shows a generic error |
| 427 | The flow token is no longer valid | Shows a generic error and disables the CTA; send a new message to issue a new token |
Meta’s error reference also lists the error types reported back to you.
| Error type | Meaning |
|---|---|
public-key-missing |
The client couldn’t retrieve your public key from WhatsApp servers |
public-key-signiture-verification |
The client couldn’t verify the key’s signature (Meta’s spelling) |
response-decryption-error |
The client couldn’t decrypt your response |
business-decryption-error |
You returned 421 even after the client refreshed the public key |
timeout_error |
Your endpoint took more than 10 seconds |
no_http_response_error |
The connection closed without a valid HTTP response |
unexpected_http_status_code |
An unexpected status, such as the 500 this server returns when handle raises |
Response time and health monitoring
Meta’s health page says to “aim to return a response in less than 1 second” (health monitoring, accessed 2026-11-04). Meta watches error rate, latency and availability, and “If any of these metrics deteriorate significantly, WhatsApp may throttle or block your Flow.”
| State | Effect | Way out |
|---|---|---|
| Throttled | “Sending of the Flow restricted to 10 messages per hour”; users can still open Flows they already received | Moves to Published once the endpoint recovers |
| Blocked | “Sending and opening of the Flow is blocked” | Moves to Throttled first, then to Published |
“You will receive multiple alert webhooks before the Flow becomes Throttled or Blocked.” Subscribe to both the flows and messages fields in the App Dashboard to get them and the nfm_reply completions.
| Alert | Thresholds | Window |
|---|---|---|
ENDPOINT_ERROR_RATE |
5%, 10%, 50% | 30 minutes |
ENDPOINT_LATENCY |
p90 of 1 s, 5 s, 7 s | 30 minutes |
ENDPOINT_AVAILABILITY |
90% | 10 minutes |
CLIENT_ERROR_RATE |
About 5%, 10%, 50% | 60 minutes |
Keep handle to fast lookups, and move CRM writes or model calls to after the nfm_reply arrives.
Z-API Omni team