Guide

Webhooks

Get notified when payments succeed, fail, or need attention.

How webhooks work

When something happens (payment succeeds, charge fails, etc.), we POST a JSON payload to your webhook URL. You verify the signature, process the event, and return 200.

Code
1CX Pay ──POST──▶ https://yoursite.com/webhooks/cxpay
2 Header: X-CXPay-Signature: t=1712345678,v1=abc123...
3 Body: { "type": "payment_intent.succeeded", "data": { ... } }
4
5Your Server ◀── 200 OK

Events you'll care about

For hosted checkout, these are the events that matter:

EventWhen it firesWhat to do
payment_intent.succeededPayment capturedFulfill the order
payment_intent.payment_failedCard declined or errorShow failure to customer
checkout_session.completedCheckout completedRetrieve its PaymentIntent; manual capture can still be requires_capture
checkout_session.expiredSession timed outOptionally notify customer

Start with payment_intent.succeeded. That's the one that means "you got paid." You can add others later.

See the full event catalog for every event type.

Webhook payload

JSON
1{
2 "id": "evt_01JQX...",
3 "object": "event",
4 "type": "payment_intent.succeeded",
5 "created": 1744054500,
6 "createdAt": "2026-04-07T18:35:00.000Z",
7 "apiVersion": "2026-01-01",
8 "livemode": false,
9 "merchantOrgId": "morg_01JQX...",
10 "data": {
11 "object": {
12 "paymentIntentId": "pi_01JQX...",
13 "amount": 5000,
14 "amountReceived": 5000,
15 "currency": "USD",
16 "status": "succeeded",
17 "chargeId": "ch_01JQX...",
18 "clientReferenceCode": null,
19 "customerId": "cus_01JQX..."
20 }
21 }
22}

What some event bodies leave out

  • charge.failed and charge.pending carry a cut-down charge: chargeId, paymentIntentId, customerId, paymentMethodId, status, amount, amountCaptured, amountRefunded, currency, captured, offSession, paymentSource, the card's brand, last4, expMonth, expYear, funding and country, the outcome, the payerAuth result, the error, createdAt and updatedAt. They no longer carry processing details or the payer's billing details.
  • charge.captured, charge.voided and refund.created no longer say who acted.
  • customer.deleted no longer carries deletedBy.
  • payment_method.compromised no longer carries reason.
  • setup_intent.requires_action carries the type of the action only.

Field names that remain are unchanged.

Verifying signatures

Every webhook includes a X-CXPay-Signature header:

X-CXPay-Signature: t=1712345678,v1=a3b2c1d4e5f6...

Verification steps

  1. Parse the header — extract t (timestamp) and v1 (signature)
  2. Check freshness — reject if timestamp is older than 5 minutes
  3. Compute — HMAC-SHA256(webhook_secret, "{t}.{raw_body}")
  4. Compare — your computed signature must match v1 (constant-time comparison)

Node.js

JavaScript
1import crypto from "crypto";
2
3function verifyWebhook(rawBody, signatureHeader, secret) {
4 const parts = signatureHeader.split(",");
5 const timestamp = parts.find(p => p.startsWith("t=")).slice(2);
6 const signature = parts.find(p => p.startsWith("v1=")).slice(3);
7
8 // Check freshness (5 min tolerance)
9 const age = Math.abs(Date.now() / 1000 - parseInt(timestamp));
10 if (age > 300) throw new Error("Webhook too old");
11
12 // Compute expected signature
13 const expected = crypto
14 .createHmac("sha256", secret)
15 .update(`${timestamp}.${rawBody}`)
16 .digest("hex");
17
18 // Constant-time comparison
19 if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
20 throw new Error("Invalid signature");
21 }
22
23 return JSON.parse(rawBody);
24}

Python

Python
1import hashlib, hmac, time, json
2
3def verify_webhook(raw_body: str, signature_header: str, secret: str):
4 parts = dict(p.split("=", 1) for p in signature_header.split(","))
5 timestamp, signature = parts["t"], parts["v1"]
6
7 if abs(time.time() - int(timestamp)) > 300:
8 raise ValueError("Webhook too old")
9
10 expected = hmac.new(
11 secret.encode(), f"{timestamp}.{raw_body}".encode(), hashlib.sha256
12 ).hexdigest()
13
14 if not hmac.compare_digest(signature, expected):
15 raise ValueError("Invalid signature")
16
17 return json.loads(raw_body)

Didn't receive a webhook?

Webhooks are delivered within seconds, but networks aren't perfect. If you haven't received one after 5 minutes, poll the API:

cURL
1GET /v1/payment-intents/{pi_id}

This returns the current Payment Intent status. See Retrieve a Payment Intent. The uncertain and requires_review statuses send no webhook, so polling is the only way to see them.

Don't rely solely on webhooks. Always have a fallback: poll the Payment Intent status if you haven't heard back in 5 minutes. Belt and suspenders.

Retry behavior

If your endpoint returns a non-2xx status or times out:

  • We make up to 8 attempts: the first delivery, then up to 7 retries with exponential backoff
  • Approximate retry schedule: 5s → 30s → 2m → 10m → 1h → 4h → 12h (~17h total window). A retry can run up to about 5 minutes after its scheduled time, so even the first retries can arrive minutes later
  • After all retries fail, the delivery is marked as failed

Your endpoint must start responding within 5 seconds. With no 2xx by then we retry, so the same event can arrive again, even if your endpoint finished the work.

Delivery order is not guaranteed. A later event can arrive before an earlier one.

Your endpoint should be idempotent — processing the same event twice shouldn't cause problems. Use the id field to deduplicate.

Powered by CX Pay