# Ask for a payment inside a WhatsApp chat

> Ask a customer to pay an amount with one API call: they get a WhatsApp message with a Pay button, pay through your own Stripe or PayPal account, and you get a payment.paid event. Includes listing, refunds and payments taken in person.

A customer asks on WhatsApp "Can I pay the deposit now?". Your system makes one API call, and the customer gets a message in the same chat with what the payment is for and a **Pay** button. The button opens a payment page, the customer pays with your own Stripe or PayPal account, and the money goes straight to you.

On your side, the call answers with the payment and its page address. When the provider confirms the payment, a `payment.paid` webhook event arrives, and the payment shows as `paid` in the API and on the dashboard.

<Note>
**What this is, and what it is not.** Payment requests are part of app2email's **Book-and-Pay** payments: they use the Stripe or PayPal account connected on the dashboard's Book-and-Pay page, and they can be tied to an appointment or stand on their own. The customer pays on a web page, not inside WhatsApp itself. Orders of Order-and-Pay and tickets of Tickets-and-Pay are paid through their own order flows, with their own refund calls (see "Other kinds of payments" below).
</Note>

## What you need

- A WhatsApp number connected to app2email, on a paid plan (Standard, Professional, Team, Agency or Agent/Developer), with the service LIVE. Every API call needs both (`403 plan_not_allowed`, `403 service_not_live`).
- Book-and-Pay set up for the number. Without it, payment calls answer `403 booking_not_enabled`.
- **Your own Stripe or PayPal account, connected** on the dashboard's Book-and-Pay page, **Payments** (https://www.app2email.com/dashboard/app/book). Stripe takes a secret or restricted key; PayPal takes the client id and secret of a REST app. There you also choose the **currency** (one per number) and which of the two providers customers may use. Without a provider, a payment request answers `409 payments_not_connected`.
- An API key from https://www.app2email.com/dashboard/apikey with these scopes:

| Scope | What it is for in this guide |
| --- | --- |
| `bookings:manage` | Ask for a payment (`POST /payments/links`), refund (`POST /payments/{id}/refund`), record a payment taken in person (`POST /bookings/{id}/payment`), and read payments |
| `messages:read` | Read payments only (`GET /payments`, `GET /payments/{id}`) and check the customer's 24-hour window (`GET /conversations/{contact}`) |
| `webhooks:manage` | Add the webhook that receives `payment.paid` (`POST /webhooks`) |
| `messages:send` | Only if you send the pay link yourself in a template (step 3) |

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

<Warning>
**No sandbox for money.** A sandbox key can read payments (`GET /payments`), but asking for a payment and refunding answer `403 sandbox_key`, because they work with real money at your provider. The instant sandbox for the demo number `12025550100` has no payment calls at all (`403 not_in_instant_sandbox`). To test, connect PayPal in **sandbox** mode on the Payments page, and ask yourself for a small amount on your own WhatsApp.
</Warning>

## Ask for a payment, step by step

<Steps>
  <Step title="Check that the customer's window is open">
    app2email can send the pay link on WhatsApp for you, but only inside the customer's 24-hour window: within 24 hours of their last message to your number (app2email stops 15 minutes early). A customer who just asked "Can I pay now?" is inside it.

    `GET /v1/YOUR_NUMBER/conversations/61412345678` (scope `messages:read`) shows `window_state` (`open` or `closed`) and `window_closes_at`.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678 \
      -H "Authorization: Bearer $A2E_KEY"
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678", {
      headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
    });
    const conv = await res.json();
    console.log(conv.window_state, conv.window_closes_at);
    ```

    ```python Python
    import os, requests

    res = requests.get(
        "https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
    )
    conv = res.json()
    print(conv["window_state"], conv.get("window_closes_at"))
    ```

    </CodeGroup>

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

    ```json
    {
      "success": true,
      "request_id": "c9slm",
      "contact": "61412345678",
      "name": "John",
      "window_state": "open",
      "window_open": true,
      "window_closes_at": "2026-10-27T01:05:44Z",
      "last_inbound_at": "2026-10-26T01:20:44Z"
    }
    ```

    If the window is closed, you can still make the payment request in the next step. app2email then does not send it, and you send its `url` in a template yourself (step 3).
  </Step>

  <Step title="Make the payment request">
    `POST /v1/YOUR_NUMBER/payments/links` (scope `bookings:manage`). The body:

    | Field | Required | Meaning |
    | --- | --- | --- |
    | `contact` | yes | The customer's WhatsApp number with country code, digits only, or their business-scoped user id |
    | `amount` | yes | The amount in your payment currency, as a number: `40` is $40.00 if your currency is USD. Must be above 0 |
    | `description` | yes | What the payment is for. The customer sees it |
    | `booking_id` | no | The appointment it is for: its id or its reference (`BK-7Q3M2A`) |
    | `name` | no | The customer's name |
    | `send` | no | `true`: also send the link on WhatsApp, as a message with a Pay button, when the customer is inside their 24-hour window. Default `false` |

    There is no currency field: the amount is always in the currency chosen on the Payments page. `config.payments.currency` in `GET /v1/YOUR_NUMBER/settings/booking` shows it, and every payment carries its `currency`.

    Send an `Idempotency-Key` header that belongs to this request, such as your invoice number. If your code retries after a timeout, the same key and body within 24 hours gets the first answer again, and the customer is not asked twice. An error does not use the key up.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/payments/links \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: deposit-BK-7Q3M2A" \
      -d '{
        "contact": "61412345678",
        "amount": 40,
        "description": "Deposit for your colour",
        "booking_id": "BK-7Q3M2A",
        "send": true
      }'
    ```

    ```javascript Node.js
    async function askForPayment({ phone, amount, description, bookingRef }) {
      const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/payments/links", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.A2E_KEY}`,
          "Content-Type": "application/json",
          "Idempotency-Key": `deposit-${bookingRef}`,
        },
        body: JSON.stringify({
          contact: phone, // "61412345678"
          amount, // 40
          description, // "Deposit for your colour"
          booking_id: bookingRef, // optional
          send: true,
        }),
      });
      const body = await res.json();
      if (!res.ok) throw new Error(`${body.error.code}: ${body.error.how_to_fix}`);
      return { paymentId: body.payment.id, url: body.url, sent: body.sent };
    }
    ```

    ```python Python
    def ask_for_payment(phone, amount, description, booking_ref=None):
        payload = {"contact": phone, "amount": amount, "description": description, "send": True}
        if booking_ref:
            payload["booking_id"] = booking_ref
        res = requests.post(
            "https://api.app2email.com/v1/YOUR_NUMBER/payments/links",
            headers={
                "Authorization": f"Bearer {os.environ['A2E_KEY']}",
                "Idempotency-Key": f"deposit-{booking_ref or phone}",
            },
            json=payload,
        )
        body = res.json()
        if not res.ok:
            raise RuntimeError(f"{body['error']['code']}: {body['error']['how_to_fix']}")
        return body["payment"]["id"], body["url"], body["sent"]
    ```

    </CodeGroup>

    **What you get back** (HTTP 201): the payment, with `kind` `request` and `status` `pending`, the page where the customer pays (`url`), and whether it went out on WhatsApp (`sent`).

    ```json
    {
      "success": true,
      "request_id": "p3lk4",
      "payment": {
        "id": 15,
        "kind": "request",
        "status": "pending",
        "provider": "stripe",
        "amount": 40.0,
        "amount_label": "$40.00",
        "full_label": "$40.00",
        "discount_label": "",
        "coupon_code": "",
        "currency": "USD",
        "refunded": 0.0,
        "refunded_label": "",
        "description": "Deposit for your colour",
        "contact": "61412345678",
        "payer_name": "John Smith",
        "appointment_id": 42,
        "booking_reference": "BK-7Q3M2A",
        "package_purchase_id": null,
        "checkout_url": "",
        "link_url": "https://www.app2email.com/book/k3XbQ9rTzP2m",
        "last_error": "",
        "paid": null,
        "refunded_at": null,
        "created": "2026-11-11T01:10:00.000Z"
      },
      "url": "https://www.app2email.com/book/k3XbQ9rTzP2m",
      "sent": true,
      "note": "The customer was sent the pay link on WhatsApp."
    }
    ```

    Keep `payment.id` with your invoice or booking: it is how you read, match and refund this payment later.
  </Step>

  <Step title="If sent is false: send the url yourself">
    `sent` is `false` when you left `send` out, or when the customer's window was closed. The payment request still exists and its `url` works. Send it the way that fits:

    - **Window open:** a normal text message with the link (`POST /messages`, `"type": "text"`, scope `messages:send`).
    - **Window closed:** an approved template. A utility template such as `Hi {{1}}, here is the payment link for {{2}}: {{3}}` works, with the `url` as the third value. How to create and send a template: [Send order and appointment notifications with templates](/guides/how-to-order-notifications).

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/messages \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: deposit-BK-7Q3M2A-link" \
      -d '{
        "to": "61412345678",
        "type": "template",
        "template": {
          "name": "payment_request",
          "language": { "code": "en" },
          "components": [
            {
              "type": "body",
              "parameters": [
                { "type": "text", "text": "John" },
                { "type": "text", "text": "the deposit for your colour" },
                { "type": "text", "text": "https://www.app2email.com/book/k3XbQ9rTzP2m" }
              ]
            }
          ]
        }
      }'
    ```

    ```javascript Node.js
    await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.A2E_KEY}`,
        "Content-Type": "application/json",
        "Idempotency-Key": `payment-${paymentId}-link`,
      },
      body: JSON.stringify({
        to: "61412345678",
        type: "template",
        template: {
          name: "payment_request",
          language: { code: "en" },
          components: [
            {
              type: "body",
              parameters: [
                { type: "text", text: "John" },
                { type: "text", text: "the deposit for your colour" },
                { type: "text", text: url }, // the url from step 2
              ],
            },
          ],
        },
      }),
    });
    ```

    ```python Python
    requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/messages",
        headers={
            "Authorization": f"Bearer {os.environ['A2E_KEY']}",
            "Idempotency-Key": f"payment-{payment_id}-link",
        },
        json={
            "to": "61412345678",
            "type": "template",
            "template": {
                "name": "payment_request",
                "language": {"code": "en"},
                "components": [
                    {
                        "type": "body",
                        "parameters": [
                            {"type": "text", "text": "John"},
                            {"type": "text", "text": "the deposit for your colour"},
                            {"type": "text", "text": url},  # the url from step 2
                        ],
                    }
                ],
            },
        },
    )
    ```

    </CodeGroup>

    You can also share the `url` in an email, an SMS or on your own invoice page. It is the same payment either way.
  </Step>

  <Step title="Receive the payment.paid event">
    Add a webhook once (`POST /v1/YOUR_NUMBER/webhooks` with your https `url`, scope `webhooks:manage`) and keep the `secret` it answers. Every webhook of the number gets every event, so handle `payment.paid` and answer 2xx to the rest. No public address yet? `GET /v1/YOUR_NUMBER/events?wait=25` fetches the same events.

    When Stripe or PayPal confirms the payment, this arrives:

    ```json
    {
      "id": "evt_Pay3k9m2Lw8Rt5Yp1Zs03",
      "type": "payment.paid",
      "created": "2026-11-11T01:00:00.000Z",
      "number": "4976659348270",
      "data": {
        "payment": {
          "id": 15,
          "kind": "request",
          "status": "paid",
          "provider": "stripe",
          "amount": 40.0,
          "amount_label": "$40.00",
          "full_label": "$40.00",
          "discount_label": "",
          "coupon_code": "",
          "currency": "USD",
          "refunded": 0.0,
          "refunded_label": "",
          "description": "Deposit for your colour",
          "contact": "61412345678",
          "payer_name": "John Smith",
          "appointment_id": null,
          "booking_reference": "",
          "package_purchase_id": null,
          "checkout_url": "",
          "link_url": "",
          "last_error": "",
          "paid": "2026-11-11T01:15:00.000Z",
          "refunded_at": null,
          "created": "2026-11-11T01:10:00.000Z"
        },
        "timestamp": "2026-11-11T01:00:00.000Z"
      }
    }
    ```

    Match it to your invoice by `data.payment.id`, and check `data.payment.kind`: `payment.paid` is also sent for a prepaid package bought online (`package`), and Order-and-Pay sends it next to `order.paid`. `paid` is the time of payment, `provider` says which provider took it.

    <CodeGroup>

    ```javascript Node.js
    app.post("/app2email", express.raw({ type: "application/json" }), async (req, res) => {
      if (!verifyWebhook(req.body, req.get("X-App2email-Signature"), process.env.WEBHOOK_SECRET)) return res.sendStatus(401);
      if (await alreadySeen(req.get("X-App2email-Delivery"))) return res.sendStatus(200); // a retry
      const event = JSON.parse(req.body);
      if (event.type === "payment.paid" && event.data.payment.kind === "request") {
        await markInvoicePaid(event.data.payment.id, event.data.payment.amount, event.data.payment.paid);
      }
      res.sendStatus(200); // within 10 seconds
    });
    ```

    ```python Python
    @app.post("/app2email")
    def app2email():
        raw = request.get_data()
        if not verify_webhook(raw, request.headers.get("X-App2email-Signature"), os.environ["WEBHOOK_SECRET"]):
            return "", 401
        if already_seen(request.headers.get("X-App2email-Delivery")):
            return "", 200  # a retry
        event = json.loads(raw)
        if event["type"] == "payment.paid" and event["data"]["payment"]["kind"] == "request":
            p = event["data"]["payment"]
            mark_invoice_paid(p["id"], p["amount"], p["paid"])
        return "", 200  # within 10 seconds
    ```

    </CodeGroup>

    `verifyWebhook` and `verify_webhook` are in the production checklist below.
  </Step>
</Steps>

## The result

**What the customer sees.** With `send: true`, a message from your business in the chat, with your `description` and a **Pay** button. The button opens the payment page (`link_url`, on your booking site), and from there the customer pays at Stripe or PayPal, with whichever of the two you allow. The money goes from the customer to your provider account; app2email takes no fee and never holds it. The receipt comes from your provider.

**What you see.** The payment moves through these `status` values:

| `status` | Meaning |
| --- | --- |
| `pending` | Made, not paid yet |
| `paid` | The provider confirmed the payment. `payment.paid` is sent |
| `partly_refunded` | Part of the money was refunded (`refunded` says how much) |
| `refunded` | All of it was refunded |
| `failed` | The payment did not go through. `last_error` says why |
| `expired` | The customer did not pay in time |
| `cancelled` | The payment was cancelled |

Only `paid` has its own event (`payment.paid`). For the other states, read the payment.

**Read one payment:** `GET /v1/YOUR_NUMBER/payments/15` (scope `bookings:manage` or `messages:read`). No provider key or secret is ever in the answer.

**List payments**, newest first: `GET /v1/YOUR_NUMBER/payments`, with the filters `contact`, `booking` (an appointment's id or `BK-` reference), `status`, `kind`, `limit` (1 to 200, default 50) and `cursor` (the `next_cursor` of the previous answer).

<CodeGroup>

```bash cURL
curl -s "https://api.app2email.com/v1/YOUR_NUMBER/payments?kind=request&status=pending&limit=50" \
  -H "Authorization: Bearer $A2E_KEY"
```

```javascript Node.js
let cursor;
do {
  const qs = new URLSearchParams({ kind: "request", status: "pending", limit: "50" });
  if (cursor) qs.set("cursor", cursor);
  const res = await fetch(`https://api.app2email.com/v1/YOUR_NUMBER/payments?${qs}`, {
    headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
  });
  const page = await res.json();
  for (const p of page.payments) console.log(p.id, p.status, p.amount_label, p.contact);
  cursor = page.next_cursor;
} while (cursor);
```

```python Python
params = {"kind": "request", "status": "pending", "limit": 50}
while True:
    page = requests.get(
        "https://api.app2email.com/v1/YOUR_NUMBER/payments",
        headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
        params=params,
    ).json()
    for p in page["payments"]:
        print(p["id"], p["status"], p["amount_label"], p["contact"])
    if not page.get("next_cursor"):
        break
    params["cursor"] = page["next_cursor"]
```

</CodeGroup>

**What you get back** (shortened): `payments`, `count`, `next_cursor` (left out on the last page) and the number's `currency`.

```json
{
  "success": true,
  "request_id": "p1ls2",
  "payments": [
    {
      "id": 15,
      "kind": "booking",
      "status": "paid",
      "provider": "stripe",
      "amount": 40.0,
      "amount_label": "$40.00",
      "currency": "USD",
      "refunded": 0.0,
      "description": "Haircut",
      "contact": "61412345678",
      "payer_name": "John Smith",
      "appointment_id": 42,
      "booking_reference": "BK-7Q3M2A",
      "paid": "2026-11-11T01:15:00.000Z",
      "created": "2026-11-11T01:10:00.000Z"
    }
  ],
  "next_cursor": null,
  "count": 1,
  "currency": "USD"
}
```

`kind` tells you where a payment came from: `request` (a payment request like the one above), `booking` (the online payment or deposit of an appointment), `package` (a prepaid package bought online) or `ticket` (a ticket order).

## Refund a payment

`POST /v1/YOUR_NUMBER/payments/{id}/refund` (scope `bookings:manage`) sends real money back through your own provider. **It cannot be undone.** Leave the body out (or `amount` out) for a full refund of everything that is left. Send `amount` for a part, in the payment's currency.

Always send an `Idempotency-Key`: a refund retried after a timeout with the same key and body gets the first answer, and the money goes back once.

<Tabs>
  <Tab title="Partial refund">
    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/payments/15/refund \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: refund-15-part-1" \
      -d '{ "amount": 10 }'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/payments/15/refund", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.A2E_KEY}`,
        "Content-Type": "application/json",
        "Idempotency-Key": "refund-15-part-1",
      },
      body: JSON.stringify({ amount: 10 }),
    });
    const { payment } = await res.json();
    console.log(payment.status, payment.refunded_label); // partly_refunded $10.00
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/payments/15/refund",
        headers={
            "Authorization": f"Bearer {os.environ['A2E_KEY']}",
            "Idempotency-Key": "refund-15-part-1",
        },
        json={"amount": 10},
    )
    payment = res.json()["payment"]
    print(payment["status"], payment["refunded_label"])  # partly_refunded $10.00
    ```

    </CodeGroup>
  </Tab>
  <Tab title="Full refund">
    <CodeGroup>

    ```bash cURL
    curl -s -X POST https://api.app2email.com/v1/YOUR_NUMBER/payments/15/refund \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Idempotency-Key: refund-15-full"
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/payments/15/refund", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.A2E_KEY}`,
        "Idempotency-Key": "refund-15-full",
      },
    });
    const { payment } = await res.json();
    console.log(payment.status); // refunded
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/payments/15/refund",
        headers={
            "Authorization": f"Bearer {os.environ['A2E_KEY']}",
            "Idempotency-Key": "refund-15-full",
        },
    )
    print(res.json()["payment"]["status"])  # refunded
    ```

    </CodeGroup>
  </Tab>
</Tabs>

**What you get back** (HTTP 200, shortened, after a partial refund of $10 of $40):

```json
{
  "success": true,
  "request_id": "p4rf5",
  "payment": {
    "id": 15,
    "kind": "booking",
    "status": "partly_refunded",
    "provider": "stripe",
    "amount": 40.0,
    "amount_label": "$40.00",
    "currency": "USD",
    "refunded": 10.0,
    "refunded_label": "$10.00",
    "description": "Haircut",
    "contact": "61412345678",
    "appointment_id": 42,
    "booking_reference": "BK-7Q3M2A",
    "paid": "2026-11-11T01:15:00.000Z",
    "created": "2026-11-11T01:10:00.000Z"
  },
  "note": "Refunded through the payment provider. booking.refunded is sent."
}
```

A refund also sends the `booking.refunded` event. It carries the appointment's fields plus `payment` and a `refund` object (`amount`, `amount_label`, `full`, `by`), so it is most useful for payments tied to an appointment. A full refund of an appointment's payment also sets the appointment's payment status to `refunded`. For any payment, the answer above and `GET /payments/{id}` show the new state.

```json
{
  "id": "evt_Pay3k9m2Lw8Rt5Yp1Zs02",
  "type": "booking.refunded",
  "created": "2026-11-11T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "id": 42,
    "reference": "BK-7Q3M2A",
    "status": "confirmed",
    "contact": "61412345678",
    "start": "2026-11-14T23:00:00.000Z",
    "end": "2026-11-14T23:30:00.000Z",
    "payment_status": "refunded",
    "payment": { "id": 15, "kind": "booking", "status": "refunded", "amount": 40.0, "refunded": 40.0, "refunded_label": "$40.00", "currency": "USD" },
    "refund": { "amount": 40.0, "amount_label": "$40.00", "full": true, "by": "jane@example.com" },
    "timestamp": "2026-11-11T01:00:00.000Z"
  }
}
```

A refund that is not possible (the payment is not paid, is already refunded, or less is left than you asked for) answers `409 refund_not_possible`. If Stripe or PayPal refuses, you get `502 payment_provider_error` with the provider's message.

## A payment taken outside app2email

When an appointment's customer pays in cash or at a card terminal, record it with `POST /v1/YOUR_NUMBER/bookings/{id}/payment` (scope `bookings:manage`; the id or the `BK-` reference). Nothing is charged or refunded: it is your own record.

| `status` | Meaning |
| --- | --- |
| `paid` | Taken outside app2email (cash, a terminal) |
| `waived` | Nothing to pay |
| `due` | Still expected (the service's price is the amount when none is recorded) |

<CodeGroup>

```bash cURL
curl -s https://api.app2email.com/v1/YOUR_NUMBER/bookings/BK-7Q3M2A/payment \
  -H "Authorization: Bearer $A2E_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "status": "paid" }'
```

```javascript Node.js
const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/bookings/BK-7Q3M2A/payment", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.A2E_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ status: "paid" }),
});
console.log((await res.json()).booking.payment);
```

```python Python
res = requests.post(
    "https://api.app2email.com/v1/YOUR_NUMBER/bookings/BK-7Q3M2A/payment",
    headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
    json={"status": "paid"},
)
print(res.json()["booking"]["payment"])
```

</CodeGroup>

**What you get back:**

```json
{
  "success": true,
  "request_id": "p5bs6",
  "booking": {
    "id": 42,
    "reference": "BK-7Q3M2A",
    "status": "confirmed",
    "payment": { "status": "paid", "due": 0.0, "paid": 0.0, "currency": "USD" }
  }
}
```

This works for appointments only. A one-off payment request without an appointment cannot be marked paid by hand through the API: it becomes `paid` when the provider confirms it. No `booking.paid` event is sent for a payment you record by hand.

## Other kinds of payments

| What was paid | Read it | Refund it |
| --- | --- | --- |
| A payment request (`kind` `request`) | `GET /payments/{id}` | `POST /payments/{id}/refund` |
| An appointment's online payment or deposit (`kind` `booking`) | `GET /payments?booking=BK-7Q3M2A` | `POST /payments/{id}/refund` (`booking.refunded` is sent) |
| A ticket order (`kind` `ticket`) | `GET /tickets/orders` | `POST /tickets/orders/{id}/refund` (scope `tickets:manage`): it also ends the tickets |
| An Order-and-Pay order | `GET /shop/orders/{id}` | `POST /shop/orders/{id}/refund` (scope `orders:manage`; `amount` there is in minor units, such as cents) |

An appointment's own payment is usually asked for by Book-and-Pay itself: the booking confirmation carries a "Pay now" button when the service is paid online, and `booking.paid` is sent when it is paid. See [Appointment booking on WhatsApp](/guides/booking).

<Tip>
**From an AI agent.** The Payments MCP server `https://api.app2email.com/mcp/payments` has the same calls as tools: `request_payment`, `list_payments` and `refund_payment`, with the same key and scopes. See [Let an AI agent run your WhatsApp with MCP](/guides/how-to-ai-agent-mcp) and [MCP](/api/mcp).
</Tip>

## Production checklist

<AccordionGroup>
  <Accordion title="Check the webhook signature">
    Every event has the header `X-App2email-Signature: t=<unix seconds>,v1=<hex>`. The `v1` value is the HMAC-SHA256 of `"<t>.<raw body>"`, with the webhook's secret (`whsec_...`, prefix included) as the key. Check every `v1=` (there are two while an old secret is still kept after a rotation), compute it over the raw body exactly as received, and refuse an old `t`. `X-Hub-Signature-256: sha256=<hex>` (HMAC-SHA256 of the raw body, current secret only) is there too, for code written for Meta's webhooks.

    A `payment.paid` event decides that a customer has paid, so never act on one whose signature does not match.

    <CodeGroup>

    ```javascript Node.js
    import crypto from "node:crypto";

    // rawBody: the body exactly as received, eg express.raw({ type: "application/json" })
    export function verifyWebhook(rawBody, header, secret, toleranceSeconds = 300) {
      const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
      const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]);
      if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds) return false;
      const expected = crypto.createHmac("sha256", secret).update(t + ".").update(rawBody).digest("hex");
      return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
    }
    ```

    ```python Python
    import hashlib, hmac, re, time

    def verify_webhook(raw_body: 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 "")
        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_body, hashlib.sha256).hexdigest()
        return any(hmac.compare_digest(v, expected) for v in v1)
    ```

    </CodeGroup>
  </Accordion>

  <Accordion title="Count a payment only when the provider confirms it">
    A customer who opened the page, or came back from the checkout, has not necessarily paid. Mark an invoice paid only on `payment.paid`, or when `GET /payments/{id}` shows `status` `paid`. Events can arrive out of order and late, so if you miss one, the payment's `status` is the truth.
  </Accordion>

  <Accordion title="Drop repeated events">
    Answer with a 2xx status within 10 seconds. Otherwise the event is sent again after 10 s, 1 min, 5 min, 30 min, 1, 2, 4, 8 and 16 hours. `X-App2email-Delivery` (the event `id`, `evt_...`) is the same on every retry, so store it and skip an event you already handled. Also make "mark paid" safe to run twice for the same `data.payment.id`. Do the slow work after you answer.
  </Accordion>

  <Accordion title="Never ask twice, never refund twice">
    Send an `Idempotency-Key` header on `POST /payments/links` and on `POST /payments/{id}/refund`, made from your own reference (`deposit-BK-7Q3M2A`, `refund-15-full`), not from the attempt. The same key and body within 24 hours gets the first answer again, with the header `Idempotent-Replayed: true`. An error does not use the key up.

    - Same key with a different body: `422 idempotency_key_reused`. Use a new key for a different request.
    - First request still running: `409 idempotency_request_in_progress`. Wait and retry with the same key.
    - First request did not finish: `409 idempotency_request_interrupted`. Check `GET /payments?contact=61412345678` before you try with a new key.

    The key is kept for 24 hours. Also keep `payment.id` with your own record and do not ask again when one is already there.
  </Accordion>

  <Accordion title="Retry the right errors, and only those">
    Every answer has `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (seconds until full again) and `X-RateLimit-Policy`. Over the limit you get `429 rate_limited` with a `Retry-After` header and `error.retry_after_seconds`: wait that long, then send the same request again.

    - `500`, timeouts, or `502 payment_provider_error` when the provider could not be reached: retry a few times with growing waits, with the same `Idempotency-Key`.
    - `409 payments_not_connected`, `409 refund_not_possible`, `403 booking_not_enabled`, `403 plan_not_allowed`: do not retry. They need a change on the dashboard or in your request.
    - Any other `4xx`: do not retry unchanged. Decide by `error.code` and follow `how_to_fix`. `error.is_retriable` tells you whether the same request can work later.
  </Accordion>

  <Accordion title="The 24-hour window">
    With `send: true`, app2email sends the pay link on WhatsApp only inside the customer's 24-hour window (app2email stops 15 minutes early). Outside it, the request is still made and `sent` is `false`: send the `url` in an approved template. `GET /v1/YOUR_NUMBER/conversations/61412345678` shows `window_state` and `window_closes_at`.
  </Accordion>

  <Accordion title="Opt-out and Do Not Call">
    A payment request answers a customer who is talking to you, so it goes out inside their window, where the Do Not Call list does not apply (it applies to marketing templates). If you send the link in a template, use a **UTILITY** template that only asks for the payment, with no offers in it. Never send payment links to people who did not ask to buy something.
  </Accordion>

  <Accordion title="Keep keys and money safe">
    Keep the API key on your server. A key with `bookings:manage` can refund real money, so give it only to the systems that need it. A key can be limited to some IP addresses (`403 ip_not_allowed` from others) and can expire, and a key with only `messages:read` can read payments but not ask for or refund them. Payments never contain card details or provider keys.
  </Accordion>
</AccordionGroup>

## If it does not work

Every error is JSON with `error.code`, `message`, `how_to_fix` and a `request_id` to quote to support. See [Errors](/api/errors) for every code.

```json
{
  "success": false,
  "request_id": "p3lk4",
  "error": {
    "code": "payments_not_connected",
    "message": "The business has not connected Stripe or PayPal (or the way of paying is not offered).",
    "how_to_fix": "The account owner connects a provider on the dashboard (Book-and-Pay > Payments) and chooses the methods.",
    "documentation_url": "https://www.app2email.com/docs/api/errors#payments_not_connected",
    "is_retriable": false
  }
}
```

| Code | When | What to do |
| --- | --- | --- |
| `401 missing_api_key` | No API key was sent | Send `Authorization: Bearer YOUR_API_KEY` |
| `403 insufficient_scope` | The key lacks a scope (`details.required_scope`) | Use a key with `bookings:manage` (or `messages:read` for reading) |
| `403 sandbox_key` | Asking for a payment, refunding or recording a payment with a sandbox key | Use a normal key (one without the sandbox flag) |
| `403 plan_not_allowed` | The number's plan does not include the API | Choose a paid plan on the billing page |
| `403 service_not_live` | The service is paused, cancelled or not paid | Check the service and the plan on the dashboard |
| `403 booking_not_enabled` | Book-and-Pay is not set up for this number yet | Set up Book-and-Pay on the dashboard, or contact support@app2email.com with the `request_id` |
| `409 payments_not_connected` | No Stripe or PayPal account is connected, or that way of paying is not offered | Connect a provider on the Book-and-Pay page, **Payments**, and choose the methods |
| `400 invalid_payment` | `amount` is missing or not above 0, or a booking has no amount to mark as due | Fix the field named in the message |
| `400 invalid_number` | `contact` is not a full phone number | Country code first, digits only, eg `61412345678` |
| `404 booking_not_found` | `booking_id` (or the booking in the path) is not an appointment of this number | Use the appointment's id or its `BK-` reference |
| `404 payment_not_found` | No payment with that id on this number | `GET /payments` lists the payments with their ids |
| `409 refund_not_possible` | Not paid, already refunded, or less left than you asked for | `GET /payments/{id}` shows the status and what was refunded |
| `502 payment_provider_error` | Stripe or PayPal refused the request or could not be reached | Read the provider's message in the error; try again or check the account at the provider |
| `422 idempotency_key_reused` | Same `Idempotency-Key`, different body | Use a new key for a different request, or send the first body again |
| `409 idempotency_request_in_progress` | The first request with this key is still running | Wait, then retry with the same key |
| `400 invalid_cursor` | The `cursor` of `GET /payments` was changed | Pass the `next_cursor` of the previous answer unchanged |
| `429 rate_limited` | Too many calls for this key | Wait `Retry-After` seconds, then retry |

## More how-to guides

<CardGroup cols={2}>
  <Card title="Build a WhatsApp chatbot with the API" href="/guides/how-to-whatsapp-chatbot">
    Receive messages by webhook and answer with text, buttons and lists.
  </Card>
  <Card title="Send order and appointment notifications with templates" href="/guides/how-to-order-notifications">
    Create a utility template, send it when an order ships, and follow its status.
  </Card>
  <Card title="Send a marketing broadcast that respects opt-ins" href="/guides/how-to-marketing-broadcast">
    One template to a list or a segment, with consent and the Do Not Call list.
  </Card>
  <Card title="Let an AI agent run your WhatsApp with MCP" href="/guides/how-to-ai-agent-mcp">
    Connect an agent to the MCP server and let it read and send messages.
  </Card>
  <Card title="Hand a chat from your bot to a person and back" href="/guides/how-to-human-handoff">
    Set the conversation owner so your bot steps aside while a person answers.
  </Card>
</CardGroup>

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