## Webhooks

The payment platform posts a signed JSON request to the merchant's server when a
transaction changes. Build the receiver from this section; do not assume
anything that is not stated here.

A webhook describes a **transaction** (one payment attempt), not a Payment
Intent:

- `id` is the transaction reference. For a widget payment it is the intent's
  `transaction_reference`. A new attempt on the same intent (for example after a
  wallet decline) gets a **new** reference, so one intent can produce webhooks
  for several transactions.
- `externalid` (same value as `externalReference`) is the intent's `externalid`,
  or the intent `id` when none was set. On a hosted product page it is the
  product id, which is not unique per order.

Confirm a payment synchronously with `GET /api/v1/payment-intents/{id}`. Use
webhooks for everything after it: settlement, refunds, disputes, payouts.

### Configure the endpoint

The merchant sets the URL in the dashboard: Developer → Webhook. There is no
API for it.

The URL must satisfy all of these, or every delivery to it is dropped:

- absolute, at most 2048 characters, scheme `https`;
- no username or password, no `#fragment`;
- port absent or `443`;
- hostname contains a dot, or is a public IP address;
- hostname does not end in `localhost`, `.local`, `.internal` or `.home.arpa`,
  and is not a private or reserved IP address;
- not one of the platform's own domains or a subdomain of one;
- at delivery time the hostname resolves **only** to public addresses;
- valid TLS certificate, TLS 1.2 or newer.

A query string is kept and sent with every request.

The dashboard form checks only that the value is an absolute `http` or `https`
URL of at most 2048 characters. A URL that breaks the other rules can be saved,
but each delivery to it is then dropped without a request and without retries.
Tell the merchant to use an `https` URL that meets every rule.

Signing secret:

- generated when an endpoint's URL is first saved or changed, or on request
  ("New secret"): 64 lowercase hexadecimal characters, shown **once** in the
  dashboard, never retrievable later;
- saving an unchanged URL keeps the secret; when a new one is issued the old
  secret stops working at once, and deliveries still queued or retrying are
  signed with the new secret;
- store it as a server-side secret; it is not the API secret key.

Other rules:

- There is a primary endpoint and, optionally, one additional endpoint. Both
  receive every event; each has its own secret, independent of the other's.
- The primary URL can be changed in the dashboard but not removed.
- An endpoint's URL and secret serve live and sandbox payments; split them on `env`.
- Webhooks are available only once the merchant account is activated.
- While no URL is set, nothing is queued, and nothing is sent later for those
  payments.

### The request

```http
POST <path and query of the webhook URL> HTTP/1.1
Host: <merchant host>
Content-Type: application/json
Accept: application/json
Content-Length: <byte length of the body>
User-Agent: SecurePayAPI-Webhook/1.0
X-Signature: <64 lowercase hexadecimal characters>
X-Timestamp: <unix time in seconds, an integer>

<body>
```

- Always `POST` to port 443. These six headers are the only ones sent.
- The body is compact UTF-8 JSON.
- Redirects are not followed; a `3xx` answer is a failed attempt.
- Requests currently come from `157.230.218.195`. The address can change;
  authenticate with the signature, never with the source IP alone.

### Verify the signature

```
X-Signature = hex( HMAC-SHA256( key = signing secret, message = X-Timestamp + raw body ) )
```

`X-Timestamp` is the decimal string from the header and the body is the exact
bytes received. Both headers are recomputed on every attempt, so a retry
carries a new timestamp and a new signature. There is no prefix and no key id.
The platform enforces no time window; enforce your own.

```js
import crypto from 'node:crypto';

/**
 * rawBody: Buffer holding the exact bytes received.
 * Never JSON.parse and re-stringify before verifying: that changes the bytes.
 */
export function verifySecurePayWebhook(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 = crypto
    .createHmac('sha256', secret)
    .update(ts + rawBody.toString('utf8'))
    .digest('hex');

  const authentic = crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expected, 'hex'));
  const fresh = Math.abs(Date.now() / 1000 - Number(ts)) <= toleranceSeconds;
  return authentic && fresh;
}
```

With Express, mount `express.raw({ type: 'application/json' })` on the webhook
route so `req.body` is the raw `Buffer`. Reject an unverifiable request with a
non-`2xx` status and do not act on it.

### Two kinds of payload

Both kinds arrive at the same URL with the same headers, signature and delivery
rules. Tell them apart first:

| Kind | Recognise it by |
| --- | --- |
| Transaction | **no `type` field**; has `status`, `statustext`, `statushistory` |
| Subscription event | a string `type` starting with `subscription.`; its `id` is an event id, not a transaction reference |

### Transaction payload

There is **no event id and no event type**: the payload is the transaction's
current state. A field whose value is not known yet is absent; this is normal
for payments in progress. Treat every field as optional except `id`, `status`,
`statustext`, `statushistory` and `env`.

| Field | Type | Present | Meaning |
| --- | --- | --- | --- |
| `created` | number or string | always | Creation time: epoch **milliseconds** (number) on payments in progress and on the first `PAID`; may be an ISO-8601 string on finished transactions. Do not rely on it; read `created` (unix seconds) from the transactions API. |
| `id` | string | always | Transaction reference. New ones are `LU` + 14 characters `[0-9A-Z]`; older ones match `[A-Za-z0-9_-]{8,64}`. Store in a 64-character column. |
| `famt` | number | once known | Amount in the payment currency, major units (`49.99`). |
| `currency` | string | once known | Payment currency. |
| `env` | number | always | `0` live, `1` sandbox. |
| `sent` | number or null | once payout data exists | Amount paid out to the merchant. |
| `delivery` | number or null | once known | Payout method: `0` crypto direct, `1` crypto swap, `2` wire, `3` ACH. |
| `paymenttype` | number | always | `0` none, `1` e-commerce, `2` POS, `3` wire, `4` ACH. Not the card scheme. |
| `paymenttypetext` | string | always | Key of `paymenttype`: `NONE`, `ECOM`, `POS`, `WIRE`, `ACH`. Branch on the number. |
| `payment_channel` | number | always | `0` unknown, `1` ecommerce, `2` pos, `3` bank, `4` blockchain. |
| `funding_method` | number | always | `0` unknown, `1` card, `2` ach, `3` wire, `4` usdc, `5` paypal. Apple Pay and Google Pay are `1`. |
| `payment_channel_text` | string | always | `unknown`, `ecommerce`, `pos`, `bank`, `blockchain`. Treat any other value as `unknown`. |
| `funding_method_text` | string | always | `unknown`, `card`, `ach`, `wire`, `usdc`, `paypal`. Treat any other value as `unknown`. |
| `deliverystatus` | number or null | always | Payout status (table below). |
| `deliverystatustext` | string or null | always | Key of `deliverystatus` (`DELIVERYPENDING`); `null` when `deliverystatus` is `null`. Branch on the number. |
| `externalReference` | string or null | when set | The merchant's reference (for widget payments: the intent `externalid`, else the intent `id`). |
| `externalid` | string or null | when set | Same value as `externalReference`. |
| `customerid` | string or null | sometimes | Legacy field. Ignore it. |
| `status` | number | always | Transaction status code (table below). |
| `statustext` | string | always | The status **key** (`PAID`, `CHARGEBACKOPEN`), not the human label the transactions API returns (`Paid`). Branch on `status`. |
| `statushistory` | array of `{status: number, statustext: string}` | always | Normally exactly **one** entry: the current status. More entries only when newer statuses were merged into a delivery that had not gone out; oldest first; the same status may repeat. |
| `merchantid` | string | merchant payments | The merchant id. |
| `invoice` | string | when paid against an invoice | Invoice id (UUID). |
| `order` | `{id: string, version: number}` | when paid for a platform order | |
| `hash` | string or null | crypto payouts only | Payout transaction hash. |
| `chain` | number | crypto payouts only | Chain id. |
| `nonce` | number or null | crypto payouts only | |
| `output_currency` | string | crypto payouts only | Payout token, e.g. `USDC`. |
| `three_ds_status` | string | when recorded | 3-D Secure result. Store and show; do not branch on specific values. |
| `liability_shift_status` | string | when recorded | Liability-shift result. Store and show; do not branch on specific values. |
| `three_ds_eci` | string | when recorded | ECI value. |
| `refund_reason` | string | once a refund was requested | 1–160 characters. |
| `refund_request_source` | string | once a refund was requested | `merchant_api`, `admin` or `automatic_fraud`. |
| `refund_requested_at` | string or number | once a refund was requested | Parse defensively (ISO string or epoch number). |
| `refunded_presentment_amount` | string (decimal) | usually on finished transactions | Confirmed **partial**-refund total in the payment currency. Absent = `"0"`. |
| `pending_refund_presentment_amount` | string (decimal) | usually on finished transactions | Submitted, unconfirmed partial-refund total. Absent = `"0"`. |
| `partial_refund_count` | number | usually on finished transactions | Absent = `0`. |
| `customer_card_surcharge` | object | only when a card surcharge applied | Surcharge quote, amounts and refund split; leaf values are strings or `null`. |

Never in the payload: an event id or type, a card number, BIN, cardholder name
or e-mail, the decline reason, a dispute id, reason code or deadline, a refund
id, a processor reference, USD or fee amounts. Read the transactions API or the
dashboard for those.

#### Example — paid card payment

Values in all three examples are illustrative.

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

#### Example — full refund confirmed

```json
{
  "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",
  "three_ds_status": "authenticated",
  "liability_shift_status": "shifted",
  "three_ds_eci": "05",
  "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`. Do not infer it from the three refund
totals: they track partial refunds.

#### Example — chargeback opened

```json
{
  "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",
  "three_ds_status": "authenticated",
  "liability_shift_status": "shifted",
  "three_ds_eci": "05",
  "refunded_presentment_amount": "0",
  "pending_refund_presentment_amount": "0",
  "partial_refund_count": 0
}
```

A dispute webhook is the ordinary transaction payload with a dispute status and
nothing else about the dispute. The reason and the defense options are in the
dashboard (see Disputes below).

### Transaction status codes

The integer `status` in webhooks and in the transactions API. Webhooks name it
with the key; the transactions API returns the label. There is no code 17 or 18.

| Code | Key | Label in the transactions API | Meaning | Usually followed by |
| --- | --- | --- | --- | --- |
| 10 | `INIT` | Payment Init | Payment opened | further in-progress statuses |
| 11 | `DDC` | Payment DDC | Device data being collected | further in-progress statuses |
| 12 | `AUTH3DS` | Payment 3DS | Authenticating, or a wallet authorizing | further in-progress statuses |
| 13 | `AUTH3DSCHALLENGE` | Payment 3DS Challenge | Issuer challenge required | further in-progress statuses |
| 14 | `AUTH3DSCHALLENGEFORM` | Payment 3DS Form | Challenge form open | further in-progress statuses |
| 15 | `AUTH3DSRESULT` | Payment 3DS Result | Authorized, ready for capture | 16, 3 |
| 16 | `PAYING` | Payment Processing | Capture sent, outcome unknown. Neither paid nor failed; never charge again | 1, 3 |
| 1 | `PAID` | Paid | **Captured** | 20, 34, 9, 21–33 |
| 20 | `SETTLED` | Settled | Captured and settled | 34, 9, 21–33 |
| 3 | `FAILED` | the decline reason, or `Failed` | Declined or failed; this attempt is over | nothing |
| 34 | `REFUNDPENDING` | Refund Pending | Full refund requested, not yet confirmed. **Never sent as a webhook** | 9 |
| 9 | `REFUNDED` | Refunded | Fully refunded: one full refund, or partial refunds adding up to the captured amount | a dispute status can still follow |
| 21 | `INFORMATIONREQUESTED` | Information Requested | Issuer asked for information | any dispute status |
| 22 | `INFORMATIONRESPONDED` | Information Responded | Information supplied | any dispute status |
| 23 | `INFORMATIONEXPIRED` | Information Expired | Information request expired | any dispute status |
| 24 | `CHARGEBACKOPEN` | Chargeback Open | Chargeback open; amount held | any dispute status |
| 25 | `CHARGEBACKREVERSED` | Chargeback Reversed | Resolved for the merchant | any dispute status |
| 26 | `CHARGEBACKWON` | Chargeback Won | Resolved for the merchant | any dispute status |
| 27 | `CHARGEBACKLOST` | Chargeback Lost | Lost or accepted | any dispute status |
| 28 | `PREARBITRATIONOPEN` | Prearbitration Open | Pre-arbitration open; amount held | any dispute status |
| 29 | `PREARBITRATIONWON` | Prearbitration Won | Pre-arbitration won | any dispute status |
| 30 | `PREARBITRATIONLOST` | Prearbitration Lost | Pre-arbitration lost or accepted | any dispute status |
| 31 | `SCHEMEARBITRATIONOPEN` | Scheme Arbitration Open | Scheme arbitration open; amount held | any dispute status |
| 32 | `SCHEMEARBITRATIONWON` | Scheme Arbitration Won | Scheme arbitration won | — |
| 33 | `SCHEMEARBITRATIONLOST` | Scheme Arbitration Lost | Scheme arbitration lost | — |
| 0 | `UNPAID` | Unpaid | Defined; no payment flow sets it. Treat as not paid | — |
| 5 | `CANCELED` | Canceled | Defined; no payment flow sets it. Treat as not paid | — |
| 35 | `OPERATIONAL` | Operational Transfer | Internal transfer, not a payment. Ignore | — |
| 2, 4, 6, 7, 8, 19 | `DELIVERED`, `DELIVERING`, `DELIVERYPENDING`, `DELIVERYUNKNOWN`, `FROZEN`, `SETTLEMENTPENDING` | `Unknown: <code>` | Unused legacy codes the platform refuses to set. On an old record, read the transaction and escalate; do not guess | — |

The last column lists the usual paths. Do not hard-code it as a strict state
machine: accept any captured-family status after `PAID`, and any dispute status
after any other.

Groupings to code against:

| Group | Codes |
| --- | --- |
| Payment in progress | 10, 11, 12, 13, 14, 15, 16 |
| End of the payment attempt | 1 (`PAID`), 3 (`FAILED`) |
| Captured at some point | 1, 20, 34, 9, 21–33 |
| `chargeback: true` in the transactions API | 24–33 (not 21–23) |
| Amount held; a refund is refused | 24, 27, 28, 30, 31, 33 |

`PAID` ends the payment attempt, not the transaction. Settlement, refunds and
disputes follow it, and a dispute can arrive even after `REFUNDED`.

#### Payout status

`deliverystatus` describes the payout to the merchant, independently of
`status`:

| Code | Key (webhook) | Label (transactions API) |
| --- | --- | --- |
| 0 | `NONE` | None |
| 1 | `DELIVERYPENDING` | Delivery Pending |
| 2 | `DELIVERING` | Delivering |
| 3 | `FAILED` | Failed |
| 4 | `DELIVERYUNKNOWN` | Unknown if failed or succeeded |
| 5 | `DELIVERED` | Delivered |
| 6 | `FROZEN` | Frozen |
| 7 | `REFUNDED` | Refunded |
| null | null | Not Set |

### What triggers a webhook

A webhook is queued when a transaction's `status` changes, and also when its
payout status changes while `status` stays the same.

| What happened | `status` received | Notes |
| --- | --- | --- |
| Payment opened (card, Apple Pay, Google Pay) | 10 `INIT` | |
| Device-data collection page served | 11 `DDC` | |
| 3-D Secure authentication started | 12 `AUTH3DS` | |
| Issuer challenge required | 13 `AUTH3DSCHALLENGE` | |
| Challenge form opened | 14 `AUTH3DSCHALLENGEFORM` | |
| Authorization complete, ready for capture | 15 `AUTH3DSRESULT` | |
| 3-D Secure failed, or any failure before or at capture | 3 `FAILED` | |
| Capture submitted | 16 `PAYING` | Outcome not known yet. |
| Capture succeeded | 1 `PAID` | `deliverystatus` `1` in live; in sandbox a simulated payout follows at once (`deliverystatus` `5`). |
| Delayed capture completed (authorized earlier, captured on shipment) | 1 `PAID` | |
| USDC invoice paid | the transaction's current status | |
| Processor settlement recorded | 20 `SETTLED` | Only when the status actually changes. |
| Payout status changed | **the same `status`**, new `deliverystatus` | |
| Full refund accepted, nothing paid out yet (always in sandbox) | 9 `REFUNDED` | Right after the refund request. |
| Full refund accepted after the payout (live) | **nothing** | Moves to 34 `REFUNDPENDING` silently. |
| Processor confirms the full refund | 9 `REFUNDED` | |
| Partial refund confirmed | the same `status`, or 9 `REFUNDED` once confirmed partial refunds equal the captured amount | Refund totals change. |
| Partial refund failed or reversed by the processor | the same `status` | Refund totals change. |
| Dispute notification that changes the status | the dispute status, 21–33 | |
| Platform operators correct a status by hand | that status | |
| Subscription lifecycle, renewal and plan events | an event payload (`type: "subscription.*"`) | See Subscription events. |

Dispute notification → status: request for information → 21 (22 if answered,
23 if expired); information supplied → 22; chargeback notification or
chargeback → 24 (27 if lost or accepted); second chargeback → 27; chargeback
reversed → 25 (26 if won); pre-arbitration opened or declined → 28;
pre-arbitration accepted or lost → 30; pre-arbitration won → 29; scheme
arbitration → 31, won → 32, lost → 33; defense period ended → 27; issuer
response time-frame expired → 26.

#### What is not sent

- **The pending state of a full refund.** No webhook carries `status: 34`.
  Either `REFUNDED` arrives, or nothing arrives until 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. Nothing is replayed when a
  URL is added later.

### Delivery rules

| Rule | Value |
| --- | --- |
| Success | any HTTP status 200–299 |
| Response body | content ignored; more than 64 KiB makes the attempt fail |
| Deadline per attempt | 10 s in total, including DNS and TLS; 5 s without data on the socket |
| Failure | any other status, a redirect, a timeout, an oversized response, a TLS error, a host that does not resolve or resolves to a non-public address |
| Attempts | 15 in total; after the 15th failure the delivery is abandoned and never resent automatically |
| Wait after failed attempt | 1st and 2nd: 5 s · 3rd: 10 s · 4th: 30 s · 5th: 60 s · 6th: 10 min · 7th and 8th: 30 min · 9th to 14th: 60 min — about 7 h 12 min in total |
| Timing | waits are minimums; the queue is scanned about once a second, and a delivery is not necessarily sent the instant the change happens |
| Restarts | the queue survives platform restarts |
| Ordering | not guaranteed between separate deliveries |

Answer `2xx` as soon as the payload is stored durably; process afterwards.

#### Merging

While a delivery for a transaction is still waiting — not yet sent, or waiting
for a retry — a newer payload for the same transaction (same environment) is
**merged into it** instead of being queued separately:

- every field takes the newer value;
- `statushistory` becomes the old entries followed by the new ones.

**A merged status inherits the attempt count and the next-retry time of the
delivery it joined.** It does not restart the schedule:

- if the endpoint has been failing, a new status — even `PAID` — waits for that
  delivery's next retry, up to 60 minutes;
- if that delivery then fails its last attempt, the new status is lost with it.

A payload that arrives while a delivery for the same transaction is being sent
at that instant becomes a separate delivery. The same status can therefore
arrive twice, and two deliveries for one transaction can complete in either
order.

**Never rely on webhooks alone.** Run a reconciliation job (below).

#### Deliveries dropped without retries

- No webhook URL configured: nothing is queued.
- At send time the URL was removed, the secret is missing, or the URL breaks
  the rules in "Configure the endpoint": the delivery is dropped at once — no
  request, no retries.

A URL that passes the rules but resolves to a non-public address fails each
attempt and goes through the normal 15 attempts.

### Handler

The handler must survive all of the following, because all of them happen:

- there is no event id to deduplicate on;
- the same status arrives more than once (payout changes, partial refunds,
  concurrent deliveries);
- an older payload arrives after a newer one;
- one request carries several statuses in `statushistory`;
- one order can have several transactions (one per attempt), including a
  declined one before a paid one, and — rarely — two captured ones;
- statuses keep arriving **after** `PAID`: settlement, refunds, disputes;
- a status arrives late, or never.

```js
import express from 'express';
import { verifySecurePayWebhook } from './verify.js';

const app = express();

const IN_FLIGHT = new Set([10, 11, 12, 13, 14, 15, 16]);
// Captured at some point: paid, settled, refund pending, refunded, disputes.
const CAPTURED = new Set([1, 20, 34, 9, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]);

app.post('/webhooks/securepay', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!verifySecurePayWebhook(req.headers, req.body, process.env.SECUREPAY_WEBHOOK_SECRET)) {
    return res.status(401).end();               // non-2xx: the platform retries
  }
  const payload = JSON.parse(req.body.toString('utf8'));
  await inbox.enqueue(payload);                 // store durably BEFORE answering
  res.status(204).end();                        // well inside 10 seconds
});

// Worker: safe to run any number of times for the same payload.
async function handle(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 already stored, else by externalid
    // (widget payments: the 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: ignore
    if (payload.env !== order.env) return;                      // never mix live and sandbox

    // 1. Audit trail: every status this delivery mentions (insert-if-absent).
    for (const h of payload.statushistory ?? [])
      await tx.statusLog.addOnce(order.id, payload.id, h.status);

    // 2. In progress (10–16) or declined (3): information only. A declined attempt does not
    //    end the order (the shopper may retry under a new reference), and neither can ever
    //    touch a paid order. Pre-capture state comes from the Payment Intent.
    if (IN_FLIGHT.has(payload.status) || payload.status === 3) return;
    if (!CAPTURED.has(payload.status)) return;                  // 0, 5, 35, legacy codes

    // 3. Captured family: the webhook is a signal; the transaction record is the truth.
    const txn = await securepay.getTransaction(payload.id);     // GET /api/v1/transactions/{id}
    if (!CAPTURED.has(txn.status)) return;

    // First capture: fulfil exactly once, after checking amount and currency.
    if (!order.paid) {
      if (toMinorUnits(txn.amountpaid, txn.currencypaid) !== order.amountMinor ||
          txn.currencypaid !== order.currency)
        return tx.orders.flagOnce(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
    }

    // 4. After the payment, per transaction: overwrite with the record just read.
    //    Repeats are harmless; 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,                               // true for 24–33
      refunded: txn.refunded_presentment_amount,                // decimal strings
      pendingRefund: txn.pending_refund_presentment_amount,
      payoutStatus: txn.deliverystatus,
    });
  });
}

// Reconciliation: run every few minutes. Covers late and lost webhooks and the
// refund-pending state that is never sent.
async function reconcile() {
  for (const t of await db.transactions.findOpenOlderThan('5 minutes')) {
    // open = order awaiting payment, refund requested, or dispute in progress
    const txn = await securepay.getTransaction(t.ref);
    await handle({ id: txn.id, status: txn.status, env: t.env, externalid: txn.externalid,
                   statushistory: [{ status: txn.status }] });
  }
}
```

Rules the handler encodes; keep them when adapting it:

1. Verify the signature on the raw bytes before parsing.
2. Answer `2xx` only after the payload is stored durably.
3. Never let statuses 10–16 or 3 change a paid order; never let one declined
   attempt fail an order whose intent can still be paid.
4. `PAID` means "captured", not "finished": keep processing 20, 34, 9 and
   21–33 afterwards, including a dispute after `REFUNDED`.
5. Make fulfilment a once-only action keyed on the order, and check
   `amountpaid` and `currencypaid` first.
6. For anything after capture, act on the transaction record just read, not on
   the webhook's fields.
7. Run the reconciliation job; it is not optional.

#### Google Pay in the widget — known defect

When the bank requires a redirect 3-D Secure for a Google Pay payment made in
the widget, the payment is captured on the platform's own return page and the
Payment Intent can stay `requires_payment` although the money was taken. The
transaction still moves to `PAID` and its webhook carries the intent's
`externalid`. For an intent that stays `requires_payment` after the shopper
approved a wallet payment, read
`GET https://app.securepayapi.com/api/v1/transactions/{transaction_reference}`
(or check the dashboard) before asking for another payment. Never ask for money
again while a transaction for that order reads `PAID` or `PAYING`.

## Subscription events

Subscription events are described field by field in the subscriptions chapter.
For the webhook receiver, apply these rules:

- Recognise them by a string `type` starting with `subscription.`. They arrive
  at the same URL with the same signature, queue, retries and merge rule (a
  repeat with the same `id` and `type` merges into one still waiting).
- Every event has string `id`, string `type`, numeric `environment` (`0` live,
  `1` sandbox), `occurredAt` and `merchantid` (lower case; there is no
  `merchantId`).
- Treat `id` as opaque; its format differs between event types. Never parse it.
- **Deduplicate renewal events (`subscription.renewal_*`) on `id` + `paymentId`
  + `occurredAt`, never on `id` alone.** A renewal event's `id` is built from
  the agreement, the attempt number and the type, so attempt 1 of every period
  has the same `id`. `paymentId` can be `null`.
- Renewal and plan events carry no `status`; read the agreement for its state.
- There is no activation event; read the agreement
  (`GET /api/v1/subscriptions/{externalReference}`).
- Answer `2xx` to types you do not handle.

## Transactions API

### `GET https://app.securepayapi.com/api/v1/transactions/{id}` — read one transaction

The authoritative current state of one transaction. Use it to confirm a capture
before fulfilment, to reconcile, and after every captured-family webhook.

#### Authentication

`Authorization: Bearer sp_secret_…` — the merchant's secret key. Server only;
never from a browser. A publishable key (`sp_client_…`) is refused. The key
returns only the merchant's own transactions.

#### Path parameter

| Parameter | Type | Rules |
| --- | --- | --- |
| `id` | string | Transaction reference: the intent's `transaction_reference`, the webhook `id`, or the reference shown in the dashboard. Must match `[A-Za-z0-9_-]{1,64}` (surrounding whitespace is trimmed). **Not** the Payment Intent id. |

No query parameters and no body. Only `GET`.

#### Example

```bash
curl https://app.securepayapi.com/api/v1/transactions/LUZH24T2E65K3NN4 \
  -H "Authorization: Bearer sp_secret_…"
```

#### Response `200`

The platform's transaction record, unchanged:

```json
{
  "id": "LUZH24T2E65K3NN4",
  "payin_method": "card",
  "card_brand": "visa",
  "payment_network": null,
  "payment_provider": "…",
  "payment_provider_config_id": null,
  "created": 1789123456.789,
  "transaction": null,
  "status": 1,
  "statustext": "Paid",
  "paymenttype": 1,
  "paymenttypetext": "ECOM",
  "payment_channel": 1,
  "funding_method": 1,
  "payment_channel_text": "ecommerce",
  "funding_method_text": "card",
  "deliverystatus": 1,
  "deliverystatustext": "Delivery Pending",
  "url": null,
  "cardholder": "Jordan Lee",
  "card": "411111xxxxxx1111",
  "cardbank": "Example Bank",
  "cardcountry": "US",
  "amountpaid": 49.99,
  "currencypaid": "USD",
  "usdpaid": 49.99,
  "usdfee": 1.75,
  "tokenssent": null,
  "product": null,
  "chain": null,
  "token": null,
  "nonce": null,
  "externalReference": "ORDER-42",
  "externalid": "ORDER-42",
  "invoice": null,
  "order": null,
  "merchantid": "7TTR77ZC",
  "chargeback": false,
  "processorid": "…",
  "refund_reason": null,
  "refund_request_source": null,
  "refund_requested_at": null,
  "refunded_presentment_amount": "0",
  "pending_refund_presentment_amount": "0",
  "partial_refund_count": 0,
  "refunds": []
}
```

| Field | Type | Meaning |
| --- | --- | --- |
| `id` | string | Transaction reference. The only identifier. |
| `created` | number | Unix **seconds**, may be fractional. |
| `status` | number | Status code (table in Webhooks). Code against it. |
| `statustext` | string | Human label (`Paid`, `Settled`). For `FAILED` (3) it is the decline reason. Never branch on it. |
| `amountpaid` | number | Amount in the payment currency, major units. |
| `currencypaid` | string | Payment currency. |
| `usdpaid` | number | Reporting amount in USD (not the settlement amount). |
| `usdfee` | number | Platform fee in USD. |
| `payin_method` | string | `card`, `applepay`, `googlepay`, `ach`, `wire`, `usdc`, `paypal`, `unknown`. |
| `card_brand` | string or null | Normalized scheme (`visa`, `mastercard`, `amex`, `discover`) for card payments, else `null`. |
| `payment_network` | string or null | Confirmed executed network (e.g. `pulse`, `visa`), else `null`. Never infer it from the brand. |
| `payment_provider`, `payment_provider_config_id` | string or null | Processor that executed the payment and its configuration. |
| `processorid` | string or null | Processor reference of the payment. |
| `card` | string or null | Masked card number. |
| `cardholder` | string or null | Name on the card. |
| `cardbank`, `cardcountry` | string or null | Issuer name and country. |
| `paymenttype`, `paymenttypetext` | number, string | Channel (`1`/`ECOM` …), not the scheme. |
| `payment_channel`, `payment_channel_text`, `funding_method`, `funding_method_text` | number, string | As in the webhook. |
| `deliverystatus`, `deliverystatustext` | number or null, string | Payout status and its label (table in Webhooks). |
| `tokenssent`, `token` | number or null, string or null | Payout amount and currency. |
| `chain`, `nonce`, `transaction`, `url` | | Crypto payout chain, nonce, payout reference and block-explorer link; `null` otherwise. |
| `externalReference`, `externalid` | string or null | The merchant's reference, same value twice. |
| `product` | number or null | SKU recorded on the payment. |
| `invoice` | string or null | Invoice id. |
| `order` | `{id, version}` or null | Platform order. |
| `merchantid` | string | The merchant id. |
| `chargeback` | boolean | `true` for statuses 24–33. `false` during an information request (21–23). |
| `refund_reason`, `refund_request_source`, `refund_requested_at` | string or null | Set once a refund was requested. Source: `merchant_api`, `admin`, `automatic_fraud`. |
| `refunded_presentment_amount`, `pending_refund_presentment_amount` | string (decimal) | Confirmed and pending partial-refund totals; default `"0"`. |
| `partial_refund_count` | number | Default `0`. |
| `refunds` | array | Refunds of the transaction; default `[]`. Do not depend on the element shape. |
| `customer_card_surcharge` | object | Only when a card surcharge applied. |

Ignore unknown fields; code only against the fields you need.

#### Errors

All errors are JSON `{"error": "<text>"}`.

| HTTP | `error` | When | Action |
| --- | --- | --- | --- |
| 401 | `Unauthorized — provide a valid secret key as a Bearer token` | header missing or not `Bearer`; token not an `sp_secret_` key; unknown key; merchant account not yet activated on the platform. Header `WWW-Authenticate: Bearer`. | Fix the key. Do not retry unchanged. |
| 403 | `Account is not active` | merchant account suspended or not active | Stop; the merchant must contact support. |
| 404 | `Transaction not found` | unknown id; another merchant's transaction; malformed id; **or the payment platform could not be reached** | For a reference you know exists, retry with backoff before concluding anything. |

#### Decision table

| Transaction read | Meaning | Do |
| --- | --- | --- |
| `status` 1 or 20, amount and currency match | Paid | Fulfil once. |
| `status` 1 or 20, amount or currency differ | Paid, wrong amount | Do not fulfil; flag for review. |
| `status` 10–15 | Attempt in progress | Wait; read again later. |
| `status` 16 | Capture sent, outcome unknown | Do not charge again; read again later. |
| `status` 3 | This attempt declined | The order is not paid by this transaction; the shopper may pay again (new reference). |
| `status` 34 | Full refund pending | Treat as refunding; read again later. |
| `status` 9 | Fully refunded | Reverse fulfilment as your policy says. |
| `status` 21–23 | Information request | Watch the dashboard; no action available there. |
| `status` 24 | Chargeback open, amount held | Respond in the dashboard (Disputes). Do not refund. |
| `status` 25, 26, 29, 32 | Dispute resolved for the merchant | Record. |
| `status` 27, 30, 33 | Dispute lost or accepted | Record the loss; do not refund. |
| `status` 28, 31 | Pre-arbitration / arbitration open, amount held | Record; do not refund. |
| `404` | Unknown or unreachable | Retry with backoff; do not treat as unpaid. |

## Disputes

Merchants handle disputes in the dashboard. There is no public API to accept or
defend a dispute.

### How a dispute is reported

- Each status change reaches the webhook as the ordinary transaction payload
  with the dispute status (21–33). It carries no reason, amount or deadline.
- Issuer comments, fraud notifications and repeated notifications that do not
  change the status send no webhook.
- The transactions API shows the state: `status` and `chargeback` (`true` for
  24–33).
- A dispute status can follow `PAID`, `SETTLED` or `REFUNDED`.

### Lifecycle

| Stage | Codes | Amount |
| --- | --- | --- |
| Information request | 21 requested, 22 responded, 23 expired | not held |
| Chargeback | 24 open, 25 reversed, 26 won, 27 lost | held while 24; lost on 27 |
| Pre-arbitration | 28 open, 29 won, 30 lost | held while 28; lost on 30 |
| Scheme arbitration | 31 open, 32 won, 33 lost | held while 31; lost on 33 |

`WON` or `REVERSED` = resolved for the merchant; `LOST` = against the merchant.
Accepting a chargeback ends in 27. A chargeback not defended before its defense
period ends becomes 27. Stages follow the card scheme's process, not a fixed
order. A refund is refused in 24, 27, 28, 30, 31 and 33.

### Dashboard: what is shown

On the transaction page a disputed transaction (24–33) has a Chargeback card
with, when the processor provides them: the reason code and description, issuer
comments with dates, issuer documents (open or download), and the required
evidence (document type codes and requirement level). The response deadline is
**not** shown in the dashboard.

### Dashboard: respond

Available **only while `status` is 24 (`CHARGEBACKOPEN`)** and only on an
active account. Not during 21–23, 28 or 31.

**Accept** — concede. Confirmed once more in the dashboard; irreversible.

**Defend** — only when the processor reports the dispute as defendable and
lists at least one defense reason. Otherwise the card says the requirements are
unavailable and offers Refresh requirements; Accept stays available.

Defense input:

| Item | Rule |
| --- | --- |
| Defense reason | exactly one, from the processor's current list |
| Files | up to 5; `application/pdf`, `image/jpeg`, `image/tiff`; PDF ≤ 2 MB, image ≤ 10 MB each |
| Written note | optional, ≤ 1000 characters; rendered to a PDF with the merchant's letterhead and the transaction details; submitted first |
| Document type | required for every file and for the note; must be one of the chosen reason's document types |
| Submission size | ≤ 16 MB in total, including the generated note PDF |

Requirement levels per document type: `Required`, `AlternativeRequired`,
`OneOrMore`, `Optional`. The dashboard accepts the defense only when:

- every type that is not `Optional` has at least one document — a document
  already supplied to the processor (marked **Already supplied**) counts;
- every type that is not `OneOrMore` has at most one document — including an
  already supplied one, so such a type cannot receive more.

Several items under one single-document type are merged into one PDF of at most
2 MB. TIFF images, encrypted PDFs, and PDFs with form fields, annotations or
attachments cannot be merged; convert them to a static PDF first. `OneOrMore`
types keep separate documents.

On submit the requirements are read again from the processor. If the chosen
reason or its document types changed, nothing is sent; the dashboard shows the
current requirements and keeps the text and files. If the processor does not
confirm the defense, refresh the transaction and check its status before
submitting again.

The outcome arrives later as a status change (webhook and transactions API).

### Rules

- Respond well before the deadline; it is not shown in the dashboard.
- Never refund a transaction in 24, 27, 28, 30, 31 or 33 — the refund is
  refused and the disputed amount is already being returned.
- Do not treat 21–23 as a chargeback: `chargeback` is `false` and nothing can
  be submitted in the dashboard.
- Keep processing dispute statuses after `REFUNDED`.
