# Cela inkokhelo engxoxweni ye-WhatsApp

> Cela ikhasimende ukuthi likhokhe inani ngesicelo se-API esisodwa: ithola umlayezo we-WhatsApp onenkinobho ethi Pay, likhokhe ngeakhawunti yakho ye-Stripe noma ye-PayPal, bese uthola isehlakalo se-payment.paid. Kuhlanganisa ukubala, ukubuyisela imali nokukhokha ngomuntu.

Ikhasimende libuza ku-WhatsApp ukuthi "Ngingakhokha idiphozithi manje?". Uhlelo lwakho lwenza isicelo se-API esisodwa, ikhasimende lithola umlayezo engxoxweni efanayo onencazelo yokuthi yini le nkokhelo kanye nenkinobho ethi **Pay**. Le nkinobho ivula ikhasi lokukhokha, ikhasimende likhokha ngeakhawunti yakho ye-Stripe noma ye-PayPal, bese imali iya kuwe ngqo.

Ohlangothini lwakho, impendulo yesicelo ibuyisela inkokhelo nekheli lekhasi layo. Uma umhlinzeki eqinisekisa inkokhelo, kufika isehlakalo se-webhook se-`payment.paid`, bese inkokhelo ibonakala njenge-`paid` ku-API nakudeshibhodi.

<Note>
**Lokhu yini, nokungekho.** Izicelo zenkokhelo ziyingxenye yezinkokhelo ze-app2email ze-**Book-and-Pay**: zisebenzisa i-akhawunti ye-Stripe noma ye-PayPal exhunywe ekhasini le-Book-and-Pay lodeshibhodi, futhi zingaxhunywa nesikhathi sokubonana noma zime zodwa. Ikhasimende likhokha ekhasini lewebhu, hhayi ngaphakathi kwe-WhatsApp uqobo. Ama-oda e-Order-and-Pay namathikithi e-Tickets-and-Pay akhokhelwa ngama-flow awo ama-oda, nezicelo zawo zokubuyisela imali (bona "Ezinye izinhlobo zezinkokhelo" ngezansi).
</Note>

## Okudingayo

- Inombolo ye-WhatsApp exhunywe ku-app2email, esebenzisa uhlelo olukhokhelwayo (Standard, Professional, Team, Agency noma Agent/Developer), nesevisi isebenza. Yonke i-API call idinga kokubili (`403 plan_not_allowed`, `403 service_not_live`).
- I-Book-and-Pay isetshenziswe kule nombolo. Ngaphandle kwayo, izicelo zenkokhelo ziphendula `403 booking_not_enabled`.
- **I-akhawunti yakho ye-Stripe noma ye-PayPal, exhunyiwe** ekhasini le-Book-and-Pay ledeshibhodi, **Payments** (https://www.app2email.com/dashboard/app/book). I-Stripe ithatha ukhiye wemfihlo noma ukhiye olinganiselwe; i-PayPal ithatha i-client id kanye nemfihlo yohlelo lwe-REST. Lapho ukhetha futhi i-**imali** (eyodwa nge-inombolo ngayinye) kanye nabahlinzeki ababili ukuthi amakhasimende angasebenzisa olunye yini. Ngaphandle komhlinzeki, isicelo senkokhelo siphendula `409 payments_not_connected`.
- Ukhiye we-API ovela ku-https://www.app2email.com/dashboard/apikey onalezi zimvume:

| Scope | Isetshenziselwa ukuni kulesi sifundo |
| --- | --- |
| `bookings:manage` | Ukucela inkokhelo (`POST /payments/links`), ukubuyisela imali (`POST /payments/{id}/refund`), ukurekhoda inkokhelo ethathwe ngomuntu (`POST /bookings/{id}/payment`), kanye nokufunda izinkokhelo |
| `messages:read` | Ukufunda izinkokhelo kuphela (`GET /payments`, `GET /payments/{id}`) nokuhlola iwindi lamahora angu-24 lekhasimende (`GET /conversations/{contact}`) |
| `webhooks:manage` | Engeza i-webhook ezothola i-`payment.paid` (`POST /webhooks`) |
| `messages:send` | Kuphela uma uthumela isixhumanisi sokukhokha ngokwakho kusifanekiso (isinyathelo 3) |

Ukhiye we-Default (owenziwe ngaphambi kokuthi okhiye babe nezimvume) awunayo i-`bookings:manage`. Dala ukhiye onalelo scope, noma ngo-Full access (`*`). `GET /v1/YOUR_NUMBER/me` ikhombisa izimvume zokhiye osebenzisa.

<Warning>
**Akukho sandbox yezimali.** Ukhiye we-sandbox ungafunda izinkokhelo (`GET /payments`), kodwa ukucela inkokhelo nokubuyisela imali kuphendula `403 sandbox_key`, ngoba zisebenza ngemali yangempela ku-mhlinzeki wakho. I-instant sandbox yenombolo yedemo `12025550100` ayinazo nhlobo izicelo zenkokhelo (`403 not_in_instant_sandbox`). Ukuze uvivinye, xhuma i-PayPal ngemodi ye-**sandbox** ekhasini le-Payments, bese ucela inkokhelo encane kuwe ngqo ku-WhatsApp yakho.
</Warning>

## Cela inkokhelo, isinyathelo ngesinyathelo

<Steps>
  <Step title="Hlola ukuthi iwindi lekhasimende livulekile">
    I-app2email ingathumela isixhumanisi sokukhokha ku-WhatsApp ngawe, kodwa kuphela ngaphakathi kwewindi lekhasimende lamahora angu-24: phakathi kwamahora angu-24 kusukela komlayezo wakhe wokugcina ku-inombolo yakho (i-app2email imisa imizuzu eyi-15 ngaphambi kwesikhathi). Ikhasimende elisanda ukubuza "Ngingakhokha manje?" lisengaphakathi kwawo.

    `GET /v1/YOUR_NUMBER/conversations/61412345678` (scope `messages:read`) ikhombisa `window_state` (`open` noma `closed`) kanye ne-`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>

    **Okutholayo** (kufushane):

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

    Uma iwindi livaliwe, usakwazi ukwenza isicelo senkokhelo esinyathelweni esilandelayo. I-app2email ngeke ayithumele, bese wena uthumela i-`url` yayo kusifanekiso (isinyathelo 3).
  </Step>

  <Step title="Yenza isicelo senkokhelo">
    `POST /v1/YOUR_NUMBER/payments/links` (scope `bookings:manage`). Umzimba:

    | Inkambu | Iyadingeka | Incazelo |
    | --- | --- | --- |
    | `contact` | yebo | Inombolo yocingo ye-WhatsApp yekhasimende nekhodi yezwe, izinombolo kuphela, noma i-id yomsebenzisi yalo ebhizinisini |
    | `amount` | yebo | Inani ngemali yakho yokukhokha, njengenombolo: `40` ingu-$40.00 uma imali yakho ingu-USD. Kumele libe ngaphezu kuka-0 |
    | `description` | yebo | Lokho inkokhelo eyenzelwe khona. Ikhasimende liyakubona |
    | `booking_id` | cha | Isikhathi sokubonana esilotshwe kuso: i-id yaso noma inkomba yaso (`BK-7Q3M2A`) |
    | `name` | cha | Igama lekhasimende |
    | `send` | cha | `true`: ithumela nesixhumanisi ku-WhatsApp, njengomlayezo onenkinobho ethi Pay, uma ikhasimende lisengaphakathi kwewindi lamahora angu-24. Okuzenzakalelayo `false` |

    Akukho inkambu yemali: inani likhokhwa ngemali okhethe ekhasini le-Payments. I-`config.payments.currency` ku-`GET /v1/YOUR_NUMBER/settings/booking` iyikhombisa, futhi yonke inkokhelo ithwala i-`currency` yayo.

    Thumela i-header ye-`Idempotency-Key` ebhekisela kulesi sicelo, njengenombolo yakho yesikweletu. Uma ikhodi yakho iphinda ngemva kokuphela kwesikhathi, ukhiye ofanayo nomzimba ofanayo ngaphakathi kwamahora angu-24 uthola impendulo yokuqala futhi ikhasimende alibuzwa kabili. Iphutha alisebenzisi ukhiye.

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

    **Okutholayo** (HTTP 201): inkokhelo, ene-`kind` `request` ne-`status` `pending`, ikhasi lapho ikhasimende likhokha khona (`url`), nokuthi iphumile ku-WhatsApp yini (`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."
    }
    ```

    Gcina i-`payment.id` kanye nesikweletu sakho noma ukubhukha kwakho: yiyo indlela yokufunda, ukuhlanganisa nokubuyisela le nkokhelo kamuva.
  </Step>

  <Step title="Uma i-sent ingu-false: thumela i-url ngokwakho">
    I-`sent` ingu-`false` uma ushiye `send` ngaphandle, noma uma iwindi lekhasimende belivaliwe. Isicelo senkokhelo sisakhona, futhi i-`url` yaso iyasebenza. Yithumele ngendlela eyifanele:

    - **Iwindi livulekile:** umlayezo ojwayelekile wombhalo onesixhumanisi (`POST /messages`, `"type": "text"`, scope `messages:send`).
    - **Iwindi livaliwe:** isifanekiso esivunyelwe. Isifanekiso sokusebenza esifana no `Hi {{1}}, here is the payment link for {{2}}: {{3}}` siyasebenza, ne-`url` njengenani lesithathu. Ukudala nokuthumela isifanekiso: [Thumela izaziso zomyalelo nokubhukha ngezifanekiso](/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>

    Ungabuye wabelana nge-`url` ku-imeyili, ku-SMS noma ekhasini lakho lesikweletu. Kuyinkokhelo efanayo noma kunjani.
  </Step>

  <Step title="Thola isehlakalo se-payment.paid">
    Engeza i-webhook kanye (`POST /v1/YOUR_NUMBER/webhooks` nge-`url` yakho ye-https, scope `webhooks:manage`) bese ugcina i-`secret` eyiphendulayo. Yonke i-webhook yenombolo ithola yonke izehlakalo, ngakho phatha i-`payment.paid` uphendule ngo-2xx kwezinye. Awunalo ikheli lomphakathi okwamanje? I-`GET /v1/YOUR_NUMBER/events?wait=25` ithola izehlakalo ezifanayo.

    Uma i-Stripe noma i-PayPal iqinisekisa inkokhelo, lokhu kufika:

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

    Yihlanganise nesikweletu sakho nge-`data.payment.id`, bese uhlola i-`data.payment.kind`: i-`payment.paid` iphinde ithunyelwe nge-package ethengwe kusengaphambili ku-inthanethi (`package`), futhi i-Order-and-Pay iyithumela eduze kwe-`order.paid`. I-`paid` isikhathi sokukhokha, i-`provider` ithi ngubani omhlinzeki okhokhele ngaye.

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

    I-`verifyWebhook` ne-`verify_webhook` zisemhlanganweni wokuhlola okulandelayo.
  </Step>
</Steps>

## Umphumela

**Okubonwa ikhasimende.** Uma kuthi `send: true`, kuvela umlayezo ovela ebhizinisini lakho engxoxweni, unencazelo yakho (`description`) kanye nenkinobho ethi **Pay**. Inkinobho ivula ikhasi lokukhokha (`link_url`, kusayithi lakho lokubhukha), bese ikhasimende likhokha ku-Stripe noma ku-PayPal, ngalowo kulabo ababili ovumela ngawo. Imali ihamba isuka kukhasimende iye ku-akhawunti yakho yomhlinzeki; i-app2email ayithathi mali yokusebenza futhi ayiyigcini. Irisidi livela kumhlinzeki wakho.

**Okubonwa nguwe.** Inkokhelo ihamba ngale `status` ezilandelayo:

| `status` | Incazelo |
| --- | --- |
| `pending` | Yenziwe, ayikakhokhwa |
| `paid` | Umhlinzeki uqinisekisile inkokhelo. I-`payment.paid` iyathunyelwa |
| `partly_refunded` | Ingxenye yemali ibuyiselwe (`refunded` itshela ukuthi kangakanani) |
| `refunded` | Yonke ibuyiselwe |
| `failed` | Inkokhelo ayidluliselanga. I-`last_error` ichaza ukuthi kungani |
| `expired` | Ikhasimende alikhokhanga ngesikhathi |
| `cancelled` | Inkokhelo ikhanseliwe |

Kuphela i-`paid` inesehlakalo sayo (`payment.paid`). Ngezinye izimo, funda inkokhelo.

**Funda inkokhelo eyodwa:** `GET /v1/YOUR_NUMBER/payments/15` (scope `bookings:manage` noma `messages:read`). Akukho ukhiye womhlinzeki noma imfihlo phakathi kwempendulo.

**Bala izinkokhelo**, ezintsha kuqala: `GET /v1/YOUR_NUMBER/payments`, nezihlungi `contact`, `booking` (i-id yesikhathi sokubonana noma inkomba ye-`BK-`), `status`, `kind`, `limit` (1 kuya ku-200, okuzenzakalelayo 50) kanye ne-`cursor` (i-`next_cursor` yempendulo yangaphambili).

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

**Okutholayo** (kufushane): `payments`, `count`, `next_cursor` (ishiywe ekhasini lokugcina) kanye nemali yenombolo, i-`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"
}
```

I-`kind` ikutshela ukuthi inkokhelo ivela kuphi: `request` (isicelo senkokhelo esifana nalesi esingenhla), `booking` (inkokhelo ye-inthanethi noma idiphozithi yesikhathi sokubonana), `package` (ipakheji ethengwe kusengaphambili ku-inthanethi) noma `ticket` (ioda yethikithi).

## Buyisela imali inkokhelo

I-`POST /v1/YOUR_NUMBER/payments/{id}/refund` (scope `bookings:manage`) ibuyisela imali yangempela ngomhlinzeki wakho. **Ayikwazi ukuguqulwa.** Shiya umzimba ngaphandle (noma `amount` ngaphandle) ukuze ubuyiselwe konke okusele. Thumela `amount` ukuze uthole ingxenye, ngemali yenkokhelo.

Thumela njalo i-`Idempotency-Key`: ukubuyiselwa okuphindwa ngemva kokuphela kwesikhathi ngokhiye ofanayo nomzimba ofanayo kuthola impendulo yokuqala, futhi imali ibuya kanye.

<Tabs>
  <Tab title="Ukubuyiselwa ingxenye">
    <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="Ukubuyiselwa konke">
    <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>

**Okutholayo** (HTTP 200, kufushane, ngemva kokubuyisela ingxenye ye-$10 kwe-$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."
}
```

Ukubuyisela imali kuphinde kuthumele isehlakalo se-`booking.refunded`. Lithwala izinkambu zesikhathi sokubonana kanye ne-`payment` ne-object `refund` (`amount`, `amount_label`, `full`, `by`), ngakho lisebenza kakhulu ezinkokhelweni ezixhunywe nesikhathi sokubonana. Ukubuyiselwa konke kwenkokhelo yesikhathi sokubonana kubuye kusethe isimo sokukhokha sesikhathi sokubonana sibe `refunded`. Kunoma iyiphi inkokhelo, impendulo engenhla kanye ne-`GET /payments/{id}` zikhombisa isimo esisha.

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

Ukubuyisela imali okungenzeki (inkokhelo ayikhokhiwe, isiphelele ngaphambili, noma kusele ngaphansi kwalokho obucele) kuphendula `409 refund_not_possible`. Uma i-Stripe noma i-PayPal inqaba, uthola `502 payment_provider_error` nomlayezo womhlinzeki.

## Inkokhelo ethathwe ngaphandle kwe-app2email

Uma ikhasimende lesikhathi sokubonana likhokha ngemali eyimali noma kumshini wekhadi, yirekhode nge-`POST /v1/YOUR_NUMBER/bookings/{id}/payment` (scope `bookings:manage`; i-id noma inkomba ye-`BK-`). Akukho okushajwayo noma okubuyiselwayo: irekhodi lakho.

| `status` | Incazelo |
| --- | --- |
| `paid` | Ithathwe ngaphandle kwe-app2email (imali, umshini) |
| `waived` | Akukho okufanele ikhokhwe |
| `due` | Kulindeleke okwamanje (inani lesevisi liyinani uma kungarekhodiwe lutho) |

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

**Okutholayo:**

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

Lokhu kusebenza ezikhathini zokubonana kuphela. Inkokhelo yesicelo esisodwa ngaphandle kwesikhathi sokubonana ayikwazi ukumakwa njengekhokhiwe ngesandla nge-API: iba `paid` uma umhlinzeki eyiqinisekisa. Akukho isehlakalo se-`booking.paid` esithunyelwa ngenkokhelo oyirekhodayo ngesandla.

## Ezinye izinhlobo zezinkokhelo

| Okukhokhelwe | Yifunde ngayo | Yibuyisele ngayo |
| --- | --- | --- |
| Isicelo senkokhelo (`kind` `request`) | `GET /payments/{id}` | `POST /payments/{id}/refund` |
| Inkokhelo ye-inthanethi noma idiphozithi yesikhathi sokubonana (`kind` `booking`) | `GET /payments?booking=BK-7Q3M2A` | `POST /payments/{id}/refund` (`booking.refunded` iyathunyelwa) |
| Ioda yethikithi (`kind` `ticket`) | `GET /tickets/orders` | `POST /tickets/orders/{id}/refund` (scope `tickets:manage`): iphinde iphelise amathikithi |
| Ioda ye-Order-and-Pay | `GET /shop/orders/{id}` | `POST /shop/orders/{id}/refund` (scope `orders:manage`; i-`amount` lapho isesenteni, njengamasenti) |

Inkokhelo yesikhathi sokubonana ngokwaso ivame ukucelwa yi-Book-and-Pay ngokwayo: isiqinisekiso sokubhukha sinenkinobho ethi "Pay now" uma isevisi ikhokhelwa ku-inthanethi, futhi i-`booking.paid` ithunyelwa uma ikhokhiwe. Bona [Ukubhukha isikhathi sokubonana ku-WhatsApp](/guides/booking).

<Tip>
**Kusuka ku-AI agent.** I-Payments MCP server `https://api.app2email.com/mcp/payments` inezicelo ezifanayo njengamathuluzi: `request_payment`, `list_payments` kanye ne-`refund_payment`, nokhiye nezimvume ezifanayo. Bona [Vumela i-AI agent iphathe i-WhatsApp yakho nge-MCP](/guides/how-to-ai-agent-mcp) kanye ne-[MCP](/api/mcp).
</Tip>

## Uhlu lokuhlola lokukhiqiza

<AccordionGroup>
  <Accordion title="Hlola isignesha ye-webhook">
    Isehlakalo ngasinye sinehedha `X-App2email-Signature: t=<unix seconds>,v1=<hex>`. Inani le-`v1` ingu-HMAC-SHA256 ye-`"<t>.<raw body>"`, nemfihlo ye-webhook (`whsec_...`, nesiqalo sayo) njengokhiye. Hlola yonke `v1=` (kukhona ezimbili uma imfihlo endala isagcinwa ngemva kokushintshwa), ubale phezu komzimba ongaguqulwanga njengoba ufikile, bese wenqaba `t` endala. Kukhona futhi i-`X-Hub-Signature-256: sha256=<hex>` (HMAC-SHA256 yomzimba ongaguqulwanga, imfihlo yamanje kuphela), ngekhodi ebhalelwe ama-webhook ka-Meta.

    Isehlakalo se-`payment.paid` sinquma ukuthi ikhasimende likhokhile, ngakho ungalokothi wenze ngaso uma isignesha yaso ingahambisani.

    <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="Bala inkokhelo kuphela uma umhlinzeki eyiqinisekisa">
    Ikhasimende elivule ikhasi, noma elibuyile ku-checkout, alikakhokhi ngempela. Makha isikweletu njengesikhokhiwe kuphela ku-`payment.paid`, noma uma i-`GET /payments/{id}` ikhombisa `status` `paid`. Izehlakalo zingafika ngale kwe-oda noma sezisephuzile, ngakho uma ukhaphele eyodwa, i-`status` yenkokhelo iyiqiniso.
  </Accordion>

  <Accordion title="Hlonipha izehlakalo eziphindiwe">
    Phendula ngesimo se-2xx ngaphakathi kwemizuzwana engu-10. Uma kungenjalo isehlakalo siphinde sithunyelwe ngemva kwemizuzwana engu-10, imizuzu engu-1, imizuzu engu-5, imizuzu engu-30, amahora angu-1, 2, 4, 8 kanye nangu-16. I-`X-App2email-Delivery` (i-`id` yesehlakalo, `evt_...`) ifana kuwo wonke ama-retry, ngakho yigcine bese uyedlula isehlakalo osesikucubungulile. Futhi yenza ukuthi "mark paid" iphephe ukusebenza kabili ngo-`data.payment.id` efanayo. Sebenza umsebenzi onzima ngemva kokuphendula.
  </Accordion>

  <Accordion title="Ungacela kabili, ungabuyiseli imali kabili">
    Thumela i-header ye-`Idempotency-Key` ku-`POST /payments/links` nasku-`POST /payments/{id}/refund`, eyakhiwe ngokusho ireferensi yakho (`deposit-BK-7Q3M2A`, `refund-15-full`), hhayi ngomzamo. Ukhiye nomzimba ofanayo ngaphakathi kwamahora angu-24 uthola impendulo yokuqala futhi, nge-header ethi `Idempotent-Replayed: true`. Iphutha alisebenzisi ukhiye.

    - Ukhiye ofanayo nomzimba ohlukile: `422 idempotency_key_reused`. Sebenzisa ukhiye omusha esicelweni esihlukile.
    - Isicelo sokuqala sisasebenza: `409 idempotency_request_in_progress`. Linda bese uzama futhi ngokhiye ofanayo.
    - Isicelo sokuqala asiqedanga: `409 idempotency_request_interrupted`. Hlola `GET /payments?contact=61412345678` ngaphambi kokuzama ngokhiye omusha.

    Ukhiye ugcinwa amahora angu-24. Gcina futhi i-`payment.id` kanye nerekhodi lakho, futhi ungabuzi futhi uma sekukhona.
  </Accordion>

  <Accordion title="Phinda amaphutha afanele kuphela">
    Yonke impendulo inezi-`X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (imizuzwana kuze kugcwale futhi) kanye ne-`X-RateLimit-Policy`. Uma udlula umkhawulo uthola `429 rate_limited` ne-header ethi `Retry-After` kanye ne-`error.retry_after_seconds`: linda isikhathi esifanayo, bese uthumela isicelo esifanayo futhi.

    - `500`, ukuphela kwesikhathi, noma `502 payment_provider_error` lapho umhlinzeki engafinyeleleki: zama izikhathi ezimbalwa ngokukhula kokulinda, ngokhiye ofanayo we-`Idempotency-Key`.
    - `409 payments_not_connected`, `409 refund_not_possible`, `403 booking_not_enabled`, `403 plan_not_allowed`: ungazami futhi. Zidinga ushintsho ku-dashboard noma esicelweni sakho.
    - Noma yimuphi omunye `4xx`: ungazami ngaphandle kokushintsha. Nquma ngo-`error.code` ulandele i-`how_to_fix`. I-`error.is_retriable` ikutshela ukuthi isicelo esifanayo singase sisebenze kamuva.
  </Accordion>

  <Accordion title="Iwindi lamahora angu-24">
    Uma kuthi `send: true`, i-app2email ithumela isixhumanisi sokukhokha ku-WhatsApp kuphela ngaphakathi kwewindi lekhasimende lamahora angu-24 (i-app2email imisa imizuzu eyi-15 ngaphambi kwesikhathi). Ngaphandle kwalo, isicelo senziwa nokho futhi i-`sent` ingu-`false`: thumela i-`url` kusifanekiso esivunyelwe. I-`GET /v1/YOUR_NUMBER/conversations/61412345678` ikhombisa i-`window_state` ne-`window_closes_at`.
  </Accordion>

  <Accordion title="Ukuphuma nohlu Lokungashayi">
    Isicelo senkokhelo siphendula ikhasimende elikhuluma nawe, ngakho sihamba ngaphakathi kwewindi lalo, lapho uhlu Lokungashayi (Do Not Call) lingasebenzi khona (lisebenza kuzifanekiso zokukhangisa). Uma uthumela isixhumanisi kusifanekiso, sebenzisa isifanekiso se-**UTILITY** esicela ukukhokha kuphela, ngaphandle kwezinikezo. Ungalokothi uthumele izixhumanisi zokukhokha kubantu ababengacelanga ukuthenga into.
  </Accordion>

  <Accordion title="Gcina okhiye nemali iphephile">
    Gcina ukhiye we-API oseveni lakho. Ukhiye one-`bookings:manage` ungabuyisela imali yangempela, ngakho nikeza kuphela izinhlelo ezidinga kuwo. Ukhiye ungakhawulelwa kwezinye izikhombisi-ndawo ze-IP (`403 ip_not_allowed` kwezinye) futhi ungaphela, nokhiye one-`messages:read` kuphela ungafunda izinkokhelo kodwa awukwazi ukuzicela noma ukuzibuyisela. Izinkokhelo azikaze ziqukathe imininingwane yekhadi noma okhiye bomhlinzeki.
  </Accordion>
</AccordionGroup>

## Uma kungasebenzi

Yonke iphutha ngu-JSON enesi-`error.code`, i-`message`, i-`how_to_fix` kanye ne-`request_id` ongayicaphuna ku-support. Bona [Amaphutha](/api/errors) ngazo zonke ikhodi.

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

| Ikhodi | Lapho | Okufanele wenze |
| --- | --- | --- |
| `401 missing_api_key` | Akukho khiye we-API othunyiwe | Thumela `Authorization: Bearer YOUR_API_KEY` |
| `403 insufficient_scope` | Ukhiye awunayo i-scope (`details.required_scope`) | Sebenzisa ukhiye one-`bookings:manage` (noma `messages:read` yokufunda) |
| `403 sandbox_key` | Ukucela inkokhelo, ukubuyisela imali noma ukurekhoda inkokhelo ngukhiye we-sandbox | Sebenzisa ukhiye ojwayelekile (ongenayo imaki ye-sandbox) |
| `403 plan_not_allowed` | Uhlelo lwenombolo alufaki i-API | Khetha uhlelo olukhokhelwayo ekhasini lokukhokha |
| `403 service_not_live` | Isevisi imisiwe, ikhanseliwe noma ayikhokhelwanga | Hlola isevisi nohlelo ku-dashboard |
| `403 booking_not_enabled` | I-Book-and-Pay ayisetshenwe kule nombolo okwamanje | Setha i-Book-and-Pay ku-dashboard, noma xhumana ne-support@app2email.com nge-`request_id` |
| `409 payments_not_connected` | Ayikho i-akhawunti ye-Stripe noma ye-PayPal exhunyiwe, noma leyo ndlela yokukhokha ayinikezwa | Xhuma umhlinzeki ekhasini le-Book-and-Pay, **Payments**, bese ukhetha izindlela |
| `400 invalid_payment` | `amount` ayikho noma ingaphezu kuka-0, noma ukubhukha akunalo inani lokumaka njengedlulile | Lungisa inkambu okhonjiswe yona umlayezo |
| `400 invalid_number` | `contact` ayisiyo inombolo yocingo ephelele | Ikhodi yezwe iqala, izinombolo kuphela, njengo `61412345678` |
| `404 booking_not_found` | `booking_id` (noma ukubhukha okusendleleni) ayisiyo isikhathi sokubonana salale nombolo | Sebenzisa i-id yesikhathi sokubonana noma inkomba yaso ye-`BK-` |
| `404 payment_not_found` | Ayikho inkokhelo enaleyo id kule nombolo | `GET /payments` ibala izinkokhelo nama-id azo |
| `409 refund_not_possible` | Ayikhokhiwe, isibuyisiwe kakade, noma kusele ngaphansi kwalokho okucele | `GET /payments/{id}` ikhombisa isimo nokuthi yini ebuyisiwe |
| `502 payment_provider_error` | I-Stripe noma i-PayPal inqabe isicelo noma ayifinyeleleki | Funda umlayezo womhlinzeki kwiphutha; zama futhi noma hlola i-akhawunti kumhlinzeki |
| `422 idempotency_key_reused` | I-`Idempotency-Key` efanayo, umzimba ohlukile | Sebenzisa ukhiye omusha esicelweni esihlukile, noma thumela umzimba wokuqala futhi |
| `409 idempotency_request_in_progress` | Isicelo sokuqala ngalokhiye sisasebenza | Linda, bese uzama futhi ngokhiye ofanayo |
| `400 invalid_cursor` | I-`cursor` ye-`GET /payments` ishintshiwe | Dlulisa i-`next_cursor` yempendulo yangaphambili ingashintshiwe |
| `429 rate_limited` | Izicelo eziningi kakhulu kulokhiye | Linda izikhathi `Retry-After`, bese uzama futhi |

## Ezinye izincwadi zokwenza

<CardGroup cols={2}>
  <Card title="Yakha i-WhatsApp chatbot nge-API" href="/guides/how-to-whatsapp-chatbot">
    Thola imilayezo nge-webhook bese uphendula ngombhalo, izinkinobho nezinhlu.
  </Card>
  <Card title="Thumela izaziso zomyalelo nokubhukha ngezifanekiso" href="/guides/how-to-order-notifications">
    Dala isifanekiso sokusebenza, usithumele lapho i-oda lihamba, bese ulandela isimo sakhe.
  </Card>
  <Card title="Thumela umsakazo wokukhangisa ohlonipha ukuvuma" href="/guides/how-to-marketing-broadcast">
    Isifanekiso esisodwa kuhlu noma kwisegmenti, nokuvuma kanye nohlu Lokungashayi (Do Not Call).
  </Card>
  <Card title="Vumela i-AI agent iphathe i-WhatsApp yakho nge-MCP" href="/guides/how-to-ai-agent-mcp">
    Xhuma i-agent ku-MCP server bese uyivumela ifunde futhi ithumele imilayezo.
  </Card>
  <Card title="Nikezela ingxoxo kusuka ku-bot yakho kuya komuntu nakabuye" href="/guides/how-to-human-handoff">
    Setha umnikazi wengxoxo ukuze i-bot yakho ihambe eceleni kuyilapho umuntu ephendula.
  </Card>
</CardGroup>

[Zonke izincwadi zokwenza](https://www.app2email.com/docs#how-to)
