> ## Documentation Index
> Fetch the complete documentation index at: https://docs.services.payward.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Receiving webhooks

> Verify webhook signatures, respond to deliveries, and understand retries.

Payward Services sends each event you subscribe to as an HTTP `POST` with a JSON body, to the URL you registered with
[Create webhook](https://docs.services.payward.com/api-reference/production-live/webhooks/create-webhook.md) (`POST /v1/webhooks`). Its required, nonempty
`events` field selects the event types delivered to that URL. Register one webhook for your account, not one per user:
it receives the events it subscribes to for every user you create.

Before registering, ask your Payward contact to allowlist your callback hostname. Allowlisting is per hostname and per
environment, so a hostname approved for the sandbox is not approved for production.

Every delivery body carries a `type` field naming the event. The individual event pages hold the payload schema and a
complete example, such as
[Deposit received](https://docs.services.payward.com/api-reference/production-live/webhooks/deposit-received.md).

Your endpoint is publicly reachable, so anyone can post to it. Verify the signature on every delivery before you act on
it.

## Delivery headers

Payward Services delivers webhooks with [Svix](https://www.svix.com), which is why these headers carry an `svix-`
prefix. Retries reuse the event's `svix-id`, but each attempt is signed again, with its own `svix-timestamp` and a
matching `svix-signature`:

| Header | Description |
| - | - |
| `svix-id` | Identifier of the event. The same value as the `message_id` of every attempt that delivers it. |
| `svix-timestamp` | Unix timestamp, in seconds, of when this attempt was signed. |
| `svix-signature` | One or more signatures, separated by spaces. Each has the form `v1,<base64>`. |

`svix-id` identifies the event, not the resource it concerns and not the attempt. It is unique within your account, so
two webhooks subscribed to the same event receive that event under the same `svix-id`. If one service receives
deliveries for several webhooks, key your deduplication store on the webhook's `id` together with `svix-id`, or the
second webhook's copy is discarded as a duplicate.

## Verify the signature

> [!NOTE]
>
> These headers follow the Svix signature scheme, so the official Svix libraries verify them, including the timestamp.
> Prefer a library to your own code. Install the `svix` package with `pip install svix` or `npm install svix`, create a
> `Webhook` with your signing secret, and call its `verify` method with the raw body and the headers, as the [Svix
> verification guide](https://docs.svix.com/receiving/verifying-payloads/how) shows. In Python and Node.js, `verify`
> throws a `WebhookVerificationError` when a delivery fails verification: catch it and reject the delivery rather than
> let it become a `500`.

[Create webhook](https://docs.services.payward.com/api-reference/production-live/webhooks/create-webhook.md) returns that webhook's secret in
`data.signing_secret` exactly once. It looks like `whsec_` followed by base64 characters. Store it securely alongside
`data.id`, the webhook's identifier. [Get webhook](https://docs.services.payward.com/api-reference/production-live/webhooks/get-webhook.md)
(`GET /v1/webhooks/{webhook_id}`) does not return it. If you lose it, call
[Rotate webhook secret](https://docs.services.payward.com/api-reference/production-live/webhooks/rotate-webhook-secret.md)
(`POST /v1/webhooks/{webhook_id}/secret/rotate`) and save the replacement.

If one service receives deliveries for several webhooks, give each one a distinct callback path, and select that path's
stored secret before verifying.

The samples below decode the secret inside `verify`, for illustration. In your own service, decode and validate the
configured secret at startup, so a secret that was stored wrong fails there instead of turning every delivery into a
`500`.

**1. Read the raw request body**

Verify against the exact bytes you received. Parsing the JSON and serializing it again changes the bytes, and the
signature no longer matches.

How you reach the raw body depends on your web framework. To supply the `body` and `headers` arguments of the
samples below:

* In Python with Flask, use `request.get_data()` for `body` and `request.headers` for `headers`.
* In Node.js with Express, register the webhook route with `express.raw({ type: 'application/json' })` ahead of any
  `express.json()` middleware that would parse it. Use `req.body` for `body` and `req.headers` for `headers`.

**2. Check the timestamp**

Reject the delivery if `svix-timestamp` is more than five minutes away from your current time, in either
direction. Without that check, someone who captures a delivery can replay it later with its signature intact.

**3. Build the signed content**

Join the ID, the timestamp, and the raw body with periods:

```
<svix-id>.<svix-timestamp>.<body>
```

**4. Compute the signature**

Remove the `whsec_` prefix from the secret and base64-decode the rest to get the key. Compute HMAC-SHA256 over the
signed content with that key, then base64-encode the result.

**5. Compare**

Split `svix-signature` on spaces. For each value, compare your result against the part after `v1,` using a
constant-time comparison. The delivery is authentic if any value matches.

```python Python theme={null}
import base64
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300


def verify(secret, headers, body):
    """Return True when `body` (raw bytes) carries a valid signature."""
    headers = {name.lower(): value for name, value in headers.items()}
    msg_id = headers.get("svix-id")
    timestamp = headers.get("svix-timestamp")
    signatures = headers.get("svix-signature")
    if not (msg_id and timestamp and signatures):
        return False

    try:
        signed_at = int(timestamp)
    except ValueError:
        return False
    if abs(time.time() - signed_at) > TOLERANCE_SECONDS:
        return False

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed_content = f"{msg_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed_content, hashlib.sha256).digest())

    for versioned in signatures.split(" "):
        version, _, signature = versioned.partition(",")
        if version == "v1" and hmac.compare_digest(signature.encode(), expected):
            return True
    return False
```

```javascript Node.js theme={null}
import crypto from 'node:crypto';

const TOLERANCE_SECONDS = 300;

// `body` must be the raw request body as a Buffer or string, and `headers` a plain object with lowercase
// names, such as `req.headers`. Convert a Fetch API `Headers` object with `Object.fromEntries(headers)`.
function verify(secret, headers, body) {
  const msgId = headers['svix-id'];
  const timestamp = headers['svix-timestamp'];
  const signatures = headers['svix-signature'];
  if (!msgId || !timestamp || !signatures) return false;

  const signedAt = Number(timestamp);
  if (!Number.isSafeInteger(signedAt) || Math.abs(Date.now() / 1000 - signedAt) > TOLERANCE_SECONDS) return false;

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const signedContent = Buffer.concat([Buffer.from(`${msgId}.${timestamp}.`), Buffer.from(body)]);
  const expected = crypto.createHmac('sha256', key).update(signedContent).digest('base64');
  const expectedBuffer = Buffer.from(expected);

  return signatures.split(' ').some(versioned => {
    const [version, signature = ''] = versioned.split(',');
    const candidate = Buffer.from(signature);
    return (
      version === 'v1' &&
      candidate.length === expectedBuffer.length &&
      crypto.timingSafeEqual(candidate, expectedBuffer)
    );
  });
}
```

If a delivery fails verification, return `400 Bad Request` and do not process it. That covers a missing header, a
timestamp that is not an integer, and a malformed signature. Verification also fails for genuine deliveries when the
secret you hold is the wrong one, and rejecting those produces retries that can end in
[the webhook being disabled](#webhooks-disabled-after-sustained-failure).

Header names are case-insensitive, and not every framework hands you a mapping that honors that: `dict(request.headers)`
in Python gives you whichever casing arrived. The Python sample lowercases the names before reading them, so a valid
delivery is never rejected for arriving as `Svix-Id`. Node lowercases incoming header names for you.

### Verify during secret rotation

[Rotate webhook secret](https://docs.services.payward.com/api-reference/production-live/webhooks/rotate-webhook-secret.md) returns the new
`signing_secret` once; save it securely. For 24 hours afterwards, deliveries are signed with both the old secret and
the new one, so you can roll the new value out without dropping deliveries. That is why `svix-signature` can hold
several values: verify against each one and accept the delivery if any matches. Once the 24 hours elapse, a receiver
still holding only the old secret fails verification. At most 10 rotations are accepted within a 24-hour window; the
next one returns `400` with the code `limit_reached`.

## Allowlist our source IP addresses

If your endpoint sits behind an IP allowlist, allow all of the addresses for the environment you use. Deliveries leave
through several shared gateways rather than a single address, so allowing only one of them drops most deliveries.

| Environment | Source IP addresses |
| - | - |
| Production | `18.132.230.47/32`, `18.168.240.88/32`, `13.43.0.25/32` |
| Sandbox | `3.11.131.94/32`, `18.168.234.223/32`, `18.168.122.158/32` |

These addresses cover the current delivery path and do not change with routine deployments, restarts, or scaling. If
they ever need to change, your Payward contact tells you in advance. They cover webhooks from the Payward Services API
only; other Payward products deliver from different addresses.

Registering a webhook does not call your endpoint, so there is no separate address to allow for that. Only deliveries
and [test events](https://docs.services.payward.com/api-reference/production-live/webhooks/send-webhook-test-event.md)
(`POST /v1/webhooks/{webhook_id}/test`) reach your URL.

> [!NOTE]
>
> Filtering by source IP address is defense in depth, not authentication. Verify the signature on every delivery
> regardless.

## Respond to a delivery

Return any `2xx` status to acknowledge a delivery. Every other status is treated as a failure and the event is retried,
including `4xx` responses such as `403` from a web application firewall.

Respond within 30 seconds. After that the attempt is abandoned and counts as a failure, even if your handler later
finishes its work. If your processing is slow, verify the signature and durably save the event before returning a
`2xx`, then process the saved event asynchronously. Once a `2xx` arrives within the timeout, that delivery is not
retried, so an event lost after you acknowledge it is not sent again. If you cannot save the event, return a failure
status so the delivery is retried.

There is no per-endpoint delivery rate limit, so size your receiver and its queue for bursts of events.

## Retries

A failed delivery is retried up to seven times, stopping at the first success, so an event is attempted at most eight
times in total. Each delay is measured from the end of the previous attempt, and is randomized by up to 20% in either
direction, so treat these values as approximate:

| Attempt | Sent after the previous attempt | Elapsed since the first attempt |
| - | - | - |
| 1 | — | 0 |
| 2 | 5 seconds | 5 seconds |
| 3 | 5 minutes | \~5 minutes |
| 4 | 30 minutes | \~35 minutes |
| 5 | 2 hours | \~2 hours 35 minutes |
| 6 | 5 hours | \~7 hours 35 minutes |
| 7 | 10 hours | \~17 hours 35 minutes |
| 8 | 10 hours | \~27 hours 35 minutes |

Two cases do not follow the table. An attempt that times out, and one answered with `429 Too Many Requests`, waits at
least one minute before the next attempt, whatever the scheduled delay. A handler that stalls until the 30-second
timeout is therefore retried about 90 seconds after the attempt began, not 5 seconds.

Your response can also carry a `Retry-After` header, as either a number of seconds or an HTTP date. It can push the next
attempt later, to at most twice the scheduled delay, and never makes a retry happen sooner.

After the last attempt the event is not retried automatically. Its attempts stay available for 90 days through
[List webhook attempts](https://docs.services.payward.com/api-reference/production-live/webhooks/list-webhook-attempts.md)
(`GET /v1/webhooks/{webhook_id}/attempts`), which records delivery metadata rather than the event payload or the ID of
the resource the event concerned.

If you know the affected resource's ID, read its current state through that resource's API. For example, keep `data.id`
from [Create quote](https://docs.services.payward.com/api-reference/production-live/swaps/create-quote.md)
(`POST /v1/accounts/{account_id}/quotes`); if you miss a quote event, pass that ID as `quote_id` to
[Get quote](https://docs.services.payward.com/api-reference/production-live/swaps/get-quote.md)
(`GET /v1/accounts/{account_id}/quotes/{quote_id}`) with the same `account_id`, and read `data.status`. That request
needs the `query-open-trades` API key permission. It returns the quote's current state, not the event you missed or a
history of the changes in between.

## Webhooks disabled after sustained failure

A webhook that fails continuously for five days, with no successful delivery in between, is disabled automatically. Any
success inside that window resets it.

Payward does not notify you when this happens, so poll `data.disabled` on
[Get webhook](https://docs.services.payward.com/api-reference/production-live/webhooks/get-webhook.md) if you need to detect it. Re-enable the webhook by
sending `{"disabled": false}` to [Update webhook](https://docs.services.payward.com/api-reference/production-live/webhooks/update-webhook.md)
(`PATCH /v1/webhooks/{webhook_id}`) once you have fixed the cause, then confirm the response reports
`data.disabled: false`.

Re-enabling does not resend what was missed. Events that occurred while the webhook was disabled are not delivered
later, and there is no replay operation, so reconcile the affected resources through their own API read operations.

## Investigate a delivery that did not arrive

[List webhook attempts](https://docs.services.payward.com/api-reference/production-live/webhooks/list-webhook-attempts.md) returns the attempts made to a
webhook, most recent first and paginated: pass the `next_page_token` from one response as `page_token` on the next
request to reach older attempts. There is no filter by event, so group the attempts for one event yourself, by their
shared `message_id`.

Each attempt reports a `status`:

| Status | Meaning |
| - | - |
| `success` | The endpoint returned a `2xx`. Final. |
| `failed` | The attempt failed. Final for that attempt; a retry appears as a separate record. |
| `canceled` | The attempt was not delivered and will not be retried. Final. |
| `sending` | The attempt is in flight. |
| `pending` | The attempt is queued. |

A scheduled retry is not listed before it runs, and no field reports when the next one is due, so a `failed` attempt
that is not yet followed by another record does not tell you whether a retry is still coming.

Each attempt also reports the `response_status_code` your endpoint returned. A `0` means no HTTP response was received
at all, for example a timeout or a connection error. Check that:

* Your handler responds within 30 seconds.
* Your endpoint is reachable over public HTTPS.
* Its certificate chains to a public root other than emSign ECC Root CA G3 or Comodo AAA Services, which Payward no
  longer trusts.
* Your Payward contact has allowlisted the callback hostname for this environment.
* Your own firewall accepts [our source IP addresses](#allowlist-our-source-ip-addresses).

To exercise the path without waiting for a real event, use
[Send webhook test event](https://docs.services.payward.com/api-reference/production-live/webhooks/send-webhook-test-event.md).

## Handle duplicates

The same event can be delivered more than once, for example when your endpoint responds after the 30-second timeout and
the delivery is retried. Treat `svix-id` as the deduplication key. Once the signature verifies, save the event and its
ID together in one atomic operation, before acknowledging the delivery. If the ID is already recorded, return a `2xx`
without saving a second copy; answering anything else has the duplicate retried. A recorded ID means the event is
saved, not that you have finished processing it.

Record an ID only once the signature verifies. Anyone can post to your endpoint, so an ID written before verification
lets an unauthenticated sender suppress the genuine delivery that carries it. Keep the IDs for at least three days,
which covers the retry schedule even when every delay is stretched by `Retry-After`. The five-minute timestamp
tolerance bounds the replay of a captured delivery, not a legitimate retry.

Do not assume events arrive in the order they occurred. One resource can emit several distinct events as its state
changes, each with its own `svix-id`, so deduplicate by `svix-id` and not by the ID of the resource. For deposits,
[Deposit webhook events](https://docs.services.payward.com/tabs/developer-documentation/payments/deposits-and-withdrawals.md#deposit-webhook-events)
explains how the events of one deposit relate.

## Change your endpoint URL

[Update webhook](https://docs.services.payward.com/api-reference/production-live/webhooks/update-webhook.md) changes the destination when you supply a new
`url`, and keeps the existing `signing_secret`, so your verification code continues to work unchanged. Before you
switch, ask your Payward contact to add the new hostname to Payward's callback allowlist for the environment you use,
or deliveries to it fail.
