Webhooks
Webhooks let securepayAPI notify your server as a payment moves through its lifecycle — from the first attempt, through capture and settlement, to any later refund or dispute — so you can fulfil orders, update records or alert a customer without polling.
Webhooks describe the transaction on the payment platform, not the Payment Intent. Each payment attempt is its own transaction:
- its
idis the transaction reference — for a widget payment, the Payment Intent'stransaction_reference. When the shopper tries again (for example after a wallet decline), the intent gets a new reference, so one intent can produce webhooks for several transactions; - its
externalidis theexternalidyou set on the intent, or the intent id when you set none. On a hosted product page it is the product id.
Use the Payment Intent to confirm a payment synchronously; use webhooks for everything that happens after.
Set up an endpoint
- Build an HTTPS endpoint on your server that accepts
POSTrequests with a JSON body. - In the Developer section of your dashboard, under Webhook, enter its URL. It must be an absolute
https://URL of up to 2048 characters, on the default port (an explicit:443is fine), without credentials or a#fragment; a query string is kept and sent with every request. The host must be a public hostname containing a dot (or a public IP):localhost,.local,.internal,.home.arpa, private and reserved addresses, and our own domains (and their subdomains) are refused. The address is resolved at delivery time and must then resolve only to public addresses. Your endpoint needs a valid certificate and TLS 1.2 or newer. Redirects are not followed. - When you first save an endpoint, the dashboard generates a signing secret (64 hexadecimal characters) and shows it once. Copy it then. Use it to verify deliveries to that endpoint.
The form checks only that the URL is an absolute http(s) address. A URL that breaks any other rule above — http://, another port, a private host — may be saved, but every delivery to it is then dropped without a request and without retries. If nothing arrives, check the URL first.
- An endpoint keeps its secret until its URL changes or you ask for a new one. Saving the same URL again leaves the secret as it is. Changing the URL generates a new secret for that endpoint, and New secret issues one without changing the URL. Either way the old secret stops working at once: deliveries still queued or waiting for a retry at that moment are signed with the new secret. Deploy it on your server immediately.
- You can add one additional endpoint. Both receive every event, each signed with its own secret; changing or removing one does not affect the other's secret.
- You can change the primary URL but not remove it from the dashboard.
- An endpoint's URL and secret serve both live and sandbox payments; tell them apart by
env. - Webhooks become available once your account is activated. Payments made while no URL is set are never sent later — nothing is queued for them.
When webhooks fire
A webhook is queued when a transaction's status changes, and also when only its payout state (deliverystatus) or its partial-refund totals change — so a delivery may repeat a status you have already seen.
| What happened | status you receive |
|---|---|
| Payment opened | 10 INIT |
| 3-D Secure steps: device data, authentication, challenge, challenge form | 11, 12, 13, 14 |
| Authorized, ready for capture | 15 AUTH3DSRESULT |
| Capture submitted | 16 PAYING |
| Capture succeeded | 1 PAID |
| Declined or failed, at any step before or at capture | 3 FAILED |
| Processor settlement recorded | 20 SETTLED |
| Payout state changed | the same status, new deliverystatus |
| Full refund accepted before the funds were paid out to you (and always in sandbox) | 9 REFUNDED |
| Full refund accepted after the payout | nothing — see below |
| Processor confirms a full refund | 9 REFUNDED |
| Partial refund confirmed, failed or reversed | the same status, new refund totals — or 9 REFUNDED once confirmed partial refunds add up to the captured amount |
| A dispute changes the status | the dispute status, 21–33 |
| Subscription lifecycle, renewal and plan events | an event payload |
Not sent — design for these:
- A full refund's pending state. When the funds were already paid out, the transaction moves to 34
REFUNDPENDINGwithout a webhook; the next one you get is 9REFUNDEDwhen the processor confirms. Read the transaction to see the pending state. - Dispute notifications that do not change the status — repeated notifications, issuer comments, fraud notifications.
- Separate "refund created", "dispute created", "payout" or "settlement" events. They do not exist: everything is the transaction payload.
- Anything at all while no webhook URL is configured.
A delivery is not necessarily sent the instant the change happens, and several rapid changes may be folded into one delivery (statushistory lists them).
The request
POST /your/webhook HTTP/1.1
Host: shop.example.com
Content-Type: application/json
Accept: application/json
Content-Length: 612
User-Agent: SecurePayAPI-Webhook/1.0
X-Timestamp: 1789123456
X-Signature: 3f1c…e9a0These are the only headers sent. The body is compact UTF-8 JSON:
{
"created": 1789123456789,
"id": "LUZH24T2E65K3NN4",
"famt": 49.99,
"currency": "USD",
"env": 0,
"delivery": 2,
"paymenttype": 1,
"paymenttypetext": "ECOM",
"payment_channel": 1,
"funding_method": 1,
"payment_channel_text": "ecommerce",
"funding_method_text": "card",
"deliverystatus": 1,
"deliverystatustext": "DELIVERYPENDING",
"externalReference": "ORDER-42",
"externalid": "ORDER-42",
"customerid": null,
"status": 1,
"statustext": "PAID",
"statushistory": [{ "status": 1, "statustext": "PAID" }],
"merchantid": "7TTR77ZC",
"three_ds_status": "authenticated",
"liability_shift_status": "shifted",
"three_ds_eci": "05"
}Values are illustrative. There is no event id and no event type on payment webhooks: the payload is the transaction's current state. A field whose value is not known yet is simply absent — normal for payments still in progress. Treat every field as optional except id, status, statustext, statushistory and env.
| Field | Description |
|---|---|
id | The transaction reference. New references are LU followed by 14 characters [0-9A-Z]; older ones match [A-Za-z0-9_-]{8,64}. |
status | Current status code — see Transaction statuses. Branch on this number. |
statustext | The status key (PAID), not the human label the transaction returns (Paid). |
statushistory | Normally exactly one entry: the current status. More entries appear only when newer statuses were merged into a delivery that had not gone out yet — oldest first, and the same status may repeat. |
env | 0 live, 1 sandbox. |
created | Creation time — a number of milliseconds on payments still in progress, possibly an ISO-8601 string on finished ones. Do not rely on it; read the transaction (Unix seconds) for timestamps. |
famt, currency | Amount as a JSON number in major units (49.99 = $49.99) and the payment currency. |
externalid, externalReference | Your reference — the same value under both names. |
merchantid | Your merchant id. |
customerid | Legacy field; null or absent. |
paymenttype, paymenttypetext | Channel: 0 NONE, 1 ECOM, 2 POS, 3 WIRE, 4 ACH — not the card scheme. |
payment_channel, payment_channel_text | 0 unknown, 1 ecommerce, 2 pos, 3 bank, 4 blockchain. |
funding_method, funding_method_text | 0 unknown, 1 card, 2 ach, 3 wire, 4 usdc, 5 paypal. Apple Pay and Google Pay are 1 card. Treat any other value as unknown. |
deliverystatus, deliverystatustext | Payout state of the funds: 0 NONE, 1 DELIVERYPENDING, 2 DELIVERING, 3 FAILED, 4 DELIVERYUNKNOWN, 5 DELIVERED, 6 FROZEN, 7 REFUNDED; null when not set. |
sent, delivery | Amount paid out to you, and the payout method (0 crypto direct, 1 crypto swap, 2 wire, 3 ACH) — once known. |
hash, chain, nonce, output_currency | Crypto payouts only. |
invoice | Invoice id, when the payment was against an invoice. |
order | { "id": string, "version": number }, when the payment was for a platform order. |
three_ds_status, liability_shift_status, three_ds_eci | 3-D Secure result, when recorded. Store and show them; do not branch on specific values. |
refund_reason, refund_request_source, refund_requested_at | Set once a refund was requested. The source is merchant_api, admin or automatic_fraud; parse the time defensively (ISO string or number). |
refunded_presentment_amount, pending_refund_presentment_amount, partial_refund_count | Confirmed and pending partial-refund totals (decimal strings in the payment currency) and their count. Treat absent as "0" / 0. |
customer_card_surcharge | Present only when a card surcharge was applied. |
The payload never contains a card number, cardholder name or e-mail, the decline reason, a dispute reason or deadline, a refund id, or USD and fee amounts — read the transaction or the dashboard for those.
A full refund that the processor confirmed:
{
"created": "2026-09-11T10:04:16.789Z",
"id": "LUZH24T2E65K3NN4",
"famt": 49.99,
"currency": "USD",
"env": 0,
"sent": 48.24,
"delivery": 2,
"paymenttype": 1,
"paymenttypetext": "ECOM",
"payment_channel": 1,
"funding_method": 1,
"payment_channel_text": "ecommerce",
"funding_method_text": "card",
"deliverystatus": 5,
"deliverystatustext": "DELIVERED",
"externalReference": "ORDER-42",
"externalid": "ORDER-42",
"customerid": null,
"status": 9,
"statustext": "REFUNDED",
"statushistory": [{ "status": 9, "statustext": "REFUNDED" }],
"merchantid": "7TTR77ZC",
"refund_reason": "customer_request",
"refund_request_source": "merchant_api",
"refund_requested_at": "2026-09-14T08:00:00.000Z",
"refunded_presentment_amount": "0",
"pending_refund_presentment_amount": "0",
"partial_refund_count": 0
}Recognise a full refund by status: 9, not by the refund totals — those track partial refunds.
A chargeback opened — the ordinary payload with a dispute status and nothing else about the dispute:
{
"created": "2026-09-11T10:04:16.789Z",
"id": "LUZH24T2E65K3NN4",
"famt": 49.99,
"currency": "USD",
"env": 0,
"sent": 48.24,
"delivery": 2,
"paymenttype": 1,
"paymenttypetext": "ECOM",
"payment_channel": 1,
"funding_method": 1,
"payment_channel_text": "ecommerce",
"funding_method_text": "card",
"deliverystatus": 5,
"deliverystatustext": "DELIVERED",
"externalReference": "ORDER-42",
"externalid": "ORDER-42",
"customerid": null,
"status": 24,
"statustext": "CHARGEBACKOPEN",
"statushistory": [{ "status": 24, "statustext": "CHARGEBACKOPEN" }],
"merchantid": "7TTR77ZC",
"refunded_presentment_amount": "0",
"pending_refund_presentment_amount": "0",
"partial_refund_count": 0
}Open the transaction in the dashboard for the dispute's reason and what you can submit — see Disputes.
Transaction statuses
Each webhook carries a numeric status code and its statustext key.
Payment
| Code | Status | Meaning |
|---|---|---|
| 10 | INIT | Payment opened |
| 11 | DDC | Device data collection (3-D Secure) |
| 12 | AUTH3DS | 3-D Secure authentication started, or a wallet authorizing |
| 13 | AUTH3DSCHALLENGE | 3-D Secure challenge required |
| 14 | AUTH3DSCHALLENGEFORM | Challenge form presented |
| 15 | AUTH3DSRESULT | Authorized — ready for capture |
| 16 | PAYING | Capture submitted, outcome not yet known — neither paid nor failed |
| 1 | PAID | Captured — success |
| 20 | SETTLED | Captured and settled |
| 3 | FAILED | Declined or failed — this attempt is over |
Refunds
| Code | Status | Meaning |
|---|---|---|
| 34 | REFUNDPENDING | Full refund requested, not yet confirmed — never sent as a webhook (see above) |
| 9 | REFUNDED | Fully refunded: one full refund, or partial refunds adding up to the captured amount |
Disputes
Sent throughout the dispute lifecycle:
| Code | Status | Meaning |
|---|---|---|
| 21 | INFORMATIONREQUESTED | Issuer requested more information |
| 22 | INFORMATIONRESPONDED | Information supplied |
| 23 | INFORMATIONEXPIRED | Information request expired |
| 24 | CHARGEBACKOPEN | Chargeback opened; the amount is held |
| 25 | CHARGEBACKREVERSED | Chargeback reversed — in your favour |
| 26 | CHARGEBACKWON | Chargeback won |
| 27 | CHARGEBACKLOST | Chargeback lost or accepted |
| 28 | PREARBITRATIONOPEN | Pre-arbitration opened; the amount is held |
| 29 | PREARBITRATIONWON | Pre-arbitration won |
| 30 | PREARBITRATIONLOST | Pre-arbitration lost |
| 31 | SCHEMEARBITRATIONOPEN | Scheme arbitration opened; the amount is held |
| 32 | SCHEMEARBITRATIONWON | Scheme arbitration won |
| 33 | SCHEMEARBITRATIONLOST | Scheme arbitration lost |
Other codes
0 UNPAID and 5 CANCELED are defined, but no payment flow sets them; if you see one, treat the payment as not paid. 2, 4, 6, 7, 8, 19 (DELIVERED, DELIVERING, DELIVERYPENDING, DELIVERYUNKNOWN, FROZEN, SETTLEMENTPENDING) are unused legacy codes the platform refuses to set; if one appears on an old record, read the transaction rather than guess. Code 35 (OPERATIONAL) marks internal transfers and is never a merchant payment — ignore it.
What can follow what
The payment attempt ends at PAID or FAILED. PAID is not the end of the transaction: SETTLED, REFUNDPENDING, REFUNDED and the dispute statuses (21–33) follow it, and a dispute status can arrive even after REFUNDED. Every status from PAID onward means the money was captured at some point, and your handler must keep processing them after the order is paid. The dispute statuses follow the card scheme's process, not a fixed sequence — accept any of them after any other.
| Group | Codes |
|---|---|
| Payment in progress | 10, 11, 12, 13, 14, 15, 16 |
| Captured at some point | 1, 20, 34, 9, 21–33 |
Chargeback (chargeback: true on the transaction) | 24–33 — not the information request 21–23 |
| Amount held — a refund is refused | 24, 27, 28, 30, 31, 33 |
Verify the signature
X-Signature = hex( HMAC-SHA256( key = signing secret, message = X-Timestamp + raw body ) )The key is the signing secret shown when you saved the webhook — not your API secret key. X-Timestamp is Unix seconds, as a decimal string; the digest is lowercase hex with no prefix. Both headers are regenerated on every retry.
const { createHmac, timingSafeEqual } = require('node:crypto');
// rawBody: Buffer with the exact bytes received — never a re-serialised object.
function isValidWebhook(headers, rawBody, secret, toleranceSeconds = 300) {
const ts = String(headers['x-timestamp'] ?? '');
const sig = String(headers['x-signature'] ?? '');
if (!/^\d{1,12}$/.test(ts) || !/^[0-9a-f]{64}$/.test(sig)) return false;
const expected = createHmac('sha256', secret)
.update(ts + rawBody.toString('utf8'))
.digest('hex');
const authentic = timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expected, 'hex'));
const fresh = Math.abs(Date.now() / 1000 - Number(ts)) <= toleranceSeconds;
return authentic && fresh;
}- Verify against the raw request body. Parsing and re-stringifying the JSON changes the bytes and breaks the signature. With Express, mount
express.raw({ type: 'application/json' })on the webhook route. - The platform enforces no time window. The 5-minute freshness check is yours — it is your protection against replayed requests.
Always verify the signature before trusting a webhook. Don't act on an event you can't authenticate.
Acknowledge receipt
Answer with any 2xx status within 10 seconds — the budget covers DNS, TLS and the request, and an idle socket times out after 5 s. Keep the response body under 64 KB; its content is otherwise ignored. Anything else — including a redirect, a timeout, an oversized body, or a host that does not resolve (or resolves to a non-public address) at that moment — counts as a failure and the delivery is retried. Only a webhook configuration that is missing or no longer valid drops a delivery without retries.
Acknowledge first, process later. Store the payload durably and return 2xx quickly, then run any heavy work (order fulfilment, emails) asynchronously.
Retries
| After failure | Next try in |
|---|---|
| 1–2 | 5 s |
| 3 | 10 s |
| 4 | 30 s |
| 5 | 1 min |
| 6 | 10 min |
| 7–8 | 30 min |
| 9–14 | 60 min |
| 15 | given up |
That is about seven hours of retries; the queue is served on a one-second tick, so each delay is a lower bound. The queue survives restarts on our side. A delivery that exhausts its retries is not replayed to you automatically. After fixing an outage, reconcile what you missed by reading the transaction for every open order.
Coalescing, order and duplicates
Three properties your handler must be built for:
- Coalescing. While a delivery for a payment is still waiting — not yet sent, or waiting for a retry — a newer status is merged into it: every field takes the newer value and
statushistorygains the new entry. You may never receive an intermediate status as a request of its own. - No ordering. An older state can arrive after a newer one. Never let a webhook move an order backwards (for example from
PAIDtoPAYING). - Duplicates. A status that arrives while a delivery for the same payment is being sent becomes a separate delivery, and a record is re-sent with an unchanged
statuswhen the payout state or refund totals change. Make your handler idempotent.
A merged status inherits the retry state of the delivery it joined. It does not restart the schedule: if your endpoint has been failing, a new status — even PAID — waits for that delivery's next retry (up to an hour), and if that delivery then uses its last attempt, the new status is lost with it. Never rely on webhooks alone: for any order not in a final state some minutes after you expected it, read the transaction.
Deliveries are merged per transaction and environment: a sandbox and a live transaction never fold into one another — distinguish them by env.
A handler that keeps working after PAID
The webhook is a signal; the transaction is the truth. Treat in-progress and failed statuses as information only (a declined attempt does not end an order — the shopper can try again, under a new reference), and for anything in the captured family read the transaction and store what it says now:
const IN_FLIGHT = new Set([10, 11, 12, 13, 14, 15, 16]);
const CAPTURED = new Set([1, 20, 34, 9, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]);
// Runs from your durable queue; safe to run any number of times per payload.
async function handleWebhook(payload) {
if (typeof payload.type === 'string') return handleSubscriptionEvent(payload);
if (typeof payload.id !== 'string' || typeof payload.status !== 'number') return;
await db.transaction(async (tx) => {
// Find the order: by a transaction reference you stored, else by your externalid
// (for widget payments: your intent externalid, or the intent id).
const order =
(await tx.orders.lockByTransactionRef(payload.id)) ??
(await tx.orders.lockByExternalId(payload.externalid));
if (!order) return; // not ours
if (payload.env !== order.env) return; // never mix live and sandbox
for (const h of payload.statushistory ?? [])
await tx.statusLog.addOnce(order.id, payload.id, h.status); // audit trail, idempotent
// 10–16 and 3: an attempt in progress or declined. Never touches a paid order.
if (IN_FLIGHT.has(payload.status) || payload.status === 3) return;
if (!CAPTURED.has(payload.status)) return; // 0, 5, 35, legacy codes: ignore
// Captured family: read the current record (GET /api/v1/transactions/{id}).
const txn = await securepay.getTransaction(payload.id);
if (!CAPTURED.has(txn.status)) return;
// First capture: fulfil exactly once, after checking amount and currency
// (amountpaid is a JSON number in major units — convert before comparing).
if (!order.paid) {
if (toMinor(txn.amountpaid, txn.currencypaid) !== order.amountMinor ||
txn.currencypaid !== order.currency)
return tx.orders.flagForReview(order.id, 'amount mismatch');
await tx.orders.markPaidOnce(order.id, payload.id);
} else if (order.paidTransactionRef !== payload.id) {
await tx.orders.flagOnce(order.id, `second capture ${payload.id}`); // paid twice: review, refund one
}
// After the payment: settlement, refunds, disputes — per transaction. Overwrite with the
// record just read: repeats are harmless and a stale webhook cannot move anything backwards.
await tx.transactions.setPostPaymentState(order.id, payload.id, {
status: txn.status, // 1, 20, 34, 9, 21–33
chargeback: txn.chargeback,
refunded: txn.refunded_presentment_amount,
pendingRefund: txn.pending_refund_presentment_amount,
payoutStatus: txn.deliverystatus,
});
});
}Run a reconciliation job next to it: every few minutes, read the transaction for orders still awaiting payment and for orders with a refund or dispute in progress. It covers late and lost deliveries and the refund-pending state that is never sent.
Google Pay in the widget — known issue. When the bank requires a redirect 3-D Secure for a Google Pay payment, the payment is captured on the payment platform's own return page and the Payment Intent can stay requires_payment although the money was taken. The transaction still reports PAID (and its webhook carries your externalid). For an intent that stays requires_payment after the shopper approved a wallet payment, check the transaction — GET https://app.securepayapi.com/api/v1/transactions/{transaction_reference} — or the dashboard before asking for another payment.
Subscription events
Agreements created through a subscription Payment Intent send their own events to the same URL, signed with the same secret and delivered through the same queue (same retries; a repeat of an event with the same id and type merges into one still waiting). Recognise them by a string type; their id is an event id, not a transaction reference. Every event carries id, type, environment (0 live, 1 sandbox), occurredAt and merchantid:
type | Extra fields |
|---|---|
subscription.paused, subscription.resumed, subscription.cancellation_scheduled, subscription.cancelled | processorConfigId, subscriptionExternalReference, status, effectiveAt, source ("merchant" or "customer"). A cancellation that takes effect at the end of the period arrives as subscription.cancelled without source. |
subscription.payment_method_recovered, subscription.payment_method_recovery_failed | processorConfigId, subscriptionExternalReference, status, paymentId; provider, providerReference, reason on the failure |
subscription.renewal_paid, subscription.renewal_recovered, subscription.renewal_retry_scheduled, subscription.renewal_recovery_scheduled, subscription.renewal_past_due, subscription.renewal_outcome_unknown | processorConfigId, subscriptionExternalReference, attemptNumber, outcome, paymentId, nextRetryAt; refusalCode, retryReason when applicable. No status. |
subscription.renewal_skipped | processorConfigId, subscriptionExternalReference, amount, currency, periodStart, periodEnd. No status. |
subscription.plan_version_created, subscription.plan_archived, subscription.plan_reactivated | planExternalReference; version on plan_version_created only — no subscriptionExternalReference, no processorConfigId |
Treat id as an opaque string — its format differs between event types. Read each field defensively and answer 2xx to types you do not handle.
The id of a renewal event is not unique per period. It is built from the agreement, the attempt number and the type, so the first attempt of every period carries the same id. Deduplicate renewal events on id together with paymentId and occurredAt (paymentId can be null on an attempt that never reached the processor) — never on id alone, or every renewal after the first is dropped.
There is no subscription.activated or subscription.started webhook: activation is observed by reading the agreement (its status) with your secret key — GET /api/v1/subscriptions/{externalReference}, see Recurring payments — or from the first subscription.renewal_* event.
{
"id": "subscription:0:<processorConfigId>:membership-42:<paymentId>:payment_method_recovered",
"type": "subscription.payment_method_recovered",
"environment": 0,
"processorConfigId": "…",
"subscriptionExternalReference": "membership-42",
"status": "active",
"paymentId": "LU…",
"occurredAt": "2026-10-28T19:05:00.000Z",
"merchantid": "…"
}Allowlist our IP
Webhook requests are sent from 157.230.218.195. If your infrastructure filters inbound traffic, allow this address.