Dala i-WhatsApp Flow nge-API, hlola bese uyipapasha, uyithumele kukhasimende engxoxweni noma ngenkinobho yesifanekiso, bese uthola izinkambu ezigcwaliswe ku-webhook yakho.
Kule ncwadi wakha ifomu lokucela isiphakamiso elivula ngaphakathi kwe-WhatsApp. Ikhasimende linikeza igama lalo, likhethe isevisi bese likhetha usuku oluthandayo, futhi uhlelo lwakho luthola izimpendulo njengezinkambu ezicacile esikhundleni somlayezo wombhalo wengxoxo.
Okubonwa ikhasimende: umlayezo engxoxweni onenkinobho ethi Cela isiphakamiso. Le nkinobho ivula isikrini sefomu ngaphakathi kwe-WhatsApp, esinensimu yegama, uhlu lwezevisi kanye nesikhethi sosuku. Ithinta Thumela isicelo, ifomu livaleka, kuvele impendulo encane ethi "Sent" engxoxweni, futhi emizweni embalwa umlayezo wakho wokubonga ufika.
Okubonwa nguwe: i-flow kanye nesimo sayo ku-API, isixhumanisi sokubuka ukuze uzame ifomu kusiphequluli, izehlakalo message.status zomlayezo owathwele ifomu, kanye nesehlakalo esisodwa message.received esinezimpendulo zekhasimende ku-data.flow.response. Impendulo ibonakala nasengxenyeni ye-Inbox nasku-Activity Log.
POST /flows. Iqala njenge-draft, futhi impendulo ibala iphutha lokuqinisekisa elivela ku-WhatsApp.PUT /flows/{id}/json, uzame ifomu ngesixhumanisi sokubuka, bese uyipapasha nge-POST /flows/{id}/publish.POST /messages nomlayezo we-interactive flow. Ngaphandle kwalo: isifanekiso esivunyelwe esinenkinobho ye-Flow.message.received ene-type interactive, interactive.type nfm_reply kanye nento flow ebamba izinkambu kanye ne-flow_token oyithumele.Ama-Flow abelwana ngawo i-WhatsApp Business Account yonke. I-flow oyidalayo, oyishintshayo, oyipapashayo noma oyiyekayo yabelwana ngayo zonke izinombolo ezisendaweni efanayo ye-WhatsApp Business Account, futhi i-flow.status_changed iya kuzo zonke izinombolo. Sebenzisa amagama akhomba ukuthi i-flow yenzelwe ukuthini.
plan_not_allowed; isevisi emisiwe iphendula 403 service_not_live. Bona Ukuqala.| Scope | Isetshenziselwa ukuni kulesi sifundo |
|---|---|
templates:manage | Ukudala i-flow (POST /flows), ukushintsha i-Flow JSON yayo (PUT /flows/{id}/json), ukuyipapasha (POST /flows/{id}/publish), ukwenza isixhumanisi esisha sokubuka, ukuyiyeka noma ukuyisusa. Futhi ukudala isifanekiso ne-Flow button (POST /templates) |
messages:read | Ukufunda ama-flow (GET /flows, GET /flows/{id}, GET /flows/{id}/json) nesixhumanisi sokubuka (GET /flows/{id}/preview) |
messages:send | Ukuthumela ifomu nomlayezo wokubonga (POST /messages) |
webhooks:manage | Ukubhalisa i-webhook ezothola izimpendulo (POST /webhooks). Ungayengeza futhi ekhasini lokhiye we-API ngaphansi kwe-Webhooks |
Ukhiye we-Default (owenziwe ngaphambi kokuba okhiye banezimvume) awunayo i-templates:manage. Dala ukhiye onalelo scope, noma ngo-Full access (*). GET /v1/YOUR_NUMBER/me ikhombisa izimvume zokhiye osebenzisa.
Okungenziwa ukhiye we-sandbox kulapha. Ukhiye we-sandbox kwinombolo yakho (ukhiye onesimaki se-sandbox, owenziwe ekhasini lokhiye we-API) angakwazi ukufunda ama-flow (GET /flows, GET /flows/{id}, GET /flows/{id}/json, GET /flows/{id}/preview), futhi POST /messages nomlayezo we-flow yenza zonke izinhlolo kodwa ayithumeli lutho: impendulo inesi "sandbox": true, i-id yomlayezo iqala nge-wamid.SANDBOX., futhi izehlakalo message.status zisafika. Ukudala, ukushintsha, ukupapasha, ukuyeka nokusula ama-flow kuphendula 403 sandbox_key, ngoba zishintsha i-WhatsApp Business Account yakho. I-instant sandbox yenombolo yedemo 12025550100 ayinazo nhlobo izicelo ze-flow (403 not_in_instant_sandbox). Ngakho: yakha futhi upapashe i-flow ngokhiye ojwayelekile, uzame ngesixhumanisi sokubuka, bese uvivinya ikhodi yakho yokuthumela ngokhiye we-sandbox. Imininingwane: Sandbox.
Zonke izicelo ziya ku-https://api.app2email.com/v1/YOUR_NUMBER nge-Authorization: Bearer YOUR_API_KEY. I-YOUR_NUMBER yinombolo ye-WhatsApp oyithumela kuyo: ikhodi yezwe iqala, izinombolo kuphela.
I-flow iwuhlu lwezikrini. Le ine-skrini eyodwa, QUOTE, enekhanda, umbhalo omfushane, izinkambu ezintathu kanye nenkinobho. Isenzo se-complete senkinobho sivala ifomu futhi sibuyisele i-payload yakho: ${form.name} iyinani lenkambu ebizwa ngokuthi name, njalo nje. Amagama okhetha ku-payload ayizinkambu ozozithola.
Ulondoloze njengo-quote-request.json:
{
"version": "7.2",
"screens": [
{
"id": "QUOTE",
"title": "Request a quote",
"terminal": true,
"success": true,
"data": {},
"layout": {
"type": "SingleColumnLayout",
"children": [
{ "type": "TextHeading", "text": "Tell us what you need" },
{ "type": "TextBody", "text": "We answer every request within one working day." },
{ "type": "TextInput", "name": "name", "label": "Your name", "input-type": "text", "required": true },
{
"type": "Dropdown",
"name": "service",
"label": "Service",
"required": true,
"data-source": [
{ "id": "window_cleaning", "title": "Window cleaning" },
{ "id": "gutter_cleaning", "title": "Gutter cleaning" },
{ "id": "pressure_washing", "title": "Pressure washing" }
]
},
{ "type": "DatePicker", "name": "preferred_date", "label": "Preferred date", "required": true },
{
"type": "Footer",
"label": "Send request",
"on-click-action": {
"name": "complete",
"payload": {
"name": "${form.name}",
"service": "${form.service}",
"preferred_date": "${form.preferred_date}"
}
}
}
]
}
}
]
}Izingxenye (TextHeading, TextInput, Dropdown, DatePicker, Footer ...) nezakhiwo zazo ziyezeWhatsApp, hhayi ezika-app2email: i-app2email idlulisela i-Flow JSON ku-WhatsApp njengoba iyinjalo, futhi i-WhatsApp iyihlola. Bona incwadi ka-Meta ye-WhatsApp Flows ukuze uthole zonke izingxenye. Leli fomu alidingi iseva yakho ngenkathi ikhasimendeligcwalisa: konke kusemJSON, futhi impendulo iza kumlayezo owodwa.
POST /flows (scope templates:manage) ithatha name (eyangaphakathi, amakhasimende awayiboni, kufika kwizinhlamvu ezingu-200), okungenani enye yama-categories (SIGN_UP, SIGN_IN, APPOINTMENT_BOOKING, LEAD_GENERATION, CONTACT_US, CUSTOMER_SUPPORT, SURVEY, OTHER) kanye ne-flow_json (into noma umugqa, kufika ku-10 MB).
# Builds the body from the file with jq, then creates the draft
jq -n --slurpfile f quote-request.json \
'{name: "quote_request", categories: ["LEAD_GENERATION"], flow_json: $f[0]}' |
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/flows \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
--data @-import { readFile } from "node:fs/promises";
const flowJson = JSON.parse(await readFile("quote-request.json", "utf8"));
const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/flows", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ name: "quote_request", categories: ["LEAD_GENERATION"], flow_json: flowJson }),
});
const created = await res.json();
console.log(res.status, created.flow?.id, created.validation_errors);import json, os, requests
with open("quote-request.json") as f:
flow_json = json.load(f)
res = requests.post("https://api.app2email.com/v1/YOUR_NUMBER/flows",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={"name": "quote_request", "categories": ["LEAD_GENERATION"], "flow_json": flow_json},
timeout=30)
created = res.json()
print(res.status_code, created.get("flow", {}).get("id"), created.get("validation_errors"))Okutholayo (201 Created):
{
"success": true,
"request_id": "f1new",
"flow": {
"id": "1234567890123456",
"name": "quote_request",
"status": "DRAFT"
},
"validation_errors": [],
"note": "The flow belongs to the whole WhatsApp Business Account: every number on it can send it."
}Gcina flow.id: zonke ezinye izicelo nomlayezo othumelayo uyisebenzisa. validation_errors engenalutho isho ukuthi i-WhatsApp ayikho okufanele iyilungise. Igama elisekade lisetshenziswa i-akhawunti liphendula 409 flow_name_taken.
Uma kukhona "publish": true kuwumzimba ofanayo, i-flow engenayo amaphutha ipapashwa masinyane. Lokho akukwazi ukuguqulwa, ngakho lesi sifundo sipapasha ngesinyathelo esihlukile emva kokuzama ifomu. clone_flow_id ikopisha enye i-flow ye-akhawunti efanayo kunalokho.
Uma i-WhatsApp ithola izinkinga, i-flow isadalwa njenge-draft, futhi validation_errors ibala ngalinye ngalinye nge-error, error_type kanye ne-message ka-WhatsApp, indawo kuJSON (line_start, line_end, column_start, column_end) kanye ne-pointers. Isibonelo, ngemva kwephutha lokubhala ku-type yengxenye (ifushaniswe, umbhalo ungowe-WhatsApp):
{
"success": true,
"request_id": "f1new",
"flow": { "id": "1234567890123456", "name": "quote_request", "status": "DRAFT" },
"validation_errors": [
{
"error": "INVALID_PROPERTY_VALUE",
"error_type": "FLOW_JSON_ERROR",
"message": "Invalid value found for property 'type'.",
"line_start": 15,
"line_end": 15,
"column_start": 25,
"column_end": 36
}
]
}Lungisa ifayela bese uthumela i-Flow JSON yonke futhi nge-PUT /flows/{id}/json (scope templates:manage). Umzimba uyi-Flow JSON uqobo (noma {"flow_json": {...}}), kufika ku-10 MB.
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/json \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
--data @quote-request.jsonconst res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/json", {
method: "PUT",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: await readFile("quote-request.json", "utf8"),
});
console.log((await res.json()).validation_errors);with open("quote-request.json", "rb") as f:
res = requests.put("https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/json",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}",
"Content-Type": "application/json"},
data=f.read(), timeout=30)
print(res.json()["validation_errors"])Okutholayo:
{
"success": true,
"request_id": "f1put",
"flow_id": "1234567890123456",
"validation_errors": [],
"note": "WhatsApp found no errors. Publish with POST /flows/1234567890123456/publish (cannot be undone)."
}Umzimba ongesiyo JSON nhlobo uphendula 400 invalid_json; i-flow_json engafundeki njenge-Flow JSON iphendula 400 invalid_flow_json. GET /flows/{id}/json ibuyisela i-Flow JSON i-WhatsApp egcina ngayo i-flow.
GET /flows/{id}/preview (scope messages:read) inikeza isixhumanisi sokubuka esisebenza izinsuku ezingu-30. Engeza &interactive=true kwisixhumanisi ukuze uligcwalise wena ngokwakho.
curl https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/preview \
-H "Authorization: Bearer YOUR_API_KEY"Okutholayo:
{
"success": true,
"request_id": "f1prv",
"flow_id": "1234567890123456",
"preview_url": "https://business.facebook.com/wa/manage/flows/1234567890123456/preview/?token=b9d6a1c2",
"expires_at": "2026-12-06T01:00:00+0000",
"note": "Anyone with the link can see the flow until it expires (30 days). Add &interactive=true to try it."
}Noma ubani onesixhumanisi angasivula, nasku-iframe. Uma isixhumanisi siveza, POST /flows/{id}/preview (scope templates:manage) yenza esisha, futhi esidala siyeka ukusebenza masinyane.
Kuphela i-flow epapashiwe ingathunyelwa kumakhasimende. POST /flows/{id}/publish (scope templates:manage, akukho mzimba) ipapasha i-draft engenayo amaphutha okuqinisekisa.
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/publish \
-H "Authorization: Bearer YOUR_API_KEY"const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/publish", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.API_KEY}` },
});
console.log(res.status, await res.json());res = requests.post("https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/publish",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"}, timeout=30)
print(res.status_code, res.json())Okutholayo:
{
"success": true,
"request_id": "f1pub",
"flow_id": "1234567890123456",
"name": "quote_request",
"previous_status": "DRAFT",
"status": "PUBLISHED",
"note": "Published for every number on this WhatsApp Business Account. It cannot be deleted (deprecate it instead). Changing its name, categories, endpoint or Flow JSON puts it back to DRAFT until you publish again; messages already sent keep the old version."
}Ukupapasha akukwazi ukuguqulwa. Iwebhu yakho ithola futhi flow.status_changed ene-new_status PUBLISHED (isampula ngezansi). Uma i-WhatsApp ingayipapashi (ayisiyo i-draft, inamaphutha okuqinisekisa, noma ukuhlola kokupapasha kwehlulekile), impendulo ingu-422 flow_cannot_publish.
Ngaphambi kokuthumela, GET /flows/{id} (scope messages:read) ikhombisa isimo, amaphutha okuqinisekisa, inguqulo ye-Flow JSON kanye ne-health_status, esitshela ukuthi i-flow ingathunyelwa manje yini:
{
"success": true,
"request_id": "f1get",
"flow": {
"id": "1234567890123456",
"name": "quote_request",
"status": "PUBLISHED",
"categories": ["LEAD_GENERATION"],
"validation_errors": [],
"json_version": "7.2",
"health_status": {
"can_send_message": "AVAILABLE",
"entities": [{ "entity_type": "FLOW", "id": "1234567890123456", "can_send_message": "AVAILABLE" }]
}
}
}I-can_send_message ingu-AVAILABLE, LIMITED noma BLOCKED.
Ngaphakathi kwewindi lamahora angu-24 (ikhasimende libhale kuwe emahoreni angu-24 adlule, njengo "Ngingathola isiphakamiso?"), thumela ifomu njengomlayezo we-interactive wesimo esikhululekile nge-POST /messages (scope messages:send):
| Ingxenye | Yini okufanele ugcwalise |
|---|---|
interactive.type | flow |
header, body | Umbhalo ophezu kwenkinobho. header ayidingekile |
action.name | flow |
flow_message_version | "3" |
flow_id | I-id ye-flow kusinyathelo 2 |
flow_cta | Umbhalo wenkinobho, kufika kwizinhlamvu ezingu-30 |
flow_token | Inkomba yakho yalesi sicelo, njengesazisi somuntu othembisayo (lead) sakho. Ibuya nezimpendulo, ngakho uyazi ukuthi zezaphi izicelo |
flow_action, flow_action_payload.screen | navigate kanye ne-id yeskrini yokuqala, QUOTE |
Isihloko se-Idempotency-Key | Inani elihlukile kulokhu kuthumela. Isicelo esifanayo ngalo khiye phakathi kwamahora angu-24 ngeke sithunyelwe futhi |
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: quote-form-lead-0042" \
-d '{
"to": "61412345678",
"type": "interactive",
"interactive": {
"type": "flow",
"header": { "type": "text", "text": "Request a quote" },
"body": { "text": "Tell us what you need and when. It takes 30 seconds." },
"action": {
"name": "flow",
"parameters": {
"flow_message_version": "3",
"flow_id": "1234567890123456",
"flow_cta": "Request a quote",
"flow_token": "quote-lead-0042",
"flow_action": "navigate",
"flow_action_payload": { "screen": "QUOTE" }
}
}
}
}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": `quote-form-${leadId}`,
},
body: JSON.stringify({
to: "61412345678",
type: "interactive",
interactive: {
type: "flow",
header: { type: "text", text: "Request a quote" },
body: { text: "Tell us what you need and when. It takes 30 seconds." },
action: {
name: "flow",
parameters: {
flow_message_version: "3",
flow_id: "1234567890123456",
flow_cta: "Request a quote",
flow_token: `quote-${leadId}`,
flow_action: "navigate",
flow_action_payload: { screen: "QUOTE" },
},
},
},
}),
});
console.log(res.status, await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/messages",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}", "Idempotency-Key": f"quote-form-{lead_id}"},
json={
"to": "61412345678",
"type": "interactive",
"interactive": {
"type": "flow",
"header": {"type": "text", "text": "Request a quote"},
"body": {"text": "Tell us what you need and when. It takes 30 seconds."},
"action": {
"name": "flow",
"parameters": {
"flow_message_version": "3",
"flow_id": "1234567890123456",
"flow_cta": "Request a quote",
"flow_token": f"quote-{lead_id}",
"flow_action": "navigate",
"flow_action_payload": {"screen": "QUOTE"},
},
},
},
},
timeout=10,
)
print(res.status_code, res.json())Okutholayo (200):
{
"success": true,
"request_id": "kxrkf",
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBI1RjQyNUE3NEYxMzAzMzQ5MkEA",
"status": "accepted",
"type": "interactive",
"from": "4976659348270",
"to": "61412345678",
"window_closes_at": "2026-11-22T08:45:00Z",
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_...",
"contacts": [{ "input": "61412345678", "wa_id": "61412345678" }]
}accepted isho ukuthi i-WhatsApp iwamukele umlayezo. Gcina message_id: impendulo yekhasimende iyibhekisela kuyo. Ngaphandle kwewindi, isicelo siphendula 422 outside_24h_window.
Ngaphandle kwewindi lamahora angu-24 (ilead esuka kuwebhusayithi yakho, noma ikhasimende elibhale kuwe ngesonto eledlule), kuphela isifanekiso esivunyelwe singaqala ingxoxo. Yenza isifanekiso esinenkinobho evula i-Flow, ku-WhatsApp Manager noma nge-POST /templates (scope templates:manage, components ngefomethi ka-WhatsApp, bona incwadi ka-Meta). I-WhatsApp iyasibuka (imizuzu kuya kosuku olulodwa), futhi i-template.status_changed ikutshela umphumela. Bese usithumela ngengxenye ye-button ene-sub_type flow. I-action yayo ithwala i-flow_token:
{
"to": "61412345678",
"type": "template",
"template": {
"name": "quote_request",
"language": { "code": "en" },
"components": [
{
"type": "button",
"sub_type": "flow",
"index": "0",
"parameters": [
{ "type": "action", "action": { "flow_token": "quote-lead-0042" } }
]
}
]
}
}I-index yindawo yenkinobho kusifanekiso, kusukela ku-"0". I-flow_token ayidingekile; ngaphandle kwayo awukwazi ukutshela impendulo ngayo yesicelo, ngakho yithumele. I-action.flow_action_data idlulisela amanani kwiskrini lokuqala, uma i-Flow JSON yeskrini ithatha i-data; le fomu ayithathi lutho. GET /templates (scope messages:read) ibala izifanekiso zakho, futhi ngesifanekiso ngasinye esivunyelwe, isicelo sesibonelo esiphelele. Uma amanani esifanekiso engahambisani, impendulo ingu-422 template_parameters_invalid enesi-example_request esilungile.
message.status zomlayezo wefomu (sent, delivered, read), njengomlayezo wanoma yimuphi, bese ithola impendulo:{
"id": "evt_Pa3k9m2Lw8Rt5Yp1Zs014",
"type": "message.received",
"created": "2026-11-21T09:14:00.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgASGBQzQUZCMTY0MDc2MUYwNzBDNTY5MAA=",
"from": "61412345678",
"name": "Jane Citizen",
"type": "interactive",
"text": "[FLOW] Sent\r\nname: Jane Citizen\r\nservice: gutter_cleaning\r\npreferred_date: 2026-12-03",
"in_reply_to": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBI1RjQyNUE3NEYxMzAzMzQ5MkEA",
"context": {
"from": "4976659348270",
"id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBI1RjQyNUE3NEYxMzAzMzQ5MkEA"
},
"interactive": { "type": "nfm_reply" },
"flow": {
"name": "flow",
"body": "Sent",
"token": "quote-lead-0042",
"response": {
"flow_token": "quote-lead-0042",
"name": "Jane Citizen",
"service": "gutter_cleaning",
"preferred_date": "2026-12-03"
}
},
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_k3XbQ9rTzP2mWv7a1c9e",
"timestamp": "2026-11-21T09:14:00.000Z"
}
}data.flow.response ingokugcwaliswe ikhasimende, ngaphansi kwamagama e-payload yakho, kanye ne-flow_token. Impendulo ye-Dropdown ingu-id yenketho (gutter_cleaning), hhayi isihloko sayo.data.flow.token ingu-flow_token oyithumele: yisebenzise ukuthola umuntu wakho othembisayo.in_reply_to ne-context.id ziyi-message_id yomlayezo wefomu owuthumelile.data.text ingcaphuno efundeka yale mpendulo, yamalogi nabantu.from_user_id kodwa lingabi ne-from. Leyo id isebenza noma kuphi lapho inombolo isebenza.Zombili izinguqulo ziqinisekisa isignesha, zidlule izehlakalo ezicutshungulwe kakade, zigcine kuphela izimpendulo ze-Flow ezine-token ethi quote-, zigcine umuntu othembisayo bese zibonga. Setha kuqala i-NUMBER, i-API_KEY kanye ne-WEBHOOK_SECRET (imfihlo ye-whsec_... yewebhu yakho).
// Node.js 18 or newer. npm install express then node server.mjs
import crypto from "node:crypto";
import express from "express";
const { NUMBER, API_KEY, WEBHOOK_SECRET, PORT = 3000 } = process.env;
const API = `https://api.app2email.com/v1/${NUMBER}`;
const SERVICES = new Set(["window_cleaning", "gutter_cleaning", "pressure_washing"]);
const done = new Set(); // handled event ids: use a database table or Redis in production
function verify(raw, header, secret) {
const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]); // two during a secret change
if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
const expected = crypto.createHmac("sha256", secret).update(t + ".").update(raw).digest("hex");
return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}
async function saveLead(lead) {
console.log("new quote request", lead); // your CRM or database: one row per flow token
}
async function thank(to, messageId, name) {
const res = await fetch(`${API}/messages`, {
method: "POST",
signal: AbortSignal.timeout(4000),
headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", "Idempotency-Key": `thanks-${messageId}` },
body: JSON.stringify({ to, type: "text", text: { body: `Thanks ${name}! You will get your quote within one working day.` } }),
});
const json = await res.json();
if (res.status === 429 || res.status >= 500) throw new Error(`${json.error?.code} ${json.request_id}`);
if (!res.ok) console.warn("thank-you not sent:", json.error?.code, json.error?.how_to_fix, json.request_id);
}
const app = express();
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
if (!verify(req.body, req.get("X-App2email-Signature"), WEBHOOK_SECRET)) return res.sendStatus(401);
const event = JSON.parse(req.body);
const m = event.data ?? {};
const isQuote = event.type === "message.received" && m.interactive?.type === "nfm_reply" && m.flow?.token?.startsWith("quote-");
if (!isQuote || done.has(event.id)) return res.sendStatus(200);
const answers = m.flow.response ?? {};
const lead = {
token: m.flow.token,
contact: m.from || m.from_user_id,
name: String(answers.name ?? "").slice(0, 100),
service: SERVICES.has(answers.service) ? answers.service : "other",
preferred_date: /^\d{4}-\d{2}-\d{2}$/.test(answers.preferred_date ?? "") ? answers.preferred_date : null,
message_id: m.message_id,
};
try {
await saveLead(lead);
if (!event.test) await thank(lead.contact, m.message_id, lead.name); // test events have a made-up contact
done.add(event.id); // only after it worked: a failed event comes again
res.sendStatus(200);
} catch (err) {
console.error("not handled, app2email will send it again:", event.id, err.message);
res.sendStatus(503);
}
});
app.listen(PORT, () => console.log(`listening on http://localhost:${PORT}/webhook`));# Python 3.9 or newer. pip install flask requests then flask --app server run --port 3000
import hashlib, hmac, json, os, re, time
import requests
from flask import Flask, request
NUMBER, API_KEY, SECRET = os.environ["NUMBER"], os.environ["API_KEY"], os.environ["WEBHOOK_SECRET"]
API = f"https://api.app2email.com/v1/{NUMBER}"
SERVICES = {"window_cleaning", "gutter_cleaning", "pressure_washing"}
done = set() # handled event ids: use a database table or Redis in production
def verify(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
t = re.search(r"(?:^|,)\s*t=(\d+)", header or "")
v1 = re.findall(r"(?:^|,)\s*v1=([0-9a-f]+)", header or "") # two during a secret change
if not t or not v1 or abs(time.time() - int(t.group(1))) > tolerance:
return False
expected = hmac.new(secret.encode(), t.group(1).encode() + b"." + raw, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(v, expected) for v in v1)
def save_lead(lead):
print("new quote request", lead) # your CRM or database: one row per flow token
def thank(to, message_id, name):
res = requests.post(f"{API}/messages", timeout=4,
headers={"Authorization": f"Bearer {API_KEY}", "Idempotency-Key": f"thanks-{message_id}"},
json={"to": to, "type": "text",
"text": {"body": f"Thanks {name}! You will get your quote within one working day."}})
data = res.json()
if res.status_code == 429 or res.status_code >= 500:
raise RuntimeError(f"{data.get('error', {}).get('code')} {data.get('request_id')}")
if not res.ok:
print("thank-you not sent:", data["error"]["code"], data["error"].get("how_to_fix"), data.get("request_id"))
app = Flask(__name__)
@app.post("/webhook")
def webhook():
raw = request.get_data()
if not verify(raw, request.headers.get("X-App2email-Signature"), SECRET):
return "bad signature", 401
event = json.loads(raw)
m = event.get("data") or {}
flow = m.get("flow") or {}
is_quote = (event.get("type") == "message.received"
and (m.get("interactive") or {}).get("type") == "nfm_reply"
and str(flow.get("token", "")).startswith("quote-"))
if not is_quote or event["id"] in done:
return "", 200
answers = flow.get("response") or {}
date = str(answers.get("preferred_date", ""))
lead = {
"token": flow["token"],
"contact": m.get("from") or m.get("from_user_id"),
"name": str(answers.get("name", ""))[:100],
"service": answers.get("service") if answers.get("service") in SERVICES else "other",
"preferred_date": date if re.fullmatch(r"\d{4}-\d{2}-\d{2}", date) else None,
"message_id": m.get("message_id"),
}
try:
save_lead(lead)
if not event.get("test"): # test events have a made-up contact
thank(lead["contact"], m["message_id"], lead["name"])
except Exception as err:
print("not handled, app2email will send it again:", event["id"], err)
return "", 503
done.add(event["id"]) # only after it worked: a failed event comes again
return "", 200Ukuze uvivinye umamukeli ngaphandle kwekhasimende langempela, thumela kuyo isampula yakho: POST /webhooks/{id}/test (scope webhooks:manage) nge-{"event": {...}} kanye nomzimba we-message.received ongenhla. Izehlakalo zokuvivinya zinethegi "test": true kanye nehedha X-App2email-Test: true, futhi zisayinwa njengazo zonke izehlakalo; kufika kwezivivinyo ezingu-30 ngehora ngenombolo ngayinye.
flow.status_changed ibika okwenzekayo ku-flow: ipapashiwe, ivinjiwe, ivinjelwe noma iyekiwe, isixwayiso sekhasi noma sekhasimende esiphakanyiswe noma esisulwe yi-Meta, noma isixwayiso sokuthi inguqulo ye-Flow JSON yayo isazophelelwa. Zonke izinombolo ku-WhatsApp Business Account ziyithola.
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs21",
"type": "flow.status_changed",
"created": "2026-11-21T09:05:00.000Z",
"number": "4976659348270",
"data": {
"flow_id": "1234567890123456",
"change": "status",
"event": "FLOW_STATUS_CHANGE",
"old_status": "DRAFT",
"new_status": "PUBLISHED",
"message": "Flow quote_request changed status from DRAFT to PUBLISHED",
"timestamp": "2026-11-21T09:05:00.000Z"
}
}Qaphela new_status THROTTLED noma BLOCKED, kanye nokuthi change flow_version_expiry_warning: i-warning yayo ikhomba ukuthi inguqulo ye-Flow JSON izokhenga nini. Emva kwalokho i-flow ayisaye ithunyelwa, ngakho hambisa i-JSON ibe version entsha nge-PUT /flows/{id}/json bese uyipapasha futhi.
PUT /flows/{id}/json nge-JSON entsha, noma PATCH /flows/{id} nge-name, categories noma endpoint_uri entsha. I-flow epapashiwe ibuyela ku-DRAFT uze uyiphapshe futhi, futhi imilayezo esuke ithunyiwe igcina inguqulo endala. Ezinye ama-flow awavumi ukushintshwa (409 flow_not_editable, njengalowo oyekiwe): yikopishe nge-POST /flows ne-clone_flow_id, bese ushintsha ikhophi bese uyipapasha leyo.POST /flows/{id}/deprecate (scope templates:manage). Ayisaye ithunyelwa noma ivulwa. Lokhu akukwazi ukuguqulwa.DELETE /flows/{id} isebenza kumadrafti kuphela. I-flow epapashiwe iphendula 409 flow_not_deletable: yiyeke kunalokho.GET /flows (scope messages:read) ibala zonke ama-flow ye-akhawunti ngenombolo yawo, igama, isimo, izigaba kanye namaphutha okuqinisekisa, 1 kuya ku-100 ngesikhathi (limit, kanye ne-cursor nge-next_cursor yempendulo yangaphambili).Amafomu adinga idatha ephilayo. Lesi sifundo sifomu elizimele. I-flow ethola idatha ngenkathi ikhasimende ligcwalisa (izikhathi ezikhululekile, amanani) isebenzisa iphoyinti ledatha lakho: endpoint_uri ku-flow, kanye nokhiye womphakathi we-RSA we-2048-bit wenombolo osethwe nge-PUT /flows/encryption-key (scope templates:manage; GET /flows/encryption-key ikhombisa wona). Inombolo ngayinye inokhiye wayo. Ngenkathi i-Book-and-Pay isebenzisa lokhiye ngama-Flow ayo okubhukha, ukusetha elinye kuphendula 409 encryption_key_managed.
Awunayo i-Flow JSON yokubhala? I-app2email nayo yakha amafomu e-WhatsApp ngawe. Submit-Info iguqula uhlu lwemibuzo elula ibe yifomu le-WhatsApp nekhasi lewebhu (POST /submit/forms, POST /submit/forms/{key}/publish, POST /submit/forms/{key}/send, scope submissions:manage); izimpendulo zayo ziza njenge-submission.created. Isigaba se-Book-and-Pay sinefomu lokubhukha namanye amafomu owathumela ngawo nge-POST /flows/{key}/send (scope bookings:manage); ifomu le-Flow kulelo sigaba libika flow.completed, i-flow yokubhukha ibika booking.created. Ama-flow odala ngawo nge-POST /flows abika izimpendulo zawo njenge-message.received, njengoba kukhonjisiwe ngenhla.
Hlola zonke izehlakalo. Hlola X-App2email-Signature (t=<unix seconds>,v1=<hex>, i-HMAC-SHA256 ka-t, ichashazi nomzimba ongaguqulwanga, ngemfihlo ye-whsec_... yewebhu), phezu komzimba ongaguqulwanga, ngaphambi kokuwuhlaziya. Hlola yonke v1=, qhathanisa ngendlela engathathi isikhathi esihlukile futhi wenqabe t edlule imizuzu emi-5.
Hlukanisa ngama-id angempela. Gcina i-id yesehlakalo (futhi ku-X-App2email-Delivery) yayo yonke izehlakalo ezicutshunguliwe okungenani izinsuku ezimbili: isehlakalo esehlulekile siyathunyelwa futhi cishe emahoreni angu-32. Gcina ilead eyodwa ngayo yonke flow_token, ukuze ikhasimende elithumela ifomu kabili libuyekeze isicelo sakho esikhona kunokudala esesibili.
Thumela umlayezo ngamunye kanye. Nika yonke POST /messages i-Idempotency-Key (efomini: i-id yelead yakho; ekubongeni: i-message_id yempendulo). Ukhiye nomzimba ofanayo ngaphakathi kwamahora angu-24 kubuyisa impendulo yokuqala nge-Idempotent-Replayed: true. Ukhiye ofanayo nomzimba omunye: 422 idempotency_key_reused. 409 idempotency_request_in_progress: linda bese uzama futhi ngokhiye ofanayo.
Phendula ngokushesha. Buyisela 2xx ngaphakathi kwemizuzwana engu-10; ukuqondiswa kabusha akulandelwa. Emsebenzini omude, gcina isehlakalo, phendula ngo-200 bese usicubungula kusuka ku-queue.
Hlonipha imikhawulo. Yonke impendulo inezi-X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset kanye ne-X-RateLimit-Policy. Uma udlula umkhawulo: 429 rate_limited ne-Retry-After; linda, bese uthumela futhi. Imikhawulo ye-WhatsApp (429 whatsapp_rate_limit, too_many_messages_to_recipient) idinga imizuzu. Umlayezo ngamunye wefomu ubalwa njengomlayezo oyedwa wohlelo lwakho.
Qaphela iwindi lamahora angu-24. Umlayezo wefomu we-interactive uyisimo esikhululekile: uya kukhasimende elibhale kuphela emahoreni angu-24 adlule (i-app2email imisa imizuzu eyi-15 ngaphambi kwesikhathi; i-window_closes_at iyisikhathi esiqondile). Abanye bonke bathola isifanekiso esivunyelwe ne-Flow button.
Ukuvuma nokungashayi. Uma isifanekiso sakho senkinobho ye-Flow siyisifanekiso sokukhangisa, silandela imithetho efanayo nanoma yisiphi isifanekiso sokukhangisa: ikhasimende oselisohlwini lwakho Lokungashayi (Do Not Call) liphendula 403 recipient_opted_out, futhi inombolo edinga ukuvuma kuqala iphendula 403 recipient_not_opted_in kukhasimende elingenalo. Izifanekiso zokusebenza (utility) zisathunyelwa. Bona Thumela umsakazo wokukhangisa ohlonipha ukuvuma.
Phatha impendulo njengedatha. Ikhasimende yiyo eyibhalile. Hlola inkambu ngayinye (i-id yesevisi esaziwayo, usuku lwangempela, ubude obufanele) ngaphambi kokuthi ingene edathabeni yakho, futhi ungayisebenzisi njengomyalelo noma uyidlulisele kumodeli ye-AI ihlanganiswe nemiyalelo yakho.
Shintsha ama-flow ngokucophelela. Ama-flow abelwana ngawo zonke izinombolo ku-WhatsApp Business Account, futhi ukushintsha i-flow epapashiwe kuyibuyisela ku-DRAFT uze uyiphapshe futhi. Gcina i-Flow JSON kwinguqulo yakho yokulawula, zama ukushintsha ngesixhumanisi sokubuka, futhi qaphela i-flow.status_changed.
Ukufinyelela okuncane. Umamukeli udinga i-messages:send kuphela (ukubonga). Gcina i-templates:manage kukhiye ohlukile osetshenziswa yizikripthi zakho zokusetha kuphela. Gcina okhiye kuseva, hhayi ekhasini lewebhu noma elogini.
| Okubonakalayo | Kungani | Ukulungisa |
|---|---|---|
403 insufficient_scope | Ukhiye awunayo imvume (details.required_scope) | Yenza ukhiye one-templates:manage ukuze wakhe ama-flow, ne-messages:send ukuze uwathumele |
403 sandbox_key | Ukhiye we-sandbox awukwazi ukudala, ukushintsha noma ukupapasha ama-flow | Sebenzisa ukhiye ojwayelekile kulezi zicelo; gcina ukhiye we-sandbox ukuvivinya POST /messages |
403 not_in_instant_sandbox | Inombolo yedemo 12025550100 ayinazicelo zama-flow | Sebenzisa inombolo yakho exhunywe |
400 invalid_flow_name | name ayikho noma inde kunezinhlamvu ezingu-200 | Thumela igama elifushane langaphakathi, njengo quote_request |
400 invalid_flow_categories | categories ayikho noma inexabiso elingaziwa | Thumela uhlu olunesigaba esisodwa okungenani, njengo ["LEAD_GENERATION"] |
400 invalid_flow_json, invalid_json | I-Flow JSON noma umzimba awuyona i-JSON evumelekile, noma awuyona into (object) | Hlola amabhrakethi, izinikazi namakhoma; thumela i-Flow JSON njengento (object) |
400 invalid_flow_field | Inkambu inohlobo lwenani olungafanele, njengo-publish ongesiyo true noma false | Sebenzisa izinkambu name, categories, flow_json, publish, endpoint_uri, clone_flow_id |
400 invalid_flow_id, 404 flow_not_found | I-id esekheli ayisiyo i-flow yale akhawunti | GET /flows ibala ama-id |
404 flow_json_not_found | I-flow ayinayo i-Flow JSON okwamanje | Yilayisha nge-PUT /flows/{id}/json |
validation_errors ayingenalutho | I-WhatsApp ithole izinkinga ku-Flow JSON | Lungisa ngayinye endaweni yayo (umugqa nekholomu), bese uthumela PUT /flows/{id}/json futhi |
409 flow_name_taken | I-akhawunti sekunayo i-flow enalelo gama | Khetha elinye igama |
413 flow_json_too_large | I-Flow JSON ingaphezu komkhawulo ka-WhatsApp ongu-10 MB | Yenza ibe mincane |
422 flow_cannot_publish | I-flow ayisiyo i-draft, inamaphutha okuqinisekisa, noma yehlulekile ukuhlolwa kokupapasha | GET /flows/{id} ikhombisa validation_errors ne-health_status; zilungise bese upapasha futhi |
422 flow_rejected | I-WhatsApp ayiyamukelanga isicelo | Funda whatsapp_error kwimpendulo, lungisa isicelo bese usithumela futhi |
409 flow_not_editable | I-WhatsApp ayivumi ukuthi le flow ishintshwe | Yikopishe nge-clone_flow_id, shintsha ikhophi bese upapasha leyo |
409 flow_not_deletable | I-flow epapashiwe ayikwazi ukususwa | Yiyeke nge-POST /flows/{id}/deprecate |
409 flow_not_published | Kuphela i-flow epapashiwe ingayekwa | Akukho okuyekwayo; i-draft ingasulwa |
409 encryption_key_managed | I-Book-and-Pay isebenzisa ukhiye wokubethela we-Flow wenombolo | Shiya ukhiye njengoba unjalo; i-flow enephoyinti ledatha lakho idinga inombolo engenayo i-Book-and-Pay |
403 flow_blocked_by_integrity | I-Meta ivimbela ukudala noma ukupapasha ama-flow kule-akhawunti ye-WhatsApp | Xhumana nosekelo lwe-Meta nge-WhatsApp Manager |
403 whatsapp_permission_missing | I-Meta ayinikanga i-app2email imvume edingwa yile nto ye-akhawunti yakho | Ukuzama futhi akusizi; xhumana ne-support@app2email.com |
422 outside_24h_window | Ikhasimende libhale okokugcina ngaphezu kwamahora angu-24 adlule | Thumela isifanekiso esivunyelwe ne-Flow button kunalokho |
404 template_not_found, 422 template_not_approved | Igama noma ulimi lwesifanekiso alulungile, noma asivunyelwe okwamanje | Khetha esinye ku-GET /templates esinesimo APPROVED |
422 template_parameters_invalid | Inkinobho yesifanekiso ayihambisani nesifanekiso | Qhathanisa ne-example_request kwimpendulo |
400 invalid_interactive | Ingxenye ye-interactive ayisebenzi (uhlobo lwayo noma ubude bombhalo) | Hlola interactive.type flow, i-action.parameters, bese ugcina flow_cta ibe yizinhlamvu ezingu-30 |
429 rate_limited | Izicelo eziningi kakhulu kulokhiye | Linda izikhathi Retry-After bese uzama futhi |
502 whatsapp_error | I-WhatsApp inqabe isicelo ngephutha elingenakhodi yalo | Funda whatsapp_error; zama futhi kamuva, futhi uthumele i-request_id kusekelo uma kuhlulekile njalo |
| Ifomu livula, kodwa impendulo ayifiki | Iwebhu icimyile, noma umamukeli wakho ulahla isehlakalo | GET /webhooks ikhombisa active nokulethwa kokugcina; GET /webhooks/{id}/deliveries?status=failed ikhombisa okwehlulekile |
Yonke impendulo inesi-request_id. GET /requests/{id} ikhombisa okulogiwe ngayo, futhi ne-support@app2email.com ingayithola. Zonke ikhodi: Amaphutha.
Yebo. I-MCP server https://api.app2email.com/mcp/flows inazo zonke izicelo njengamathuluzi: list_flows, get_flow, create_flow, update_flow, get_flow_json, update_flow_json, publish_flow, deprecate_flow, delete_flow, get_flow_preview kanye ne-renew_flow_preview. Bona Vumela i-AI agent iphathe i-WhatsApp yakho nge-MCP kanye ne-MCP.
Umlayezo wefomu we-interactive uya komunye umuntu ngocingo ngalunye, ngaphakathi kwewindi lakhe. Ukuze ufinyelele abaningi, thumela isifanekiso esivunyelwe ne-Flow button, njengomsakazo kuqembu elithile, futhi ulandele imithetho yokuvuma yezifanekiso zokukhangisa. Nika wonke ikhasimende i-flow_token yalo uma udinga ukuhlanganisa impendulo nabantu.
Imilayezo esuke ithunyiwe igcina inguqulo ye-flow ethunyelwe ngayo. Ukushintsha kuqala ukusebenza kumilayezo emisha uma upapasha futhi. I-flow eyekiwe ayisaye ithunyelwe noma ivulwe.
Yebo: i-webhook ene-"format": "meta" ithola okufika ku-WhatsApp njengomzimba ka-Meta ngqo (entry[].changes[]), isayinwe ngendlela efanayo. Kufomethi ezenzakalelayo ye-app2email impendulo sekhishwe ibe data.flow, njengoba kukhonjisiwe ngenhla. I-data.whatsapp nayo iphethe umlayezo ka-Meta ungaguqulwanga.
Izikhathi ezikhululekile, ukubhukha nezikhumbuzo nge-Book-and-Pay API.
Thola imilayezo ku-webhook esayiniwe bese uphendula kusikripthi sakho.
Izifanekiso ezivunyelwe zemilayezo ngaphandle kewindi lamahora angu-24, nesimo sokulethwa.
Beka abaholi ofomu lakho olibuthayo eduze kwedatha yakho yonke yamakhasimende.