app2email API Prezzi

Documentazione

Raccogliere dati con un modulo WhatsApp Flow

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.

Come funziona

  1. Descrive il modulo in Flow JSON (il formato proprio di WhatsApp per i Flows) e lo crea con POST /flows. Parte come bozza, e la risposta elenca gli errori di validazione di WhatsApp.
  2. Corregge gli eventuali errori con PUT /flows/{id}/json, prova il modulo con il suo link di anteprima e lo pubblica con POST /flows/{id}/publish.
  3. Invia il modulo. Dentro la finestra di 24 ore del cliente: POST /messages con un messaggio interattivo flow. Fuori dalla finestra: un template approvato con un pulsante Flow.
  4. Il cliente lo compila. Il suo webhook riceve message.received con type interactive, interactive.type nfm_reply e un oggetto flow con i campi e il flow_token che ha inviato.
Note

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.

Cosa serve

  • Un numero WhatsApp collegato ad app2email, con un piano a pagamento e attivo. Senza un piano ogni chiamata risponde 403 plan_not_allowed; un servizio in pausa risponde 403 service_not_live. Vedere Per iniziare.
  • Una chiave API dalla pagina delle chiavi API con questi scope:
ScopeA cosa serve in questa guida
templates:manageCreare 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:readLeggere i flow (GET /flows, GET /flows/{id}, GET /flows/{id}/json) e il link di anteprima (GET /flows/{id}/preview)
messages:sendInviare il modulo e il messaggio di ringraziamento (POST /messages)
webhooks:manageRegistrare 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.

Warning

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.

Creare e inviare il modulo

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.

  1. 1. Scriva il modulo in Flow JSON

    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:

    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.

  2. 2. Crei il flow come bozza

    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).

    cURL
    # 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 @-
    Node.js
    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);
    Python
    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.

  3. 3. Corregga gli errori di validazione

    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
    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.json
    Node.js
    const 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);
    Python
    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.

  4. 4. Provi il modulo prima che lo veda qualcun altro

    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.

  5. 5. Pubblichi il flow

    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
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/publish \
      -H "Authorization: Bearer YOUR_API_KEY"
    Node.js
    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());
    Python
    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.

  6. 6. Invii il modulo a un cliente

    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):

    ParteCosa inserire
    interactive.typeflow
    header, bodyIl testo sopra il pulsante. header è facoltativo
    action.nameflow
    flow_message_version"3"
    flow_idL'id del flow dal passo 2
    flow_ctaIl testo del pulsante, fino a 30 caratteri
    flow_tokenUn 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.screennavigate e l'id della prima schermata, QUOTE
    Header Idempotency-KeyUn valore unico per questo invio. La stessa richiesta con la stessa chiave entro 24 ore non viene inviata di nuovo
    cURL
    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" }
            }
          }
        }
      }'
    Node.js
    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());
    Python
    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.

Il risultato

  1. Il cliente tocca Richiedi un preventivo. Il modulo si apre dentro WhatsApp.
  2. Scrive il suo nome, sceglie Pulizia grondaie, seleziona il 3 dicembre e tocca Invia richiesta.
  3. Il modulo si chiude e nella chat compare una risposta "Inviato" al suo messaggio. Nell'Inbox e nell'Activity Log vede la risposta.
  4. Il suo webhook riceve gli eventi 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.
  • Un cliente che usa un nome utente WhatsApp può arrivare con from_user_id e senza from. Quell'id funziona ovunque funzioni un numero.

Ricevere le risposte nel codice

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 (Express)
server.mjs
// 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 (Flask)
server.py
# 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 "", 200

Per 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.

Modifiche al flow stesso

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.

Modificare, ritirare o eliminare un flow

  • Modificare il modulo: 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.
  • Ritirarlo: POST /flows/{id}/deprecate (scope templates:manage). Non può più essere inviato né aperto. Non si può annullare.
  • Eliminarlo: DELETE /flows/{id} funziona solo per le bozze. Un flow pubblicato risponde 409 flow_not_deletable: lo depreci invece.
  • Elencarli: 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).
Info

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.

Tip

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.

Checklist per la produzione

Done

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.

Done

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.

Done

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.

Done

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.

Done

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.

Done

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.

Done

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.

Done

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.

Done

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.

Done

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.

Se non funziona

Cosa vedePerchéSoluzione
403 insufficient_scopeAlla chiave manca un permesso (details.required_scope)Crei una chiave con templates:manage per creare i flow e messages:send per inviarli
403 sandbox_keyUna chiave sandbox non può creare, modificare o pubblicare flowUsi una chiave normale per queste chiamate; tenga la chiave sandbox per testare POST /messages
403 not_in_instant_sandboxIl numero demo 12025550100 non ha chiamate flowUsi il suo numero collegato
400 invalid_flow_namename è vuoto o più lungo di 200 caratteriInvii un breve nome interno, per es. quote_request
400 invalid_flow_categoriescategories manca o ha un valore sconosciutoInvii un elenco con almeno una categoria, per es. ["LEAD_GENERATION"]
400 invalid_flow_json, invalid_jsonIl Flow JSON o il body non è un JSON valido, o non è un oggettoControlli parentesi, virgolette e virgole; invii il Flow JSON come oggetto
400 invalid_flow_fieldUn campo ha il tipo di valore sbagliato, per es. publish non è true o falseUsi i campi name, categories, flow_json, publish, endpoint_uri, clone_flow_id
400 invalid_flow_id, 404 flow_not_foundL'id nell'indirizzo non è un flow di questo accountGET /flows elenca gli id
404 flow_json_not_foundIl flow non ha ancora un Flow JSONLo carichi con PUT /flows/{id}/json
validation_errors non vuotoWhatsApp ha trovato problemi nel Flow JSONCorregga ciascuno alla sua riga e colonna, poi di nuovo PUT /flows/{id}/json
409 flow_name_takenL'account ha già un flow con questo nomeScelga un altro nome
413 flow_json_too_largeIl Flow JSON supera il limite di 10 MB di WhatsAppLo riduca
422 flow_cannot_publishIl flow non è una bozza, ha errori di validazione o un controllo di pubblicazione è fallitoGET /flows/{id} mostra validation_errors e health_status; li corregga e pubblichi di nuovo
422 flow_rejectedWhatsApp non ha accettato la richiestaLegga whatsapp_error nella risposta, corregga la richiesta e la invii di nuovo
409 flow_not_editableWhatsApp non permette di modificare questo flowLo copi con clone_flow_id, modifichi la copia e pubblichi quella
409 flow_not_deletableUn flow pubblicato non può essere eliminatoLo depreci con POST /flows/{id}/deprecate
409 flow_not_publishedSolo un flow pubblicato può essere deprecatoNiente da deprecare; una bozza si può eliminare
409 encryption_key_managedBook-and-Pay usa la chiave di crittografia Flow del numeroLasci la chiave com'è; un flow con un endpoint dati suo richiede un numero senza Book-and-Pay
403 flow_blocked_by_integrityMeta blocca la creazione o la pubblicazione di flow su questo account WhatsAppContatti il supporto Meta tramite WhatsApp Manager
403 whatsapp_permission_missingMeta non ha dato ad app2email il permesso che serve per il suo accountRiprovare non aiuta; contatti support@app2email.com
422 outside_24h_windowIl cliente ha scritto l'ultima volta più di 24 ore faInvii invece il template approvato con il pulsante Flow
404 template_not_found, 422 template_not_approvedIl nome o la lingua del template è sbagliato, oppure non è ancora approvatoNe scelga uno da GET /templates con stato APPROVED
422 template_parameters_invalidIl componente del pulsante non corrisponde al templateConfronti con l'example_request nella risposta
400 invalid_interactiveLa 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_limitedTroppe chiamate per questa chiaveAttenda Retry-After secondi, poi riprovi
502 whatsapp_errorWhatsApp ha rifiutato la richiesta con un errore senza codice proprioLegga whatsapp_error; riprovi più tardi e, se continua a fallire, invii il request_id al supporto
Il modulo si apre, ma non arriva alcuna rispostaIl webhook è disattivato, oppure il suo ricevitore scarta l'eventoGET /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.

FAQ

Un agente AI può creare e gestire i flow?

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.

Posso inviare il modulo a molti clienti in una volta?

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.

Cosa succede ai clienti che hanno ancora una versione più vecchia?

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.

Posso ottenere il formato webhook proprio di Meta?

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.

Altre guide pratiche

Tutte le guide pratiche