# Webhooks

> Receive signed, real-time notifications at your own HTTPS endpoint when things happen in your Nexpay account.

Webhooks let Nexpay tell your systems when something happens in your account, instead of your integration polling the API. You register an HTTPS endpoint, and Nexpay sends it a signed `POST` request each time a subscribed event occurs.

---

## How webhooks work

1. You register an HTTPS **destination URL** in the Nexpay Dashboard and choose the events it should receive.
2. Nexpay checks that you control the URL with a one-time [verification challenge](#one-time-verification-challenge).
3. When a subscribed event happens — for example, a payment intent is created — Nexpay sends a JSON payload to your URL, signed with the endpoint's secret.
4. Your endpoint [verifies the signature](#verifying-signatures), returns a `2xx` response quickly, and processes the event.

If your endpoint doesn't answer with a `2xx`, Nexpay [retries the delivery](#retries) for about a day.

Treat webhooks as a fast signal, not your only source of truth. In rare cases, such as an outage on our side, an event may not be sent at all, so [reconcile important state](#reconcile-with-the-api) through the API.

See the [events reference](/docs/webhooks/events.md) for every event Nexpay sends.

---

## The event payload

Every delivery is a `POST` with a JSON body in the same envelope:

```json
{
  "event": "paymentIntents.create",
  "tenantId": "51",
  "messageId": "22583937982654680",
  "version": "v2",
  "data": {
    "id": "6af4ece9e1b0571e8f75b918",
    "status": "draft",
    "useCase": "education_provider_tuition",
    "deliveryMode": "reusable_payment_link",
    "name": "Term 1 tuition link",
    "amountMode": "payer_fixed",
    "recipients": [
      {
        "role": "public_payee",
        "connectorPayeeId": 51,
        "amount": { "payerAmount": "10", "currency": "AUD" },
        "reference": "STU-12345"
      }
    ],
    "createdAt": "2026-11-11T22:32:09.633Z",
    "updatedAt": "2026-11-11T22:32:09.633Z"
  }
}
```

The `data` object above is shortened. A real delivery carries the full object — see the [events reference](/docs/webhooks/events.md).

| Property | Description |
| --- | --- |
| `event` | The event type, in `resource.action` form. Use it to decide how to process the delivery. The shape of `data` depends on it. |
| `tenantId` | Your Nexpay account. If one endpoint receives events for several Nexpay accounts, use this to tell them apart. |
| `messageId` | Unique per event, and the same on every retry of that event. Use it to [ignore duplicates](#handle-duplicate-events). |
| `version` | The API version the `data` object follows. Currently `v2`, matching the [v2 API](https://v2-spec.nexpay.com.au). |
| `data` | The object the event is about, in the same shape the v2 API returns it. |

### Request headers

| Header | Description |
| --- | --- |
| `Signature-Header` | `sha256=<hex>` — an HMAC-SHA256 of the raw request body, keyed with your webhook secret. See [verifying signatures](#verifying-signatures). |
| `Webhook-Signature` | `t=<unix seconds>,v1=<hex>` — an HMAC-SHA256 of `<t>.<raw body>`, keyed with your webhook secret. It includes the time of the attempt, so you can reject replayed requests. |
| `Webhook-Delivery-Attempt` | `1` for the first attempt, `2` for the first retry, and so on. |
| `Content-Type` | `application/json` |

---

## Setting up a webhook

Only a signed-in dashboard user can add or remove webhooks. API keys can't manage them.

1. Open the Nexpay Dashboard.
2. Click your avatar in the top-right corner and select **Settings**.
3. Open the **Webhooks** tab and click **Add Webhook**.
4. Enter your **Endpoint URL**. It must use `https`.
5. Choose the events to receive.
6. Make sure your endpoint answers the [verification challenge](#one-time-verification-challenge), then click **Add Webhook**.
7. Copy the **signing secret** and store it in your secrets manager.

> **Warning — Save your signing secret**
>
> Nexpay generates the signing secret in your browser and shows it **once**. It can't be retrieved later. If you lose it, remove the webhook and add it again to get a new secret.

The secret looks like `whsec_` followed by 64 hex characters. Use the **whole string**, including the `whsec_` prefix, as the HMAC key.

To stop deliveries, click **Remove** next to the webhook in **Settings → Webhooks**. Once a webhook is removed, Nexpay stops queued and future deliveries to it. An attempt already in progress at that moment may still arrive. Your account can have up to 100 active webhooks.

---

## One-time verification challenge

When you add a webhook, Nexpay first sends a `GET` request to your URL with a random `validationToken` query parameter:

```
GET https://example.com/webhooks/nexpay?validationToken=5f2c0d…
```

Your endpoint must reply within 30 seconds with a `2xx` status and the token, exactly as received, as a plain-text body. If it doesn't, the webhook isn't created and the dashboard shows an error.

**Node.js (Express)**

```javascript
app.get('/webhooks/nexpay', (req, res) => {
  const { validationToken } = req.query

  if (typeof validationToken !== 'string') {
    return res.status(400).send('Missing validationToken')
  }

  res.type('text/plain').send(validationToken)
})
```

**PHP (Laravel)**

```php
Route::get('/webhooks/nexpay', function (Request $request) {
    $token = $request->query('validationToken');

    if (! is_string($token)) {
        return response('Missing validationToken', 400);
    }

    return response($token, 200)->header('Content-Type', 'text/plain');
});
```

Your URL must answer both `GET` (the challenge) and `POST` (deliveries).

---

## Verifying signatures

Every delivery is signed with your webhook secret, so you can confirm it came from Nexpay and wasn't changed on the way. Verify one of the two signature headers before you trust a delivery. We recommend `Webhook-Signature`, because its timestamp also protects you against replayed requests.

> **Warning — Sign the raw body, not the parsed one**
>
> Compute the HMAC over the **raw request body** — the exact bytes Nexpay sent. Parsing the JSON and serialising it again can reorder keys or change whitespace, and then no signature will match. In Express, capture the raw body with `express.json({ verify: (req, _res, buf) => { req.rawBody = buf } })`.

### Using `Webhook-Signature` (recommended)

1. Split the header on `,` to get `t` and `v1`.
2. Compute HMAC-SHA256 of the string `<t>.<raw body>` (the timestamp, a dot, then the raw body) with your secret, as hex.
3. Compare it with `v1` in constant time.
4. Reject the delivery if `t` is more than 5 minutes old.

Each retry carries a fresh `t`, so a delivery that's retried later still passes the time check.

**Node.js (Express)**

```javascript
import crypto from 'node:crypto'
import express from 'express'

const app = express()
const secret = process.env.NEXPAY_WEBHOOK_SECRET // the whole whsec_… string
const TOLERANCE_SECONDS = 5 * 60

app.post(
  '/webhooks/nexpay',
  express.json({ verify: (req, _res, buf) => { req.rawBody = buf } }),
  (req, res) => {
    const header = req.get('Webhook-Signature') ?? ''
    const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')))
    const t = Number(parts.t)

    const expected = crypto
      .createHmac('sha256', secret)
      .update(`${parts.t}.`)
      .update(req.rawBody)
      .digest('hex')

    const valid =
      /^[0-9a-f]{64}$/i.test(parts.v1 ?? '') &&
      crypto.timingSafeEqual(Buffer.from(parts.v1, 'hex'), Buffer.from(expected, 'hex'))
    const fresh = Math.abs(Date.now() / 1000 - t) <= TOLERANCE_SECONDS

    if (!valid || !fresh) {
      return res.status(401).send('Invalid signature')
    }

    // Acknowledge first, then process asynchronously.
    res.sendStatus(204)
    handleEvent(req.body).catch((error) => console.error('Webhook processing failed', error))
  },
)
```

**PHP (Laravel)**

```php
Route::post('/webhooks/nexpay', function (Request $request) {
    $secret = config('services.nexpay.webhook_secret'); // the whole whsec_… string
    $raw = $request->getContent();

    parse_str(str_replace(',', '&', $request->header('Webhook-Signature', '')), $parts);
    $t = (int) ($parts['t'] ?? 0);
    $expected = hash_hmac('sha256', $t . '.' . $raw, $secret);

    $valid = is_string($parts['v1'] ?? null) && hash_equals($expected, $parts['v1']);
    $fresh = abs(time() - $t) <= 300;

    if (! $valid || ! $fresh) {
        return response('Invalid signature', 401);
    }

    ProcessNexpayWebhook::dispatch(json_decode($raw, true));

    return response()->noContent();
});
```

### Using `Signature-Header`

`Signature-Header` is `sha256=` followed by the hex HMAC-SHA256 of the raw body. Compute the same value and compare the whole string in constant time:

```javascript
const expected =
  'sha256=' + crypto.createHmac('sha256', secret).update(req.rawBody).digest('hex')
const received = req.get('Signature-Header') ?? ''

const valid =
  /^sha256=[0-9a-f]{64}$/i.test(received) &&
  crypto.timingSafeEqual(Buffer.from(received.toLowerCase()), Buffer.from(expected))
```

It has no timestamp, so it doesn't protect against replays on its own. Pair it with [duplicate handling](#handle-duplicate-events) on `messageId`.

---

## Delivery behaviour

### Responses

Nexpay treats any `2xx` status as delivered. Anything else — a `3xx`, `4xx` or `5xx` status, no answer within 30 seconds, or a connection error — counts as a failed attempt.

Nexpay doesn't follow redirects, so a `301` or `302` is a failure. Register the final URL.

### Retries

After a failed attempt, Nexpay tries again on this schedule:

| Attempt | Sent after the previous attempt |
| --- | --- |
| 2 | 1 minute |
| 3 | 5 minutes |
| 4 | 30 minutes |
| 5 | 2 hours |
| 6 | 6 hours |
| 7 | 12 hours |
| 8 | 6 hours |

That's 8 attempts over about 27½ hours.

If your endpoint responds `410 Gone`, Nexpay stops retrying that event straight away. The webhook stays active for future events.

### Deactivation

If a delivery has been waiting for 24 hours or more and its next attempt also fails, Nexpay switches the webhook off. The last retry comes after that point, so an event that fails every attempt also switches the webhook off. Once it's off:

- It no longer appears in **Settings → Webhooks**.
- Events that hadn't been delivered yet are dropped.
- Events created while it's off aren't queued and won't be sent later.

Nexpay doesn't currently send a notification when this happens, so monitor your endpoint's errors and watch for the webhook disappearing from the list.

To start receiving events again, fix your endpoint, then add the webhook again. It gets a new signing secret. Use the API to fetch anything you missed in the meantime.

### Ordering

Nexpay doesn't guarantee that events arrive in the order they happened, and a retried event can arrive after newer ones. Use the timestamps in `data`, such as `updatedAt`, and fetch the latest state from the API when the order matters.

---

## Best practices

### Handle duplicate events

Your endpoint may occasionally receive the same event more than once, for example if your `2xx` response was lost. Record the `messageId` of each event you've processed and skip any you've already seen.

### Return a 2xx quickly

Acknowledge the delivery before doing slow work. Put the event on a queue or background job and return `2xx` straight away. A slow response can hit the 30-second limit and be retried even though you received it.

### Reconcile with the API

Webhooks tell you something changed. They don't guarantee you'll hear about every change. For anything that matters, such as marking an invoice paid, confirm the current state with `GET /v2/payment-intents/{id}`, and periodically check for anything you may have missed.

### Verify every delivery

Check the signature on every `POST` before acting on it, and keep your signing secret out of source control.

### Subscribe only to what you need

Choose only the events your integration uses. You can add another webhook later for other events.

### Use HTTPS on a public address

Destination URLs must use `https` and resolve to a public internet address. Nexpay refuses private, internal and loopback addresses, and URLs that include a username or password.
