app2email API Amanani

Imibhalo

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

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:
ScopeIsetshenziselwa ukuni kulesi sifundo
bookings:manageUkucela inkokhelo (POST /payments/links), ukubuyisela imali (POST /payments/{id}/refund), ukurekhoda inkokhelo ethathwe ngomuntu (POST /bookings/{id}/payment), kanye nokufunda izinkokhelo
messages:readUkufunda izinkokhelo kuphela (GET /payments, GET /payments/{id}) nokuhlola iwindi lamahora angu-24 lekhasimende (GET /conversations/{contact})
webhooks:manageEngeza i-webhook ezothola i-payment.paid (POST /webhooks)
messages:sendKuphela 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.

Cela inkokhelo, isinyathelo ngesinyathelo

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

    cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678 \
      -H "Authorization: Bearer $A2E_KEY"
    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
    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"))

    Okutholayo (kufushane):

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

  2. 2. Yenza isicelo senkokhelo

    POST /v1/YOUR_NUMBER/payments/links (scope bookings:manage). Umzimba:

    InkambuIyadingekaIncazelo
    contactyeboInombolo yocingo ye-WhatsApp yekhasimende nekhodi yezwe, izinombolo kuphela, noma i-id yomsebenzisi yalo ebhizinisini
    amountyeboInani ngemali yakho yokukhokha, njengenombolo: 40 ingu-$40.00 uma imali yakho ingu-USD. Kumele libe ngaphezu kuka-0
    descriptionyeboLokho inkokhelo eyenzelwe khona. Ikhasimende liyakubona
    booking_idchaIsikhathi sokubonana esilotshwe kuso: i-id yaso noma inkomba yaso (BK-7Q3M2A)
    namechaIgama lekhasimende
    sendchatrue: 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.

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

    Okutholayo (HTTP 201): inkokhelo, ene-kind request ne-status pending, ikhasi lapho ikhasimende likhokha khona (url), nokuthi iphumile ku-WhatsApp yini (sent).

    {
      "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.

  3. 3. 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.
    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" }
              ]
            }
          ]
        }
      }'
    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
    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
                        ],
                    }
                ],
            },
        },
    )

    Ungabuye wabelana nge-url ku-imeyili, ku-SMS noma ekhasini lakho lesikweletu. Kuyinkokhelo efanayo noma kunjani.

  4. 4. 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:

    {
      "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.

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

    I-verifyWebhook ne-verify_webhook zisemhlanganweni wokuhlola okulandelayo.

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:

statusIncazelo
pendingYenziwe, ayikakhokhwa
paidUmhlinzeki uqinisekisile inkokhelo. I-payment.paid iyathunyelwa
partly_refundedIngxenye yemali ibuyiselwe (refunded itshela ukuthi kangakanani)
refundedYonke ibuyiselwe
failedInkokhelo ayidluliselanga. I-last_error ichaza ukuthi kungani
expiredIkhasimende alikhokhanga ngesikhathi
cancelledInkokhelo 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).

cURL
curl -s "https://api.app2email.com/v1/YOUR_NUMBER/payments?kind=request&status=pending&limit=50" \
  -H "Authorization: Bearer $A2E_KEY"
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
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"]

Okutholayo (kufushane): payments, count, next_cursor (ishiywe ekhasini lokugcina) kanye nemali yenombolo, i-currency.

{
  "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.

Ukubuyiselwa ingxenye
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 }'
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
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
Ukubuyiselwa konke
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"
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
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

Okutholayo (HTTP 200, kufushane, ngemva kokubuyisela ingxenye ye-$10 kwe-$40):

{
  "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.

{
  "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.

statusIncazelo
paidIthathwe ngaphandle kwe-app2email (imali, umshini)
waivedAkukho okufanele ikhokhwe
dueKulindeleke okwamanje (inani lesevisi liyinani uma kungarekhodiwe lutho)
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" }'
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
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"])

Okutholayo:

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

OkukhokhelweYifunde ngayoYibuyisele 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-7Q3M2APOST /payments/{id}/refund (booking.refunded iyathunyelwa)
Ioda yethikithi (kind ticket)GET /tickets/ordersPOST /tickets/orders/{id}/refund (scope tickets:manage): iphinde iphelise amathikithi
Ioda ye-Order-and-PayGET /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.

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 kanye ne-MCP.

Uhlu lokuhlola lokukhiqiza

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.

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

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.

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.

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

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.

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.

Uma kungasebenzi

Yonke iphutha ngu-JSON enesi-error.code, i-message, i-how_to_fix kanye ne-request_id ongayicaphuna ku-support. Bona Amaphutha ngazo zonke ikhodi.

{
  "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
  }
}
IkhodiLaphoOkufanele wenze
401 missing_api_keyAkukho khiye we-API othunyiweThumela Authorization: Bearer YOUR_API_KEY
403 insufficient_scopeUkhiye awunayo i-scope (details.required_scope)Sebenzisa ukhiye one-bookings:manage (noma messages:read yokufunda)
403 sandbox_keyUkucela inkokhelo, ukubuyisela imali noma ukurekhoda inkokhelo ngukhiye we-sandboxSebenzisa ukhiye ojwayelekile (ongenayo imaki ye-sandbox)
403 plan_not_allowedUhlelo lwenombolo alufaki i-APIKhetha uhlelo olukhokhelwayo ekhasini lokukhokha
403 service_not_liveIsevisi imisiwe, ikhanseliwe noma ayikhokhelwangaHlola isevisi nohlelo ku-dashboard
403 booking_not_enabledI-Book-and-Pay ayisetshenwe kule nombolo okwamanjeSetha i-Book-and-Pay ku-dashboard, noma xhumana ne-support@app2email.com nge-request_id
409 payments_not_connectedAyikho i-akhawunti ye-Stripe noma ye-PayPal exhunyiwe, noma leyo ndlela yokukhokha ayinikezwaXhuma umhlinzeki ekhasini le-Book-and-Pay, Payments, bese ukhetha izindlela
400 invalid_paymentamount ayikho noma ingaphezu kuka-0, noma ukubhukha akunalo inani lokumaka njengedlulileLungisa inkambu okhonjiswe yona umlayezo
400 invalid_numbercontact ayisiyo inombolo yocingo epheleleIkhodi yezwe iqala, izinombolo kuphela, njengo 61412345678
404 booking_not_foundbooking_id (noma ukubhukha okusendleleni) ayisiyo isikhathi sokubonana salale nomboloSebenzisa i-id yesikhathi sokubonana noma inkomba yaso ye-BK-
404 payment_not_foundAyikho inkokhelo enaleyo id kule nomboloGET /payments ibala izinkokhelo nama-id azo
409 refund_not_possibleAyikhokhiwe, isibuyisiwe kakade, noma kusele ngaphansi kwalokho okuceleGET /payments/{id} ikhombisa isimo nokuthi yini ebuyisiwe
502 payment_provider_errorI-Stripe noma i-PayPal inqabe isicelo noma ayifinyelelekiFunda umlayezo womhlinzeki kwiphutha; zama futhi noma hlola i-akhawunti kumhlinzeki
422 idempotency_key_reusedI-Idempotency-Key efanayo, umzimba ohlukileSebenzisa ukhiye omusha esicelweni esihlukile, noma thumela umzimba wokuqala futhi
409 idempotency_request_in_progressIsicelo sokuqala ngalokhiye sisasebenzaLinda, bese uzama futhi ngokhiye ofanayo
400 invalid_cursorI-cursor ye-GET /payments ishintshiweDlulisa i-next_cursor yempendulo yangaphambili ingashintshiwe
429 rate_limitedIzicelo eziningi kakhulu kulokhiyeLinda izikhathi Retry-After, bese uzama futhi

Ezinye izincwadi zokwenza

Zonke izincwadi zokwenza