Crei un WhatsApp Flow con l'API, lo controlli e lo pubblichi, lo invii a un cliente dentro la chat o con il pulsante di un template e riceva i campi compilati sul suo webhook.
In questa guida crea un modulo di richiesta preventivo che si apre dentro WhatsApp. Il cliente indica il suo nome, sceglie un servizio e una data preferita, e il suo sistema riceve le risposte come campi ordinati invece di una chat a testo libero.
Cosa vede il cliente: un messaggio nella chat con un pulsante Richiedi un preventivo. Il pulsante apre una schermata del modulo dentro WhatsApp, con un campo per il nome, un elenco di servizi e un selettore di data. Tocca Invia richiesta, il modulo si chiude, nella chat compare una piccola risposta "Inviato" e un attimo dopo arriva il suo messaggio di ringraziamento.
Cosa vede Lei: il flow e il suo stato nell'API, un link di anteprima per provare il modulo in un browser, gli eventi message.status per il messaggio che conteneva il modulo e un evento message.received con le risposte del cliente in data.flow.response. La risposta compare anche nell'Inbox e nell'Activity Log.
POST /flows. Parte come bozza, e la risposta elenca gli errori di validazione di WhatsApp.PUT /flows/{id}/json, prova il modulo con il suo link di anteprima e lo pubblica con POST /flows/{id}/publish.POST /messages con un messaggio interattivo flow. Fuori dalla finestra: un template approvato con un pulsante Flow.message.received con type interactive, interactive.type nfm_reply e un oggetto flow con i campi e il flow_token che ha inviato.I Flows appartengono all'intero account WhatsApp Business. Un flow che crea, modifica, pubblica o depreca è condiviso da ogni numero dello stesso account WhatsApp Business, e flow.status_changed va a ogni numero. Usi nomi che dicano a cosa serve il flow.
plan_not_allowed; un servizio in pausa risponde 403 service_not_live. Vedere Per iniziare.| Scope | A cosa serve in questa guida |
|---|---|
templates:manage | Creare un flow (POST /flows), sostituirne il Flow JSON (PUT /flows/{id}/json), pubblicarlo (POST /flows/{id}/publish), creare un nuovo link di anteprima, deprecarlo o eliminarlo. Anche creare il template con un pulsante Flow (POST /templates) |
messages:read | Leggere i flow (GET /flows, GET /flows/{id}, GET /flows/{id}/json) e il link di anteprima (GET /flows/{id}/preview) |
messages:send | Inviare il modulo e il messaggio di ringraziamento (POST /messages) |
webhooks:manage | Registrare il webhook che riceve le risposte (POST /webhooks). Può anche aggiungerlo nella pagina delle chiavi API sotto Webhooks |
La chiave Default (creata prima che le chiavi avessero i permessi) non ha templates:manage. Crei una chiave con quello scope, oppure con accesso completo (*). GET /v1/YOUR_NUMBER/me mostra gli scope della chiave che ha.
Cosa può e non può fare qui una chiave sandbox. Una chiave sandbox sul suo numero (una chiave con il flag sandbox, creata nella pagina delle chiavi API) può leggere i flow (GET /flows, GET /flows/{id}, GET /flows/{id}/json, GET /flows/{id}/preview), e POST /messages con un messaggio flow esegue ogni controllo e non invia nulla: la risposta ha "sandbox": true, l'id del messaggio inizia con wamid.SANDBOX. e gli eventi message.status arrivano comunque. Creare, modificare, pubblicare, deprecare ed eliminare flow rispondono 403 sandbox_key, perché modificano il suo account WhatsApp Business. La sandbox istantanea per il numero demo 12025550100 non ha alcuna chiamata flow (403 not_in_instant_sandbox). Quindi: crei e pubblichi il flow con una chiave normale, lo provi con il link di anteprima e testi il suo codice di invio con una chiave sandbox. Dettagli: Sandbox.
Ogni chiamata va a https://api.app2email.com/v1/YOUR_NUMBER con Authorization: Bearer YOUR_API_KEY. YOUR_NUMBER è il numero WhatsApp da cui invia: prima il prefisso internazionale, solo cifre.
Un flow è un elenco di schermate. Questo ne ha una, QUOTE, con un titolo, un breve testo, tre campi e un pulsante. L'azione complete del pulsante chiude il modulo e Le rimanda il suo payload: ${form.name} è il valore del campo chiamato name, e così via. I nomi che sceglie nel payload sono i nomi dei campi che riceve.
Lo salvi come 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}"
}
}
}
]
}
}
]
}I componenti (TextHeading, TextInput, Dropdown, DatePicker, Footer ...) e le loro proprietà sono di WhatsApp, non di app2email: app2email passa il Flow JSON a WhatsApp così com'è, e WhatsApp lo controlla. Vedere la guida di Meta ai WhatsApp Flows per ogni componente. Questo modulo non richiede alcun server suo mentre il cliente lo compila: tutto è nel JSON e le risposte tornano in un solo messaggio.
POST /flows (scope templates:manage) richiede un name (interno, i clienti non lo vedono, fino a 200 caratteri), almeno una tra le categories (SIGN_UP, SIGN_IN, APPOINTMENT_BOOKING, LEAD_GENERATION, CONTACT_US, CUSTOMER_SUPPORT, SURVEY, OTHER) e il flow_json (un oggetto o una stringa, al massimo 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"))Cosa riceve in risposta (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."
}Conservi flow.id: ogni altra chiamata e il messaggio che invia lo usano. Un validation_errors vuoto significa che WhatsApp non ha trovato nulla da correggere. Un nome già usato dall'account risponde 409 flow_name_taken.
Con "publish": true nello stesso body, un flow senza errori viene pubblicato subito. Non si può annullare, quindi questa guida pubblica in un passo separato dopo aver provato il modulo. clone_flow_id copia invece un flow esistente dello stesso account.
Quando WhatsApp trova dei problemi, il flow viene comunque creato come bozza e validation_errors elenca ciascuno con error, error_type e message di WhatsApp, il punto nel JSON (line_start, line_end, column_start, column_end) e pointers. Per esempio, dopo un errore di battitura nel type di un componente (abbreviato, il testo è di 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
}
]
}Corregga il file e invii di nuovo l'intero Flow JSON con PUT /flows/{id}/json (scope templates:manage). Il body è il Flow JSON stesso (oppure {"flow_json": {...}}), al massimo 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"])Cosa riceve in risposta:
{
"success": true,
"request_id": "f1put",
"flow_id": "1234567890123456",
"validation_errors": [],
"note": "WhatsApp found no errors. Publish with POST /flows/1234567890123456/publish (cannot be undone)."
}Un body che non è affatto JSON risponde 400 invalid_json; un flow_json che non si può leggere come Flow JSON risponde 400 invalid_flow_json. GET /flows/{id}/json restituisce il Flow JSON che WhatsApp conserva per il flow.
GET /flows/{id}/preview (scope messages:read) dà un link di anteprima valido per 30 giorni. Aggiunga &interactive=true al link per compilare il modulo Lei stesso.
curl https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/preview \
-H "Authorization: Bearer YOUR_API_KEY"Cosa riceve in risposta:
{
"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."
}Chiunque abbia il link può aprirlo, anche in un iframe. Se un link è uscito dalle sue mani, POST /flows/{id}/preview (scope templates:manage) ne crea uno nuovo e il vecchio smette subito di funzionare.
Solo un flow pubblicato può essere inviato ai clienti. POST /flows/{id}/publish (scope templates:manage, senza body) pubblica una bozza senza errori di validazione.
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())Cosa riceve in risposta:
{
"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."
}La pubblicazione non si può annullare. Il suo webhook riceve anche flow.status_changed con new_status PUBLISHED (esempio più avanti). Quando WhatsApp non lo pubblica (non è una bozza, ci sono errori di validazione o un controllo di pubblicazione è fallito), la risposta è 422 flow_cannot_publish.
Prima di inviare, GET /flows/{id} (scope messages:read) mostra lo stato, gli errori di validazione, la versione del Flow JSON e health_status, che dice se il flow può essere inviato ora:
{
"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" }]
}
}
}can_send_message è AVAILABLE, LIMITED o BLOCKED.
Dentro la finestra di 24 ore (il cliente Le ha scritto nelle ultime 24 ore, per esempio "Posso avere un preventivo?"), invii il modulo come messaggio interattivo a testo libero con POST /messages (scope messages:send):
| Parte | Cosa inserire |
|---|---|
interactive.type | flow |
header, body | Il testo sopra il pulsante. header è facoltativo |
action.name | flow |
flow_message_version | "3" |
flow_id | L'id del flow dal passo 2 |
flow_cta | Il testo del pulsante, fino a 30 caratteri |
flow_token | Un suo riferimento per questa richiesta, per es. l'id del suo lead. Torna con le risposte, così sa a quale richiesta appartengono |
flow_action, flow_action_payload.screen | navigate e l'id della prima schermata, QUOTE |
Header Idempotency-Key | Un valore unico per questo invio. La stessa richiesta con la stessa chiave entro 24 ore non viene inviata di nuovo |
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())Cosa riceve in risposta (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 significa che WhatsApp ha preso il messaggio. Conservi message_id: la risposta del cliente vi fa riferimento. Fuori dalla finestra la chiamata risponde 422 outside_24h_window.
Fuori dalla finestra di 24 ore (un lead dal suo sito web, un cliente che ha scritto la settimana scorsa), solo un template approvato può avviare la conversazione. Crei un template con un pulsante che apre un Flow, in WhatsApp Manager o con POST /templates (scope templates:manage, components nel formato proprio di WhatsApp, vedere la guida di Meta). WhatsApp lo controlla (da pochi minuti a un giorno) e template.status_changed Le dice il risultato. Poi lo invii con un componente button con sub_type flow. Il suo action contiene il 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" } }
]
}
]
}
}index è la posizione del pulsante nel template, a partire da "0". flow_token è facoltativo; senza di esso non può sapere a quale richiesta appartiene una risposta, quindi ne invii uno. action.flow_action_data passa valori alla prima schermata, per un Flow JSON la cui schermata accetta data; questo modulo non ne accetta. GET /templates (scope messages:read) elenca i suoi template e, per ognuno approvato, una richiesta di esempio completa. Se i valori del template non corrispondono, la risposta è 422 template_parameters_invalid con un example_request corretto.
message.status per il messaggio del modulo (sent, delivered, read), come per qualsiasi altro messaggio, e poi la risposta:{
"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 è ciò che il cliente ha compilato, con i nomi del suo payload, più il flow_token. La risposta di un Dropdown è l'id dell'opzione (gutter_cleaning), non il suo titolo.data.flow.token è il flow_token che ha inviato: lo usi per trovare il suo lead.in_reply_to e context.id sono il message_id del messaggio del modulo che ha inviato.data.text è un riepilogo leggibile della stessa risposta, per i log e per le persone.from_user_id e senza from. Quell'id funziona ovunque funzioni un numero.Entrambe le versioni verificano la firma, saltano gli eventi già gestiti, tengono solo le risposte Flow con un token quote-, salvano il lead e ringraziano. Imposti prima NUMBER, API_KEY e WEBHOOK_SECRET (il segreto whsec_... del suo webhook).
// 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 "", 200Per provare il ricevitore senza un cliente vero, gli invii un suo esempio: POST /webhooks/{id}/test (scope webhooks:manage) con {"event": {...}} e il body message.received qui sopra. Gli eventi di test portano "test": true e l'header X-App2email-Test: true e sono firmati come ogni evento; fino a 30 test all'ora per numero.
flow.status_changed segnala ciò che succede al flow: pubblicato, limitato, bloccato o deprecato, un avviso di endpoint o di client attivato o rimosso da Meta, oppure un avviso che la versione del suo Flow JSON scade presto. Lo riceve ogni numero dell'account WhatsApp Business.
{
"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"
}
}Faccia attenzione a new_status THROTTLED o BLOCKED e a change flow_version_expiry_warning: il suo warning dice quando la versione del Flow JSON si blocca. Dopo, il flow non può più essere inviato, quindi porti il JSON a una version più recente con PUT /flows/{id}/json e pubblichi di nuovo.
PUT /flows/{id}/json con il nuovo JSON, oppure PATCH /flows/{id} con un nuovo name, categories o endpoint_uri. Un flow pubblicato torna a DRAFT finché non lo pubblica di nuovo, e i messaggi già inviati mantengono la vecchia versione. Alcuni flow non si possono modificare (409 flow_not_editable, per esempio uno deprecato): lo copi con POST /flows e clone_flow_id, modifichi la copia e pubblichi quella.POST /flows/{id}/deprecate (scope templates:manage). Non può più essere inviato né aperto. Non si può annullare.DELETE /flows/{id} funziona solo per le bozze. Un flow pubblicato risponde 409 flow_not_deletable: lo depreci invece.GET /flows (scope messages:read) elenca ogni flow dell'account con id, nome, stato, categorie ed errori di validazione, da 1 a 100 alla volta (limit, e cursor con il next_cursor della risposta precedente).Moduli che richiedono dati in tempo reale. Il modulo di questa guida è autosufficiente. Un flow che recupera dati mentre il cliente lo compila (orari liberi, prezzi) usa un endpoint dati suo: endpoint_uri sul flow, e la chiave pubblica RSA a 2048 bit del numero impostata con PUT /flows/encryption-key (scope templates:manage; GET /flows/encryption-key la mostra). Ogni numero ha la propria chiave. Finché Book-and-Pay usa la chiave per i suoi Flow di prenotazione, impostarne un'altra risponde 409 encryption_key_managed.
Nessun Flow JSON da scrivere? app2email crea per Lei anche i moduli WhatsApp. Submit-Info trasforma un semplice elenco di domande in un modulo WhatsApp e in una pagina web (POST /submit/forms, POST /submit/forms/{key}/publish, POST /submit/forms/{key}/send, scope submissions:manage); le sue risposte arrivano come submission.created. La sezione Book-and-Pay ha un modulo di prenotazione e altri moduli che invia con POST /flows/{key}/send (scope bookings:manage); un Flow modulo di quella sezione segnala flow.completed, un Flow di prenotazione booking.created. I Flow che crea con POST /flows segnalano le loro risposte come message.received, come mostrato sopra.
Verifichi ogni evento. Controlli X-App2email-Signature (t=<unix seconds>,v1=<hex>, l'HMAC-SHA256 di t, un punto e il body grezzo, con il segreto whsec_... del webhook) sul body grezzo, prima di interpretarlo. Controlli ogni v1=, confronti in tempo costante e rifiuti un t più vecchio di 5 minuti.
Elimini i duplicati con id veri. Conservi l'id dell'evento (anche in X-App2email-Delivery) di ogni evento gestito per almeno due giorni: un evento fallito viene inviato di nuovo per circa 32 ore. Memorizzi un solo lead per flow_token, così un cliente che invia lo stesso modulo due volte aggiorna la sua richiesta invece di crearne una seconda.
Invii ogni messaggio una sola volta. Dia a ogni POST /messages un Idempotency-Key (per il modulo: l'id del suo lead; per il ringraziamento: il message_id della risposta). La stessa chiave e lo stesso body entro 24 ore restituiscono la prima risposta con Idempotent-Replayed: true. La stessa chiave con un altro body: 422 idempotency_key_reused. 409 idempotency_request_in_progress: attenda e riprovi con la stessa chiave.
Risponda in fretta. Restituisca 2xx entro 10 secondi; i reindirizzamenti non vengono seguiti. Per il lavoro lento, memorizzi l'evento, risponda 200 e lo elabori da una coda.
Rispetti i limiti. Ogni risposta ha X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset e X-RateLimit-Policy. Oltre il limite: 429 rate_limited con Retry-After; attenda, poi invii di nuovo. I limiti propri di WhatsApp (429 whatsapp_rate_limit, too_many_messages_to_recipient) richiedono minuti. Ogni messaggio modulo conta come un messaggio del suo piano.
Tenga conto della finestra di 24 ore. Il messaggio modulo interattivo è a testo libero: va solo a un cliente che ha scritto nelle ultime 24 ore (app2email si ferma 15 minuti prima; window_closes_at è l'orario esatto). Tutti gli altri ricevono il template approvato con il pulsante Flow.
Opt-in e Do Not Call. Se il template con il pulsante Flow è un template di marketing, segue le stesse regole di qualsiasi template di marketing: un cliente nella sua lista Do Not Call risponde 403 recipient_opted_out, e un numero che richiede un opt-in risponde 403 recipient_not_opted_in per un cliente che non ne ha uno. I template utility si possono comunque inviare. Vedere Inviare un broadcast di marketing che rispetta gli opt-in.
Tratti le risposte come dati. Le ha scritte il cliente. Controlli ogni campo (un id di servizio noto, una data reale, una lunghezza sensata) prima che finisca nel suo database, e non lo esegua mai come comando né lo passi a un modello AI mescolato alle sue istruzioni.
Modifichi i flow con cautela. I Flows sono condivisi da ogni numero dell'account WhatsApp Business, e una modifica a un flow pubblicato lo riporta a DRAFT finché non pubblica di nuovo. Tenga il Flow JSON nel suo controllo di versione, provi le modifiche con il link di anteprima e controlli flow.status_changed.
Accesso minimo. Il ricevitore richiede solo messages:send (per il ringraziamento). Tenga templates:manage su una chiave separata che usano solo i suoi script di configurazione. Tenga le chiavi sul server, mai in una pagina web o in un log.
| Cosa vede | Perché | Soluzione |
|---|---|---|
403 insufficient_scope | Alla chiave manca un permesso (details.required_scope) | Crei una chiave con templates:manage per creare i flow e messages:send per inviarli |
403 sandbox_key | Una chiave sandbox non può creare, modificare o pubblicare flow | Usi una chiave normale per queste chiamate; tenga la chiave sandbox per testare POST /messages |
403 not_in_instant_sandbox | Il numero demo 12025550100 non ha chiamate flow | Usi il suo numero collegato |
400 invalid_flow_name | name è vuoto o più lungo di 200 caratteri | Invii un breve nome interno, per es. quote_request |
400 invalid_flow_categories | categories manca o ha un valore sconosciuto | Invii un elenco con almeno una categoria, per es. ["LEAD_GENERATION"] |
400 invalid_flow_json, invalid_json | Il Flow JSON o il body non è un JSON valido, o non è un oggetto | Controlli parentesi, virgolette e virgole; invii il Flow JSON come oggetto |
400 invalid_flow_field | Un campo ha il tipo di valore sbagliato, per es. publish non è true o false | Usi i campi name, categories, flow_json, publish, endpoint_uri, clone_flow_id |
400 invalid_flow_id, 404 flow_not_found | L'id nell'indirizzo non è un flow di questo account | GET /flows elenca gli id |
404 flow_json_not_found | Il flow non ha ancora un Flow JSON | Lo carichi con PUT /flows/{id}/json |
validation_errors non vuoto | WhatsApp ha trovato problemi nel Flow JSON | Corregga ciascuno alla sua riga e colonna, poi di nuovo PUT /flows/{id}/json |
409 flow_name_taken | L'account ha già un flow con questo nome | Scelga un altro nome |
413 flow_json_too_large | Il Flow JSON supera il limite di 10 MB di WhatsApp | Lo riduca |
422 flow_cannot_publish | Il flow non è una bozza, ha errori di validazione o un controllo di pubblicazione è fallito | GET /flows/{id} mostra validation_errors e health_status; li corregga e pubblichi di nuovo |
422 flow_rejected | WhatsApp non ha accettato la richiesta | Legga whatsapp_error nella risposta, corregga la richiesta e la invii di nuovo |
409 flow_not_editable | WhatsApp non permette di modificare questo flow | Lo copi con clone_flow_id, modifichi la copia e pubblichi quella |
409 flow_not_deletable | Un flow pubblicato non può essere eliminato | Lo depreci con POST /flows/{id}/deprecate |
409 flow_not_published | Solo un flow pubblicato può essere deprecato | Niente da deprecare; una bozza si può eliminare |
409 encryption_key_managed | Book-and-Pay usa la chiave di crittografia Flow del numero | Lasci la chiave com'è; un flow con un endpoint dati suo richiede un numero senza Book-and-Pay |
403 flow_blocked_by_integrity | Meta blocca la creazione o la pubblicazione di flow su questo account WhatsApp | Contatti il supporto Meta tramite WhatsApp Manager |
403 whatsapp_permission_missing | Meta non ha dato ad app2email il permesso che serve per il suo account | Riprovare non aiuta; contatti support@app2email.com |
422 outside_24h_window | Il cliente ha scritto l'ultima volta più di 24 ore fa | Invii invece il template approvato con il pulsante Flow |
404 template_not_found, 422 template_not_approved | Il nome o la lingua del template è sbagliato, oppure non è ancora approvato | Ne scelga uno da GET /templates con stato APPROVED |
422 template_parameters_invalid | Il componente del pulsante non corrisponde al template | Confronti con l'example_request nella risposta |
400 invalid_interactive | La parte interattiva non è valida (il tipo o la lunghezza di un testo) | Controlli interactive.type flow, gli action.parameters e tenga flow_cta entro 30 caratteri |
429 rate_limited | Troppe chiamate per questa chiave | Attenda Retry-After secondi, poi riprovi |
502 whatsapp_error | WhatsApp ha rifiutato la richiesta con un errore senza codice proprio | Legga whatsapp_error; riprovi più tardi e, se continua a fallire, invii il request_id al supporto |
| Il modulo si apre, ma non arriva alcuna risposta | Il webhook è disattivato, oppure il suo ricevitore scarta l'evento | GET /webhooks mostra active e l'ultima consegna; GET /webhooks/{id}/deliveries?status=failed mostra cosa è fallito |
Ogni risposta ha un request_id. GET /requests/{id} mostra cosa è stato registrato per essa, e anche support@app2email.com può trovarlo. Tutti i codici: Errori.
Sì. Il server MCP https://api.app2email.com/mcp/flows ha le stesse chiamate come strumenti: list_flows, get_flow, create_flow, update_flow, get_flow_json, update_flow_json, publish_flow, deprecate_flow, delete_flow, get_flow_preview e renew_flow_preview. Vedere Lasci che un agente AI gestisca il suo WhatsApp con MCP e MCP.
Il messaggio modulo interattivo va a un contatto per chiamata, dentro la sua finestra. Per raggiungere molti clienti, invii il template approvato con il pulsante Flow, per esempio come broadcast a un segmento, e segua le regole dell'opt-in per i template di marketing. Dia a ogni cliente il suo flow_token se Le serve abbinare le risposte alle persone.
I messaggi già inviati mantengono la versione del flow con cui sono stati inviati. Una modifica ha effetto sui nuovi messaggi dopo che pubblica di nuovo. Un flow deprecato non può più essere inviato né aperto.
Sì: un webhook con "format": "meta" riceve ciò che arriva da WhatsApp come body proprio di Meta (entry[].changes[]), firmato allo stesso modo. Nel formato predefinito di app2email la risposta è già scomposta in data.flow, come mostrato sopra. data.whatsapp contiene inoltre l'oggetto messaggio di Meta senza modifiche.
Slot liberi, prenotazioni e promemoria tramite l'API Book-and-Pay.
Riceva i messaggi su un webhook firmato e risponda dal suo codice.
Template approvati per i messaggi fuori dalla finestra di 24 ore, con stato di consegna.
Metta i lead raccolti dal suo modulo accanto al resto dei dati dei suoi clienti.