只需一次 API 呼叫就能請客戶付款:他們會收到附有「付款」按鈕的 WhatsApp 訊息,透過您自己的 Stripe 或 PayPal 帳號付款,您則會收到 payment.paid 事件。內容包括列出付款、退款,以及當面收款的記錄。
客戶在 WhatsApp 上問:「我現在可以付訂金嗎?」您的系統發出一次 API 呼叫,客戶就會在同一個對話中收到一則訊息,說明這筆款項的用途,並附上付款(Pay)按鈕。按鈕會開啟付款頁面,客戶透過您自己的 Stripe 或 PayPal 帳號付款,款項直接進入您的帳戶。
在您這一邊,這個呼叫會回應付款資料及其頁面網址。當金流服務商確認付款後,會收到 payment.paid webhook 事件,付款在 API 和儀表板上都會顯示為 paid。
這是什麼,不是什麼。 付款請求屬於 app2email 的 Book-and-Pay 付款:它們使用在儀表板 Book-and-Pay 頁面連接的 Stripe 或 PayPal 帳號,可以綁定預約,也可以單獨使用。客戶是在網頁上付款,而不是在 WhatsApp 內部付款。Order-and-Pay 的訂單和 Tickets-and-Pay 的票券,則透過各自的訂單流程付款,並有各自的退款呼叫(請參閱下方「其他類型的付款」)。
403 plan_not_allowed、403 service_not_live)。403 booking_not_enabled。409 payments_not_connected。| 權限範圍 | 在本指南中的用途 |
|---|---|
bookings:manage | 請求付款(POST /payments/links)、退款(POST /payments/{id}/refund)、記錄當面收款(POST /bookings/{id}/payment),以及讀取付款 |
messages:read | 只用於讀取付款(GET /payments、GET /payments/{id}),以及檢查客戶的 24 小時視窗(GET /conversations/{contact}) |
webhooks:manage | 新增接收 payment.paid 的 webhook(POST /webhooks) |
messages:send | 只有在您自己用範本發送付款連結時才需要(步驟 3) |
預設金鑰(在金鑰有權限設定之前建立的)沒有 bookings:manage。請建立具備該權限範圍的金鑰,或具備完整存取權(*)的金鑰。GET /v1/YOUR_NUMBER/me 會顯示您目前金鑰的權限範圍。
金錢相關沒有沙盒。 沙盒金鑰可以讀取付款(GET /payments),但請求付款和退款會回應 403 sandbox_key,因為它們會對您的服務商動用真實的金錢。示範號碼 12025550100 的即時沙盒完全沒有付款相關呼叫(403 not_in_instant_sandbox)。若要測試,請在付款頁面以沙盒模式連接 PayPal,然後用您自己的 WhatsApp 請求一筆小額款項。
app2email 可以代您在 WhatsApp 上發送付款連結,但只限於客戶的 24 小時視窗內:也就是客戶最後一次傳訊息到您號碼後的 24 小時內(app2email 提早 15 分鐘停止)。剛剛問「我現在可以付款嗎?」的客戶就在視窗內。
GET /v1/YOUR_NUMBER/conversations/61412345678(權限範圍 messages:read)會顯示 window_state(open 或 closed)和 window_closes_at。
curl -s https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678 \
-H "Authorization: Bearer $A2E_KEY"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);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"))您會收到的回應(已縮短):
{
"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"
}如果視窗已關閉,您仍然可以在下一步建立付款請求。此時 app2email 不會發送,您需要自己用範本發送它的 url(步驟 3)。
POST /v1/YOUR_NUMBER/payments/links(權限範圍 bookings:manage)。請求內容:
| 欄位 | 必填 | 含義 |
|---|---|---|
contact | 是 | 客戶的 WhatsApp 號碼(含國碼,只用數字),或他們的企業範圍使用者 id |
amount | 是 | 以您的付款貨幣表示的金額,用數字表示:如果您的貨幣是 USD,40 就是 $40.00。必須大於 0 |
description | 是 | 這筆款項的用途。客戶看得到 |
booking_id | 否 | 這筆款項對應的預約:它的 id 或參考編號(BK-7Q3M2A) |
name | 否 | 客戶的姓名 |
send | 否 | true:當客戶在 24 小時視窗內時,同時在 WhatsApp 上發送連結,以附有「付款」按鈕的訊息呈現。預設為 false |
沒有貨幣欄位:金額一律使用付款頁面上選擇的貨幣。GET /v1/YOUR_NUMBER/settings/booking 中的 config.payments.currency 會顯示它,而且每筆付款都帶有它的 currency。
請發送一個專屬於這次請求的 Idempotency-Key 標頭,例如您的發票編號。如果您的程式碼在逾時後重試,24 小時內相同的金鑰和內容會再次得到第一次的回應,客戶不會被請求兩次。發生錯誤時,不會用掉這個金鑰。
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
}'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 };
}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"]您會收到的回應(HTTP 201):付款資料,其中 kind 為 request、status 為 pending,還有客戶付款的頁面(url),以及是否已透過 WhatsApp 發出(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."
}請把 payment.id 與您的發票或預約放在一起:之後要讀取、對帳和退款這筆付款,都靠它。
當您省略 send,或客戶的視窗已關閉時,sent 會是 false。付款請求仍然存在,它的 url 也有效。請用適合的方式發送:
POST /messages、"type": "text"、權限範圍 messages:send)。Hi {{1}}, here is the payment link for {{2}}: {{3}} 這樣的實用範本即可使用,以 url 作為第三個值。如何建立和發送範本:使用範本發送訂單和預約通知。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" }
]
}
]
}
}'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
],
},
],
},
}),
});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
],
}
],
},
},
)您也可以把 url 放在電子郵件、簡訊或您自己的發票頁面中分享。無論哪種方式,都是同一筆付款。
新增一次 webhook(POST /v1/YOUR_NUMBER/webhooks,帶上您的 https url,權限範圍 webhooks:manage),並保留它回應的 secret。該號碼的每個 webhook 都會收到每個事件,所以請處理 payment.paid,並對其餘事件回應 2xx。還沒有公開網址?GET /v1/YOUR_NUMBER/events?wait=25 可以取得相同的事件。
當 Stripe 或 PayPal 確認付款後,會送來這個:
{
"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"
}
}用 data.payment.id 與您的發票對應,並檢查 data.payment.kind:線上購買預付套餐(package)時也會發送 payment.paid,Order-and-Pay 則會在 order.paid 旁一併發送。paid 是付款時間,provider 表示由哪個服務商收款。
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
});@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 secondsverifyWebhook 和 verify_webhook 在下方的上線檢查清單中。
客戶看到的內容。 使用 send: true 時,對話中會出現一則來自您企業的訊息,附有您的 description 和付款(Pay)按鈕。按鈕會開啟付款頁面(link_url,在您的預約網站上),客戶再從那裡透過 Stripe 或 PayPal 付款,使用您允許的其中一種。款項從客戶直接進入您的服務商帳戶;app2email 不收取任何費用,也從不經手款項。收據由您的服務商開立。
您看到的內容。 付款會依序經過這些 status 值:
status | 含義 |
|---|---|
pending | 已建立,尚未付款 |
paid | 服務商已確認付款。會發送 payment.paid |
partly_refunded | 已退還部分款項(refunded 說明退了多少) |
refunded | 已全額退款 |
failed | 付款未成功。last_error 說明原因 |
expired | 客戶未在時限內付款 |
cancelled | 付款已取消 |
只有 paid 有自己的事件(payment.paid)。其他狀態請讀取付款資料。
讀取單一付款: GET /v1/YOUR_NUMBER/payments/15(權限範圍 bookings:manage 或 messages:read)。回應中絕不會出現服務商的金鑰或密鑰。
列出付款,由新到舊:GET /v1/YOUR_NUMBER/payments,可使用篩選條件 contact、booking(預約的 id 或 BK- 參考編號)、status、kind、limit(1 到 200,預設 50)和 cursor(上一個回應的 next_cursor)。
curl -s "https://api.app2email.com/v1/YOUR_NUMBER/payments?kind=request&status=pending&limit=50" \
-H "Authorization: Bearer $A2E_KEY"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);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"]您會收到的回應(已縮短):payments、count、next_cursor(最後一頁會省略)和號碼的 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"
}kind 會告訴您付款的來源:request(像上面這樣的付款請求)、booking(預約的線上付款或訂金)、package(線上購買的預付套餐)或 ticket(票券訂單)。
POST /v1/YOUR_NUMBER/payments/{id}/refund(權限範圍 bookings:manage)會透過您自己的服務商把真實的金錢退回去。無法復原。 若要退還剩餘的全部金額,請省略內容(或省略 amount)。若只退一部分,請發送 amount,以付款的貨幣表示。
請務必發送 Idempotency-Key:逾時後以相同的金鑰和內容重試的退款,會得到第一次的回應,款項只會退一次。
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 }'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.00res = 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.00curl -s -X POST https://api.app2email.com/v1/YOUR_NUMBER/payments/15/refund \
-H "Authorization: Bearer $A2E_KEY" \
-H "Idempotency-Key: refund-15-full"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); // refundedres = 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您會收到的回應(HTTP 200,已縮短,$40 中部分退款 $10 之後):
{
"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."
}退款也會發送 booking.refunded 事件。它帶有預約的欄位,加上 payment 和 refund 物件(amount、amount_label、full、by),所以對綁定預約的付款最有用。預約付款全額退款時,也會把預約的付款狀態設為 refunded。對於任何付款,上面的回應和 GET /payments/{id} 都會顯示新的狀態。
{
"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"
}
}無法進行的退款(付款尚未完成、已經退款,或剩餘金額少於您要求的金額)會回應 409 refund_not_possible。如果 Stripe 或 PayPal 拒絕,您會收到 502 payment_provider_error,並附上服務商的訊息。
當預約的客戶以現金或在刷卡機付款時,請用 POST /v1/YOUR_NUMBER/bookings/{id}/payment 記錄(權限範圍 bookings:manage;使用 id 或 BK- 參考編號)。不會有任何扣款或退款:這只是您自己的記錄。
status | 含義 |
|---|---|
paid | 在 app2email 之外收款(現金、刷卡機) |
waived | 無須付款 |
due | 仍待收款(沒有記錄金額時,以服務的價格作為金額) |
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" }'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);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"])您會收到的回應:
{
"success": true,
"request_id": "p5bs6",
"booking": {
"id": 42,
"reference": "BK-7Q3M2A",
"status": "confirmed",
"payment": { "status": "paid", "due": 0.0, "paid": 0.0, "currency": "USD" }
}
}這只適用於預約。沒有預約的單次付款請求,無法透過 API 手動標示為已付款:它會在服務商確認後變成 paid。您手動記錄的付款不會發送 booking.paid 事件。
| 付款內容 | 讀取方式 | 退款方式 |
|---|---|---|
付款請求(kind 為 request) | GET /payments/{id} | POST /payments/{id}/refund |
預約的線上付款或訂金(kind 為 booking) | GET /payments?booking=BK-7Q3M2A | POST /payments/{id}/refund(會發送 booking.refunded) |
票券訂單(kind 為 ticket) | GET /tickets/orders | POST /tickets/orders/{id}/refund(權限範圍 tickets:manage):同時會讓票券失效 |
| Order-and-Pay 訂單 | GET /shop/orders/{id} | POST /shop/orders/{id}/refund(權限範圍 orders:manage;那裡的 amount 以最小貨幣單位表示,例如分) |
預約本身的付款,通常由 Book-and-Pay 自己發出請求:當服務需要線上付款時,預約確認訊息會附上「立即付款」按鈕,付款完成時會發送 booking.paid。請參閱 WhatsApp 預約。
從 AI 代理使用。 付款 MCP 伺服器 https://api.app2email.com/mcp/payments 以工具提供相同的呼叫:request_payment、list_payments 和 refund_payment,使用相同的金鑰和權限範圍。請參閱用 MCP 讓 AI 代理管理您的 WhatsApp 和 MCP。
每個事件都有標頭 X-App2email-Signature: t=<unix seconds>,v1=<hex>。v1 的值是 "<t>.<raw body>" 的 HMAC-SHA256,並以 webhook 的密鑰(whsec_...,包含前綴)作為金鑰。請檢查每個 v1=(輪換密鑰後,舊密鑰仍保留期間會有兩個),以收到的原始內容原樣計算,並拒絕過舊的 t。X-Hub-Signature-256: sha256=<hex>(原始內容的 HMAC-SHA256,只使用目前的密鑰)也會附上,供為 Meta webhook 寫的程式碼使用。
payment.paid 事件決定了客戶是否已付款,所以絕不要依據簽章不符的事件採取行動。
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)));
}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)開啟了頁面或從結帳頁面返回的客戶,不一定已經付款。只有在收到 payment.paid,或 GET /payments/{id} 顯示 status 為 paid 時,才把發票標示為已付款。事件可能亂序或延遲送達,所以如果您漏掉了一個,付款的 status 才是事實。
請在 10 秒內以 2xx 狀態回應。否則事件會在 10 秒、1 分鐘、5 分鐘、30 分鐘、1、2、4、8 和 16 小時後重新發送。X-App2email-Delivery(事件的 id,evt_...)在每次重試時都相同,所以請儲存它,並略過已處理過的事件。同時,讓「標示為已付款」對同一個 data.payment.id 執行兩次也安全。耗時的工作請在回應之後再做。
請在 POST /payments/links 和 POST /payments/{id}/refund 上發送 Idempotency-Key 標頭,用您自己的參考編號組成(deposit-BK-7Q3M2A、refund-15-full),而不是用嘗試次數。24 小時內相同的金鑰和內容會再次得到第一次的回應,並帶有標頭 Idempotent-Replayed: true。發生錯誤時,不會用掉這個金鑰。
422 idempotency_key_reused。不同的請求請使用新的金鑰。409 idempotency_request_in_progress。請等待後,用相同的金鑰重試。409 idempotency_request_interrupted。在用新金鑰重試之前,先檢查 GET /payments?contact=61412345678。金鑰會保留 24 小時。同時,請把 payment.id 存在您自己的記錄中,已經有記錄時就不要再次請求。
每個回應都有 X-RateLimit-Limit、X-RateLimit-Remaining、X-RateLimit-Reset(距離額度完全恢復的秒數)和 X-RateLimit-Policy。超過限制時,您會收到 429 rate_limited,附帶 Retry-After 標頭和 error.retry_after_seconds:等待該段時間後,再發送相同的請求。
500、逾時,或無法連線到服務商時的 502 payment_provider_error:以逐漸拉長的間隔重試幾次,並使用相同的 Idempotency-Key。409 payments_not_connected、409 refund_not_possible、403 booking_not_enabled、403 plan_not_allowed:不要重試。它們需要在儀表板或您的請求中做出變更。4xx:不要原封不動地重試。請依 error.code 判斷,並依照 how_to_fix 處理。error.is_retriable 會告訴您相同的請求之後是否可能成功。使用 send: true 時,app2email 只會在客戶的 24 小時視窗內,於 WhatsApp 上發送付款連結(app2email 提早 15 分鐘停止)。在視窗之外,請求仍會建立,且 sent 為 false:請用已核准的範本發送 url。GET /v1/YOUR_NUMBER/conversations/61412345678 會顯示 window_state 和 window_closes_at。
付款請求是回應正在與您交談的客戶,所以它在客戶的視窗內發出,而「請勿聯絡」名單不適用於此(它適用於行銷範本)。如果您用範本發送連結,請使用只請求付款、不含任何優惠的 UTILITY 範本。絕不要把付款連結發送給沒有要求購買任何東西的人。
請把 API 金鑰放在您的伺服器上。具備 bookings:manage 的金鑰可以退還真實的金錢,所以只提供給需要的系統。金鑰可以限制為只能從某些 IP 位址使用(其他來源會得到 403 ip_not_allowed),也可以設定到期;只有 messages:read 的金鑰可以讀取付款,但不能請求或退款。付款資料中絕不會包含信用卡資料或服務商的金鑰。
每個錯誤都是 JSON,包含 error.code、message、how_to_fix,以及一個可在聯絡支援時提供的 request_id。所有代碼請參閱錯誤。
{
"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
}
}| 代碼 | 時機 | 該怎麼做 |
|---|---|---|
401 missing_api_key | 沒有發送 API 金鑰 | 發送 Authorization: Bearer YOUR_API_KEY |
403 insufficient_scope | 金鑰缺少某項權限範圍(details.required_scope) | 使用具備 bookings:manage 的金鑰(讀取則用 messages:read) |
403 sandbox_key | 用沙盒金鑰請求付款、退款或記錄付款 | 使用一般金鑰(沒有沙盒標記的金鑰) |
403 plan_not_allowed | 號碼的方案不包含 API | 在帳單頁面選擇付費方案 |
403 service_not_live | 服務已暫停、已取消或未付款 | 在儀表板檢查服務和方案 |
403 booking_not_enabled | 這個號碼尚未設定 Book-and-Pay | 在儀表板設定 Book-and-Pay,或帶著 request_id 聯絡 support@app2email.com |
409 payments_not_connected | 尚未連接 Stripe 或 PayPal 帳號,或未提供該付款方式 | 在 Book-and-Pay 頁面的付款中連接服務商,並選擇付款方式 |
400 invalid_payment | amount 缺少或不大於 0,或預約沒有可標示為待付的金額 | 修正訊息中指出的欄位 |
400 invalid_number | contact 不是完整的電話號碼 | 國碼在前,只用數字,例如 61412345678 |
404 booking_not_found | booking_id(或路徑中的預約)不是這個號碼的預約 | 使用預約的 id 或它的 BK- 參考編號 |
404 payment_not_found | 這個號碼上沒有該 id 的付款 | GET /payments 會列出付款及其 id |
409 refund_not_possible | 尚未付款、已經退款,或剩餘金額少於您要求的金額 | GET /payments/{id} 會顯示狀態和已退款的金額 |
502 payment_provider_error | Stripe 或 PayPal 拒絕了請求,或無法連線 | 閱讀錯誤中服務商的訊息;請再試一次,或到服務商那邊檢查帳號 |
422 idempotency_key_reused | 相同的 Idempotency-Key,但內容不同 | 不同的請求請使用新的金鑰,或再次發送第一次的內容 |
409 idempotency_request_in_progress | 使用此金鑰的第一個請求仍在執行 | 請等待,然後用相同的金鑰重試 |
400 invalid_cursor | GET /payments 的 cursor 被更改了 | 原封不動地傳入上一個回應的 next_cursor |
429 rate_limited | 此金鑰的呼叫太多 | 等待 Retry-After 秒,然後重試 |