# Collect details with a WhatsApp Flow form

> Create a WhatsApp Flow with the API, check and publish it, send it to a customer inside the chat or with a template button, and receive the filled-in fields on your webhook.

In this guide you build a quote request form that opens inside WhatsApp. The customer gives their name, picks a service and chooses a preferred date, and your system gets the answers as clean fields instead of a free-text chat.

**What the customer sees:** a message in the chat with a **Request a quote** button. The button opens a form screen inside WhatsApp, with a name field, a list of services and a date picker. They tap **Send request**, the form closes, a small "Sent" reply appears in the chat, and a moment later your thank-you message arrives.

**What you see:** the flow and its status in the API, a preview link to try the form in a browser, `message.status` events for the message that carried the form, and one `message.received` event with the customer's answers in `data.flow.response`. The answer also shows in the Inbox and the Activity Log.

## How it works

1. You describe the form in **Flow JSON** (WhatsApp's own format for Flows) and create it with `POST /flows`. It starts as a draft, and the answer lists WhatsApp's validation errors.
2. You fix any errors with `PUT /flows/{id}/json`, try the form with its preview link, and publish it with `POST /flows/{id}/publish`.
3. You send the form. Inside the customer's 24 hour window: `POST /messages` with an interactive `flow` message. Outside it: an approved template with a Flow button.
4. The customer fills it in. Your webhook gets `message.received` with `type` `interactive`, `interactive.type` `nfm_reply` and a `flow` object holding the fields and the `flow_token` you sent.

<Note>
**Flows belong to the whole WhatsApp Business Account.** A flow you create, change, publish or deprecate is shared by every number on the same WhatsApp Business Account, and `flow.status_changed` goes to every number. Use names that say what the flow is for.
</Note>

## What you need

- **A WhatsApp number connected to app2email**, on a paid plan and live. Without a plan every call answers 403 `plan_not_allowed`; a paused service answers 403 `service_not_live`. See [Getting started](https://www.app2email.com/docs/onboarding).
- **An API key** from [the API key page](https://www.app2email.com/dashboard/apikey) with these scopes:

| Scope | What it is for in this guide |
| --- | --- |
| `templates:manage` | Create a flow (`POST /flows`), replace its Flow JSON (`PUT /flows/{id}/json`), publish it (`POST /flows/{id}/publish`), make a new preview link, deprecate or delete it. Also creating the template with a Flow button (`POST /templates`) |
| `messages:read` | Read flows (`GET /flows`, `GET /flows/{id}`, `GET /flows/{id}/json`) and the preview link (`GET /flows/{id}/preview`) |
| `messages:send` | Send the form and the thank-you message (`POST /messages`) |
| `webhooks:manage` | Register the webhook that receives the answers (`POST /webhooks`). You can also add it on the API key page under Webhooks |

The Default key (made before keys had permissions) does not have `templates:manage`. Create a key with that scope, or with Full access (`*`). `GET /v1/YOUR_NUMBER/me` shows the scopes of the key you have.

- **A webhook URL** that checks the signature. If you do not have one yet, [Build a WhatsApp chatbot with the API](/guides/how-to-whatsapp-chatbot) sets one up in four steps, with a tunnel for your own computer.

<Warning>
**What a sandbox key can and cannot do here.** A sandbox key on your own number (a key with the sandbox flag, made on the API key page) can **read** flows (`GET /flows`, `GET /flows/{id}`, `GET /flows/{id}/json`, `GET /flows/{id}/preview`), and `POST /messages` with a flow message runs every check and sends nothing: the answer has `"sandbox": true`, the message id starts with `wamid.SANDBOX.`, and `message.status` events still arrive. Creating, changing, publishing, deprecating and deleting flows answer 403 `sandbox_key`, because they change your WhatsApp Business Account. The instant sandbox for the demo number `12025550100` has no flow calls at all (403 `not_in_instant_sandbox`). So: build and publish the flow with a normal key, try it with the preview link, and test your sending code with a sandbox key. Details: [Sandbox](/api/sandbox).
</Warning>

## Build and send the form

Every call goes to `https://api.app2email.com/v1/YOUR_NUMBER` with `Authorization: Bearer YOUR_API_KEY`. `YOUR_NUMBER` is the WhatsApp number you send from: country code first, digits only.

<Steps>
  <Step title="Write the form in Flow JSON">
    A flow is a list of screens. This one has one screen, `QUOTE`, with a heading, a short text, three fields and a button. The button's `complete` action closes the form and sends its `payload` back to you: `${form.name}` is the value of the field called `name`, and so on. The names you choose in the payload are the field names you receive.

    Save it as `quote-request.json`:

    ```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}"
                  }
                }
              }
            ]
          }
        }
      ]
    }
    ```

    The components (`TextHeading`, `TextInput`, `Dropdown`, `DatePicker`, `Footer` ...) and their properties are WhatsApp's, not app2email's: app2email passes the Flow JSON to WhatsApp as it is, and WhatsApp checks it. See [Meta's guide to WhatsApp Flows](https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/guides/sendingaflow) for every component. This form needs no server of your own while the customer fills it in: everything is in the JSON, and the answers come back in one message.
  </Step>
  <Step title="Create the flow as a draft">
    `POST /flows` (scope `templates:manage`) takes a `name` (internal, customers do not see it, up to 200 characters), at least one of the `categories` (`SIGN_UP`, `SIGN_IN`, `APPOINTMENT_BOOKING`, `LEAD_GENERATION`, `CONTACT_US`, `CUSTOMER_SUPPORT`, `SURVEY`, `OTHER`) and the `flow_json` (an object or a string, at most 10 MB).

    <CodeGroup>

    ```bash 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 @-
    ```

    ```javascript 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 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"))
    ```

    </CodeGroup>

    **What you get back** (201 Created):

    ```json
    {
      "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."
    }
    ```

    Keep `flow.id`: every other call and the message you send use it. An empty `validation_errors` means WhatsApp found nothing to fix. A name the account already uses answers 409 `flow_name_taken`.

    With `"publish": true` in the same body, a flow without errors is published at once. That cannot be undone, so this guide publishes in a separate step after trying the form. `clone_flow_id` copies an existing flow of the same account instead.
  </Step>
  <Step title="Fix the validation errors">
    When WhatsApp finds problems, the flow is still created as a draft, and `validation_errors` lists each one with WhatsApp's `error`, `error_type` and `message`, the place in the JSON (`line_start`, `line_end`, `column_start`, `column_end`) and `pointers`. For example, after a typing mistake in a component's `type` (shortened, the text is WhatsApp's):

    ```json
    {
      "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
        }
      ]
    }
    ```

    Correct the file and send the whole Flow JSON again with `PUT /flows/{id}/json` (scope `templates:manage`). The body is the Flow JSON itself (or `{"flow_json": {...}}`), at most 10 MB.

    <CodeGroup>

    ```bash 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
    ```

    ```javascript 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 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"])
    ```

    </CodeGroup>

    **What you get back:**

    ```json
    {
      "success": true,
      "request_id": "f1put",
      "flow_id": "1234567890123456",
      "validation_errors": [],
      "note": "WhatsApp found no errors. Publish with POST /flows/1234567890123456/publish (cannot be undone)."
    }
    ```

    A body that is not JSON at all answers 400 `invalid_json`; a `flow_json` that cannot be read as Flow JSON answers 400 `invalid_flow_json`. `GET /flows/{id}/json` gives back the Flow JSON WhatsApp keeps for the flow.
  </Step>
  <Step title="Try the form before anyone else sees it">
    `GET /flows/{id}/preview` (scope `messages:read`) gives a preview link that works for 30 days. Add `&interactive=true` to the link to fill the form in yourself.

    ```bash
    curl https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/preview \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```

    **What you get back:**

    ```json
    {
      "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."
    }
    ```

    Anyone with the link can open it, also in an iframe. If a link got out, `POST /flows/{id}/preview` (scope `templates:manage`) makes a new one, and the old one stops working at once.
  </Step>
  <Step title="Publish the flow">
    Only a published flow can be sent to customers. `POST /flows/{id}/publish` (scope `templates:manage`, no body) publishes a draft without validation errors.

    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/flows/1234567890123456/publish \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```

    ```javascript 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 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())
    ```

    </CodeGroup>

    **What you get back:**

    ```json
    {
      "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."
    }
    ```

    Publishing cannot be undone. Your webhook also gets `flow.status_changed` with `new_status` `PUBLISHED` (sample below). When WhatsApp does not publish it (not a draft, validation errors, or a failed publishing check), the answer is 422 `flow_cannot_publish`.

    Before you send, `GET /flows/{id}` (scope `messages:read`) shows the status, the validation errors, the Flow JSON version and `health_status`, which says whether the flow can be sent now:

    ```json
    {
      "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` is `AVAILABLE`, `LIMITED` or `BLOCKED`.
  </Step>
  <Step title="Send the form to a customer">
    **Inside the 24 hour window** (the customer wrote to you in the last 24 hours, for example "Can I get a quote?"), send the form as a free-form interactive message with `POST /messages` (scope `messages:send`):

    | Part | What to fill in |
    | --- | --- |
    | `interactive.type` | `flow` |
    | `header`, `body` | The text above the button. `header` is optional |
    | `action.name` | `flow` |
    | `flow_message_version` | `"3"` |
    | `flow_id` | The flow's id from step 2 |
    | `flow_cta` | The button text, up to 30 characters |
    | `flow_token` | Your own reference for this request, eg your lead id. It comes back with the answers, so you know which request they belong to |
    | `flow_action`, `flow_action_payload.screen` | `navigate` and the first screen's id, `QUOTE` |
    | `Idempotency-Key` header | A value unique to this send. The same request with the same key within 24 hours is not sent again |

    <CodeGroup>

    ```bash 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" }
            }
          }
        }
      }'
    ```

    ```javascript 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 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())
    ```

    </CodeGroup>

    **What you get back** (200):

    ```json
    {
      "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` means WhatsApp took the message. Keep `message_id`: the customer's answer refers to it. Outside the window the call answers 422 `outside_24h_window`.

    **Outside the 24 hour window** (a lead from your website, a customer who wrote last week), only an approved template can start the conversation. Make a template with a button that opens a Flow, in WhatsApp Manager or with `POST /templates` (scope `templates:manage`, `components` in WhatsApp's own format, see [Meta's guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/guides/sendingaflow)). WhatsApp reviews it (minutes to a day), and `template.status_changed` tells you the result. Then send it with a `button` component of `sub_type` `flow`. Its `action` carries the `flow_token`:

    ```json
    {
      "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` is the button's position in the template, from `"0"`. `flow_token` is optional; without it you cannot tell which request an answer belongs to, so send one. `action.flow_action_data` passes values to the first screen, for a Flow JSON whose screen takes `data`; this form takes none. `GET /templates` (scope `messages:read`) lists your templates, and for each approved one a complete example request. If the template's values do not match, the answer is 422 `template_parameters_invalid` with a correct `example_request`.
  </Step>
</Steps>

## The result

1. The customer taps **Request a quote**. The form opens inside WhatsApp.
2. They type their name, pick **Gutter cleaning**, choose 3 December and tap **Send request**.
3. The form closes, and a "Sent" reply to your message shows in the chat. In the Inbox and the Activity Log you see the answer.
4. Your webhook gets `message.status` events for the form message (`sent`, `delivered`, `read`), like any other message, and then the answer:

```json
{
  "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` is what the customer filled in, under the names of your `payload`, plus the `flow_token`. A `Dropdown` answer is the `id` of the option (`gutter_cleaning`), not its title.
- `data.flow.token` is the `flow_token` you sent: use it to find your lead.
- `in_reply_to` and `context.id` are the `message_id` of the form message you sent.
- `data.text` is a readable summary of the same answer, for logs and people.
- A customer who uses a WhatsApp username may come with `from_user_id` and no `from`. That id works wherever a number does.

### Receive the answers in code

Both versions verify the signature, skip events they have already handled, keep only Flow answers with a `quote-` token, save the lead and say thank you. Set `NUMBER`, `API_KEY` and `WEBHOOK_SECRET` (the `whsec_...` secret of your webhook) first.

<Tabs>
  <Tab title="Node.js (Express)">

```javascript 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`));
```

  </Tab>
  <Tab title="Python (Flask)">

```python 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
```

  </Tab>
</Tabs>

To try the receiver without a real customer, send it your own sample: `POST /webhooks/{id}/test` (scope `webhooks:manage`) with `{"event": {...}}` and the `message.received` body above. Test events carry `"test": true` and the header `X-App2email-Test: true`, and are signed like every event; up to 30 tests an hour per number.

### Changes to the flow itself

`flow.status_changed` reports what happens to the flow: published, throttled, blocked or deprecated, an endpoint or client alert raised or cleared by Meta, or a warning that its Flow JSON version expires soon. Every number on the WhatsApp Business Account gets it.

```json
{
  "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"
  }
}
```

Watch for `new_status` `THROTTLED` or `BLOCKED`, and for `change` `flow_version_expiry_warning`: its `warning` says when the Flow JSON version freezes. After that the flow can no longer be sent, so move the JSON to a newer `version` with `PUT /flows/{id}/json` and publish again.

## Change, retire or delete a flow

- **Change the form:** `PUT /flows/{id}/json` with the new JSON, or `PATCH /flows/{id}` with a new `name`, `categories` or `endpoint_uri`. A published flow goes back to `DRAFT` until you publish it again, and messages already sent keep the old version. Some flows cannot be changed (409 `flow_not_editable`, for example a deprecated one): copy it with `POST /flows` and `clone_flow_id`, change the copy and publish that.
- **Retire it:** `POST /flows/{id}/deprecate` (scope `templates:manage`). It can no longer be sent or opened. This cannot be undone.
- **Delete it:** `DELETE /flows/{id}` works for drafts only. A published flow answers 409 `flow_not_deletable`: deprecate it instead.
- **List them:** `GET /flows` (scope `messages:read`) lists every flow of the account with its id, name, status, categories and validation errors, 1 to 100 at a time (`limit`, and `cursor` with the `next_cursor` of the previous answer).

<Info>
**Forms that need live data.** This guide's form is self-contained. A flow that fetches data while the customer fills it in (free times, prices) uses a data endpoint of yours: `endpoint_uri` on the flow, and the number's 2048-bit RSA public key set with `PUT /flows/encryption-key` (scope `templates:manage`; `GET /flows/encryption-key` shows it). Each number has its own key. While Book-and-Pay uses the key for its booking Flows, setting another answers 409 `encryption_key_managed`.
</Info>

<Tip>
**No Flow JSON to write?** app2email also builds WhatsApp forms for you. **Submit-Info** turns a plain list of questions into a WhatsApp form and a web page (`POST /submit/forms`, `POST /submit/forms/{key}/publish`, `POST /submit/forms/{key}/send`, scope `submissions:manage`); its answers arrive as `submission.created`. The **Book-and-Pay** section has a booking form and other forms you send with `POST /flows/{key}/send` (scope `bookings:manage`); a form Flow of that section reports `flow.completed`, a booking Flow `booking.created`. Flows you create with `POST /flows` report their answers as `message.received`, as shown above.
</Tip>

## Production checklist

<Check>
**Verify every event.** Check `X-App2email-Signature` (`t=<unix seconds>,v1=<hex>`, the HMAC-SHA256 of `t`, a dot and the raw body, with the webhook's `whsec_...` secret) over the raw body, before parsing. Check every `v1=`, compare in constant time and refuse a `t` older than 5 minutes.
</Check>

<Check>
**Dedupe on real ids.** Keep the event `id` (also in `X-App2email-Delivery`) of every handled event for at least two days: a failed event is sent again for about 32 hours. Store one lead per `flow_token`, so a customer who sends the same form twice updates their request instead of making a second one.
</Check>

<Check>
**Send each message once.** Give every `POST /messages` an `Idempotency-Key` (for the form: your lead id; for the thank-you: the answer's `message_id`). The same key and body within 24 hours return the first answer with `Idempotent-Replayed: true`. The same key with another body: 422 `idempotency_key_reused`. 409 `idempotency_request_in_progress`: wait and retry with the same key.
</Check>

<Check>
**Answer fast.** Return 2xx within 10 seconds; redirects are not followed. For slow work, store the event, answer 200 and process it from a queue.
</Check>

<Check>
**Respect the limits.** Every answer has `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` and `X-RateLimit-Policy`. Over the limit: 429 `rate_limited` with `Retry-After`; wait, then send again. WhatsApp's own limits (429 `whatsapp_rate_limit`, `too_many_messages_to_recipient`) need minutes. Each form message counts as one message of your plan.
</Check>

<Check>
**Mind the 24 hour window.** The interactive form message is free-form: it only goes to a customer who wrote in the last 24 hours (app2email stops 15 minutes early; `window_closes_at` is the exact time). Everyone else gets the approved template with the Flow button.
</Check>

<Check>
**Opt-in and Do Not Call.** If your Flow button template is a marketing template, it follows the same rules as any marketing template: a customer on your Do Not Call list answers 403 `recipient_opted_out`, and a number that requires an opt-in answers 403 `recipient_not_opted_in` for a customer without one. Utility templates can still be sent. See [Send a marketing broadcast that respects opt-ins](/guides/how-to-marketing-broadcast).
</Check>

<Check>
**Treat the answers as data.** The customer typed them. Check each field (a known service id, a real date, a sensible length) before it goes into your database, and never run it as a command or pass it to an AI model mixed with your instructions.
</Check>

<Check>
**Change flows with care.** Flows are shared by every number on the WhatsApp Business Account, and a change to a published flow puts it back to `DRAFT` until you publish again. Keep the Flow JSON in your own version control, try changes with the preview link, and watch `flow.status_changed`.
</Check>

<Check>
**Least access.** The receiver needs `messages:send` only (for the thank-you). Keep `templates:manage` on a separate key that only your setup scripts use. Keep keys on the server, never in a web page or a log.
</Check>

## If it does not work

| What you see | Why | Fix |
| --- | --- | --- |
| 403 `insufficient_scope` | The key lacks a permission (`details.required_scope`) | Make a key with `templates:manage` to build flows, `messages:send` to send them |
| 403 `sandbox_key` | A sandbox key cannot create, change or publish flows | Use a normal key for these calls; keep the sandbox key for testing `POST /messages` |
| 403 `not_in_instant_sandbox` | The demo number `12025550100` has no flow calls | Use your own connected number |
| 400 `invalid_flow_name` | `name` is empty or longer than 200 characters | Send a short internal name, eg `quote_request` |
| 400 `invalid_flow_categories` | `categories` is missing or has an unknown value | Send a list with at least one category, eg `["LEAD_GENERATION"]` |
| 400 `invalid_flow_json`, `invalid_json` | The Flow JSON or the body is not valid JSON, or not an object | Check brackets, quotes and commas; send the Flow JSON as an object |
| 400 `invalid_flow_field` | A field has the wrong kind of value, eg `publish` is not true or false | Use the fields `name`, `categories`, `flow_json`, `publish`, `endpoint_uri`, `clone_flow_id` |
| 400 `invalid_flow_id`, 404 `flow_not_found` | The id in the address is not a flow of this account | `GET /flows` lists the ids |
| 404 `flow_json_not_found` | The flow has no Flow JSON yet | Upload it with `PUT /flows/{id}/json` |
| `validation_errors` not empty | WhatsApp found problems in the Flow JSON | Fix each one at its line and column, then `PUT /flows/{id}/json` again |
| 409 `flow_name_taken` | The account already has a flow with this name | Choose another name |
| 413 `flow_json_too_large` | The Flow JSON is over WhatsApp's 10 MB limit | Make it smaller |
| 422 `flow_cannot_publish` | The flow is not a draft, has validation errors, or failed a publishing check | `GET /flows/{id}` shows `validation_errors` and `health_status`; fix them and publish again |
| 422 `flow_rejected` | WhatsApp did not accept the request | Read `whatsapp_error` in the answer, fix the request and send it again |
| 409 `flow_not_editable` | WhatsApp does not let this flow be changed | Copy it with `clone_flow_id`, change the copy and publish that |
| 409 `flow_not_deletable` | A published flow cannot be deleted | Deprecate it with `POST /flows/{id}/deprecate` |
| 409 `flow_not_published` | Only a published flow can be deprecated | Nothing to deprecate; a draft can be deleted |
| 409 `encryption_key_managed` | Book-and-Pay uses the number's Flow encryption key | Leave the key as it is; a flow with your own data endpoint needs a number without Book-and-Pay |
| 403 `flow_blocked_by_integrity` | Meta blocks creating or publishing flows on this WhatsApp account | Contact Meta support through WhatsApp Manager |
| 403 `whatsapp_permission_missing` | Meta has not given app2email the permission this needs for your account | Retrying does not help; contact support@app2email.com |
| 422 `outside_24h_window` | The customer last wrote more than 24 hours ago | Send the approved template with the Flow button instead |
| 404 `template_not_found`, 422 `template_not_approved` | The template's name or language is wrong, or it is not approved yet | Pick one from `GET /templates` with status APPROVED |
| 422 `template_parameters_invalid` | The button component does not match the template | Compare with the `example_request` in the answer |
| 400 `invalid_interactive` | The interactive part is not valid (its type or a text length) | Check `interactive.type` `flow`, the `action.parameters`, and keep `flow_cta` to 30 characters |
| 429 `rate_limited` | Too many calls for this key | Wait `Retry-After` seconds, then retry |
| 502 `whatsapp_error` | WhatsApp refused the request with an error that has no own code | Read `whatsapp_error`; try again later, and send the `request_id` to support if it keeps failing |
| The form opens, but no answer arrives | The webhook is switched off, or your receiver drops the event | `GET /webhooks` shows `active` and the last delivery; `GET /webhooks/{id}/deliveries?status=failed` shows what failed |

Every answer has a `request_id`. `GET /requests/{id}` shows what was logged for it, and support@app2email.com can find it too. All codes: [Errors](/api/errors).

## FAQ

<AccordionGroup>
  <Accordion title="Can an AI agent build and manage flows?">
    Yes. The MCP server `https://api.app2email.com/mcp/flows` has the same calls as tools: `list_flows`, `get_flow`, `create_flow`, `update_flow`, `get_flow_json`, `update_flow_json`, `publish_flow`, `deprecate_flow`, `delete_flow`, `get_flow_preview` and `renew_flow_preview`. See [Let an AI agent run your WhatsApp with MCP](/guides/how-to-ai-agent-mcp) and [MCP](/api/mcp).
  </Accordion>
  <Accordion title="Can I send the form to many customers at once?">
    The interactive form message goes to one contact per call, inside their window. To reach many customers, send the approved template with the Flow button, for example as a broadcast to a segment, and follow the opt-in rules for marketing templates. Give every customer their own `flow_token` if you need to match answers to people.
  </Accordion>
  <Accordion title="What happens to customers who still have an older version?">
    Messages already sent keep the version of the flow they were sent with. A change takes effect for new messages after you publish again. A deprecated flow can no longer be sent or opened.
  </Accordion>
  <Accordion title="Can I get Meta's own webhook format?">
    Yes: a webhook with `"format": "meta"` gets what comes from WhatsApp as Meta's own body (`entry[].changes[]`), signed the same way. In app2email's default format the answer is already unpacked into `data.flow`, as shown above. `data.whatsapp` also carries Meta's message object unchanged.
  </Accordion>
</AccordionGroup>

## More how-to guides

<CardGroup cols={2}>
  <Card title="Take appointments from your own website or app" href="/guides/how-to-bookings-api">
    Free slots, bookings and reminders through the Book-and-Pay API.
  </Card>
  <Card title="Build a WhatsApp chatbot with the API" href="/guides/how-to-whatsapp-chatbot">
    Receive messages on a signed webhook and answer from your own code.
  </Card>
  <Card title="Send order and appointment notifications with templates" href="/guides/how-to-order-notifications">
    Approved templates for messages outside the 24 hour window, with delivery status.
  </Card>
  <Card title="Import contacts and keep them in sync with your CRM" href="/guides/how-to-contacts-crm-sync">
    Put the leads your form collects next to the rest of your customer data.
  </Card>
</CardGroup>

[All how-to guides](https://www.app2email.com/docs#how-to)
