# Webhooks

> Receive signed NorthechPay events, verify the HMAC-SHA256 signature, deduplicate by event ID, and handle retries and ordering safely.

NorthechPay sends signed HTTP `POST` requests to your server when a checkout, payout or dispute changes. These are NorthechPay events, not Moov's. Moov's own events go to NorthechPay, which turns them into the events below.

## Add an endpoint

In the dashboard, open **Developers → Webhooks** and add an endpoint:

| Setting     | Rules                                                                                                                                                                                                              |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| URL         | Required, up to 255 characters. Must be `https://` and resolve to a public IP address. Plain `http://` and private addresses work only when the platform itself runs locally. No user name or password in the URL. |
| Description | Optional, up to 255 characters.                                                                                                                                                                                    |
| Events      | One or more event types from the table below, or `*` for all.                                                                                                                                                      |

The signing secret (`whsec_` followed by 40 characters) is shown once. Store it in your server's environment, for example `NORTHECHPAY_WEBHOOK_SECRET`.

From the same page you can:

- **Send a test event.** It sends `webhook.test` to that endpoint only, whatever events it subscribes to.
- **Rotate the secret.** The old secret stops working at once. Deliveries that fail in between are retried with the new secret, so deploy it quickly.
- **Delete the endpoint.** Deliveries still waiting for it are abandoned.

Endpoints are managed in the dashboard only. There is no API for them.

## Event types

Each event is one business fact. Payment, refund and dispute events are sent once per Moov payment, refund or dispute, so a reusable payment link sends one `checkout.paid` per payment and every partial refund sends its own `checkout.refunded`.

| Event                    | Sent when                                                                                     | Once per |
| ------------------------ | --------------------------------------------------------------------------------------------- | -------- |
| `checkout.created`       | A checkout or payment link was created at Moov.                                               | checkout |
| `checkout.processing`    | A payment was submitted. Moov is processing it.                                               | payment  |
| `checkout.authorized`    | A card payment was approved. Funds are settling to the merchant wallet. Not paid yet.         | payment  |
| `checkout.paid`          | Moov reports the payment completed into the merchant wallet.                                  | payment  |
| `checkout.failed`        | A payment attempt failed or was declined. Earlier payments on the same link are not affected. | payment  |
| `checkout.expired`       | The checkout expired.                                                                         | checkout |
| `checkout.disabled`      | The checkout was disabled.                                                                    | checkout |
| `checkout.refunded`      | Moov completed a refund of a payment.                                                         | refund   |
| `checkout.refund_failed` | A refund Moov had accepted failed. Its amount is refundable again.                            | refund   |
| `checkout.reversed`      | A completed payment was reversed.                                                             | payment  |
| `checkout.disputed`      | The cardholder disputed a payment. Follow the dispute with `dispute.updated`.                 | dispute  |
| `dispute.updated`        | A dispute was opened, or Moov changed its status or phase.                                    | change   |
| `payout.pending`         | A payout to the merchant bank account is in progress.                                         | payout   |
| `payout.completed`       | Moov reports the payout completed.                                                            | payout   |
| `payout.failed`          | The payout failed, was canceled, or was returned.                                             | payout   |
| `webhook.test`           | You clicked "send test" in the dashboard. No payment exists for it.                           | click    |

## The request

```http
POST /webhooks/northechpay HTTP/1.1
Host: shop.example.com
Content-Type: application/json
User-Agent: NorthechPay-Webhooks/1.0
NorthechPay-Event-Id: 01a20951-0a1b-7c2d-9e3f-4a5b6c7d8e9f
NorthechPay-Event-Type: checkout.paid
NorthechPay-Event-Schema: 2
NorthechPay-Delivery-Id: 01a20951-2c3d-7e4f-8a5b-6c7d8e9f0a1b
NorthechPay-Signature: t=1795538071,v1=5f2c0b1e…

{"id":"01a20951-0a1b-7c2d-9e3f-4a5b6c7d8e9f","type":"checkout.paid","schema_version":2,"created_at":"2026-11-24T16:34:31+00:00","occurred_at":"2026-11-24T16:34:29+00:00","livemode":false,"resource":{"type":"payment","id":"01a20950-…"},"data":{…}}
```

| Header                     | Meaning                                                                              |
| -------------------------- | ------------------------------------------------------------------------------------ |
| `NorthechPay-Event-Id`     | The event `id`. The same on every retry. Use it to deduplicate.                      |
| `NorthechPay-Event-Type`   | The event `type`.                                                                    |
| `NorthechPay-Event-Schema` | The envelope version, `2`. Events recorded before schema 2 send `1`.                 |
| `NorthechPay-Delivery-Id`  | One delivery of one event to one endpoint. The same on every retry of that delivery. |
| `NorthechPay-Signature`    | `t={unix seconds},v1={hex signature}`. See below.                                    |

### Envelope

```json
{
    "id": "01a20951-0a1b-7c2d-9e3f-4a5b6c7d8e9f",
    "type": "checkout.paid",
    "schema_version": 2,
    "created_at": "2026-11-24T16:34:31+00:00",
    "occurred_at": "2026-11-24T16:34:29+00:00",
    "livemode": false,
    "resource": {
        "type": "payment",
        "id": "01a20950-7d1e-7a2b-8c3d-4e5f6a7b8c9d"
    },
    "data": {
        "id": "01a20926-5b7e-7c2d-9f41-6e8d2c3b1421",
        "object": "checkout",
        "status": "paid",
        "paid": true,
        "amount": {
            "amount": 2450,
            "currency": "USD",
            "decimal": "24.50",
            "formatted": "$24.50"
        },
        "merchant_reference": "ORDER-1001",
        "paid_at": "2026-11-24T16:34:31+00:00",
        "payment": {
            "id": "01a20950-7d1e-7a2b-8c3d-4e5f6a7b8c9d",
            "object": "transaction",
            "status": "completed",
            "amount": {
                "amount": 2450,
                "currency": "USD",
                "decimal": "24.50",
                "formatted": "$24.50"
            },
            "refunded_amount": {
                "amount": 0,
                "currency": "USD",
                "decimal": "0.00",
                "formatted": "$0.00"
            },
            "checkout_id": "01a20926-5b7e-7c2d-9f41-6e8d2c3b1421"
        }
    }
}
```

- `id` is stable: every retry of this event sends the same `id` and the same body.
- `resource` says what the event is about: a `payment`, `refund`, `dispute`, `checkout` or `payout`, with its NorthechPay ID.
- `created_at` is when NorthechPay recorded the event, `occurred_at` when the fact happened (from Moov where known).

`livemode` is always `false` in this build. `data` is the resource at the moment of the event:

| Events            | `data`                                                                                                                                                                                                         |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `checkout.*`      | The [checkout](/docs/checkouts) object, without the `transactions` array, plus `payment` (the [transaction](/docs/transactions) the event is about) and, for refund and dispute events, `refund` or `dispute`. |
| `dispute.updated` | The [dispute](/docs/disputes) object, without `transaction_id` and `checkout`.                                                                                                                                 |
| `payout.*`        | The [payout](/docs/payouts-and-balances) object.                                                                                                                                                               |
| `webhook.test`    | `{ "test": true, "message": "Test event from the developer portal. No payment exists for it." }`                                                                                                               |

## Verify the signature

The signature header has a timestamp and a signature:

```text
NorthechPay-Signature: t=1795538071,v1=<64 hex characters>

v1 = hex( HMAC-SHA256( key = your signing secret, message = t + "." + raw request body ) )
```

To verify:

1. Read the **raw** request body as bytes. Do not parse and re-encode the JSON first.
2. Split the header on `,` and each part on the first `=`. Take `t` and `v1`.
3. Reject the request if `t` is missing or more than 300 seconds from your clock, in either direction.
4. Compute the HMAC-SHA256 of `{t}.{raw body}` with your secret, as lowercase hex.
5. Compare it with `v1` in constant time. Reject if they differ.

Each delivery attempt is signed at send time with a fresh `t`, so retries pass the 300-second check.

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

const TOLERANCE_SECONDS = 300;

/**
 * @param {Buffer|string} rawBody  The exact bytes NorthechPay sent.
 * @param {string|undefined} header The NorthechPay-Signature header.
 * @param {string} secret           Your endpoint's signing secret (whsec_…).
 */
export function verifyNorthechPaySignature(
    rawBody,
    header,
    secret,
    now = Math.floor(Date.now() / 1000),
) {
    const parts = {};
    for (const part of String(header ?? '').split(',')) {
        const index = part.indexOf('=');
        if (index > 0)
            parts[part.slice(0, index).trim()] = part.slice(index + 1).trim();
    }

    const timestamp = Number.parseInt(parts.t ?? '', 10);
    if (
        !Number.isSafeInteger(timestamp) ||
        timestamp <= 0 ||
        Math.abs(now - timestamp) > TOLERANCE_SECONDS
    ) {
        return false;
    }

    const expected = Buffer.from(
        crypto
            .createHmac('sha256', secret)
            .update(`${timestamp}.`)
            .update(rawBody)
            .digest('hex'),
        'utf8',
    );
    const received = Buffer.from(parts.v1 ?? '', 'utf8');

    // timingSafeEqual throws on different lengths, so check the length first.
    return (
        received.length === expected.length &&
        crypto.timingSafeEqual(received, expected)
    );
}
```

```php
/**
 * @param  string  $rawBody  The exact bytes NorthechPay sent (php://input).
 * @param  string  $header   The NorthechPay-Signature header.
 * @param  string  $secret   Your endpoint's signing secret (whsec_…).
 */
function verify_northechpay_signature(string $rawBody, string $header, string $secret, ?int $now = null): bool
{
    $parts = [];

    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        $parts[$key] = $value;
    }

    $timestamp = (int) ($parts['t'] ?? 0);

    if ($timestamp <= 0 || abs(($now ?? time()) - $timestamp) > 300) {
        return false;
    }

    $expected = hash_hmac('sha256', $timestamp.'.'.$rawBody, $secret);

    return hash_equals($expected, (string) ($parts['v1'] ?? ''));
}
```

## Handle the request

Your endpoint should do four things, in this order:

1. Verify the signature. If it fails, respond `400` and stop.
2. Record the event `id` with a unique constraint. If it is already there, respond `200` and stop.
3. Respond `2xx` quickly, within 10 seconds.
4. Process the event in the background.

```js
import express from 'express';
import { verifyNorthechPaySignature } from './northechpay-signature.js';

const app = express();

// express.raw keeps the exact bytes, which the signature needs.
app.post(
    '/webhooks/northechpay',
    express.raw({ type: 'application/json' }),
    async (req, res) => {
        const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);

        if (
            !verifyNorthechPaySignature(
                rawBody,
                req.get('NorthechPay-Signature'),
                process.env.NORTHECHPAY_WEBHOOK_SECRET,
            )
        ) {
            return res.status(400).send('invalid signature');
        }

        const event = JSON.parse(rawBody.toString('utf8'));

        // Your code: INSERT the event id into a table with a UNIQUE index; returns false if it already existed.
        const isNew = await events.recordOnce(event.id, event.type);

        res.status(200).send('ok');

        if (isNew) {
            await jobs.enqueue('northechpay-event', event); // Your queue. Process outside the request.
        }
    },
);
```

```php
// routes/api.php (no CSRF middleware on API routes)
use App\Jobs\HandleNorthechPayEvent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;

Route::post('webhooks/northechpay', function (Request $request) {
    $rawBody = $request->getContent();
    $valid = verify_northechpay_signature(
        $rawBody,
        (string) $request->header('NorthechPay-Signature', ''),
        (string) config('services.northechpay.webhook_secret'),
    );

    if (! $valid) {
        return response('invalid signature', 400);
    }

    $event = json_decode($rawBody, true, flags: JSON_THROW_ON_ERROR);

    // Unique index on event_id: insertOrIgnore returns 0 for a duplicate.
    $isNew = DB::table('northechpay_events')->insertOrIgnore([
        'event_id' => $event['id'],
        'type' => $event['type'],
        'received_at' => now(),
    ]) === 1;

    if ($isNew) {
        HandleNorthechPayEvent::dispatch($event);
    }

    return response('ok', 200);
});
```

Then, in the background job, act on the event. Act on the **payment** the event names (`data.payment.id`), not on the checkout's overall `status`: on a reusable payment link that status describes the whole link. Re-read the payment from the API so you always act on the current state:

```js
async function handleNorthechPayEvent(event) {
    if (!event.type.startsWith('checkout.') || !event.data.payment) return;

    const order = await orders.findByCheckoutId(event.data.id);
    if (!order) return;

    const response = await fetch(
        `${process.env.NORTHECHPAY_API_BASE}/merchant/transactions/${event.data.payment.id}`,
        {
            headers: {
                Authorization: `Bearer ${process.env.NORTHECHPAY_API_KEY}`,
                Accept: 'application/json',
            },
        },
    );
    const { data: payment } = await response.json();

    const amountMatches =
        payment.amount.amount === order.amountCents &&
        payment.amount.currency === 'USD';

    if (payment.status === 'completed' && amountMatches) {
        // Keyed by payment ID: a second payment never marks the same order twice.
        await orders.markPaidOnce(order.id, payment.id, payment.completed_at);
    }

    // Moov's cumulative refunded total. Store it, never add event amounts to it.
    await orders.setRefundedCents(order.id, payment.refunded_amount.amount);
}
```

```php
// app/Jobs/HandleNorthechPayEvent.php: the constructor stores the event array as $this->event.
public function handle(): void
{
    $paymentId = $this->event['data']['payment']['id'] ?? null;

    if (! str_starts_with($this->event['type'], 'checkout.') || $paymentId === null) {
        return;
    }

    $order = Order::where('checkout_id', $this->event['data']['id'])->first();

    if ($order === null) {
        return;
    }

    $payment = Http::baseUrl(config('services.northechpay.api_base'))
        ->withToken(config('services.northechpay.api_key'))
        ->acceptJson()
        ->get("/merchant/transactions/{$paymentId}")
        ->throw()
        ->json('data');

    $amountMatches = $payment['amount']['amount'] === $order->amount_cents && $payment['amount']['currency'] === 'USD';

    if ($payment['status'] === 'completed' && $amountMatches) {
        $order->markPaidOnce($payment['id'], $payment['completed_at']); // no-op if this payment was already recorded
    }

    // Moov's cumulative refunded total. Store it, never add event amounts to it.
    $order->update(['refunded_cents' => $payment['refunded_amount']['amount']]);
}
```

For `checkout.expired` and `checkout.disabled` (no `payment`), re-read the checkout and close it.

> **Note:** A verified `checkout.paid` event is trustworthy proof of payment. Re-reading the payment is still the safest choice: it protects you from acting on an older event that arrives late, and it confirms the amount.

## Delivery and retries

- Any `2xx` response counts as delivered. Anything else, a timeout or a connection error is a failure.
- NorthechPay waits up to 5 seconds to connect and 10 seconds for the response.
- Redirects are not followed. A `301` or `302` counts as a failure. Use your final URL.
- Each delivery is tried up to **8 times**. The waits after each failed attempt are:

| After attempt | Wait before the next attempt                 |
| ------------- | -------------------------------------------- |
| 1             | 30 seconds                                   |
| 2             | 2 minutes                                    |
| 3             | 10 minutes                                   |
| 4             | 30 minutes                                   |
| 5             | 1 hour                                       |
| 6             | 2 hours                                      |
| 7             | 4 hours                                      |
| 8             | No more attempts. The delivery is abandoned. |

The last attempt is about 7 hours and 42 minutes after the first, plus queue time. There is no manual redelivery. If you miss events, [reconcile](/docs/reconciliation) by reading the API.

## Ordering and duplicates

- Deliveries can arrive more than once. Deduplicate by event `id`.
- Deliveries can arrive out of order, for example `checkout.authorized` after `checkout.paid` when the first one was retried. Never move an order backwards because of an older event.
- Each fact is sent once: one `checkout.paid` per payment, one `checkout.refunded` per refund, one `checkout.disputed` per dispute, one `dispute.updated` per dispute change, one `payout.*` per payout status. The same fact seen through several Moov notifications, a refresh or reconciliation is still one event with one `id`.
- A failed attempt after a successful payment on a reusable link sends `checkout.failed` for that attempt only. The earlier payment stays paid.
- Refund amounts: `data.refund.amount` is that refund only. `data.payment.refunded_amount` is Moov's running total for the payment. Store the total; do not add refund events together, or a redelivered event would be counted twice.

Treat events as a signal to look, and the API as the answer.

## What to do with each event

| Event                                    | Typical action                                                                          |
| ---------------------------------------- | --------------------------------------------------------------------------------------- |
| `checkout.authorized`                    | Show "Card approved, confirming payment". Do not ship.                                  |
| `checkout.paid`                          | Check the payment amount, record that payment once (by `data.payment.id`), then fulfil. |
| `checkout.failed`                        | Keep the order unpaid. The buyer can try again while the checkout is open.              |
| `checkout.expired`, `checkout.disabled`  | Close the checkout. Create a new one, with a new key, if the buyer still wants to pay.  |
| `checkout.refunded`                      | Re-read the payment. Store its `refunded_amount` (Moov's total).                        |
| `checkout.refund_failed`                 | Re-read the payment. The refund did not happen; its amount is refundable again.         |
| `checkout.reversed`, `checkout.disputed` | Re-read. Flag the order for review. For disputes, see [Disputes](/docs/disputes).       |
| `dispute.updated`                        | Re-read the dispute. Respond before `respond_by` if it needs a response.                |
| `payout.*`                               | Update your accounting. Re-read the payout for details.                                 |

## Schema 2 (what changed)

Events recorded since the per-fact change carry `schema_version: 2`. Compared with earlier events:

- **More events, never fewer.** A reusable link's later payments, every partial refund, the final refund after partial ones and every failed attempt now send an event. Before, each `checkout.*` type was sent at most once per checkout.
- **`checkout.refunded` is sent when Moov completes the refund**, once per refund. Before, it was sent once per checkout when the checkout's status first became `partially_refunded` or `refunded`. A failed refund sends the new `checkout.refund_failed`.
- **New fields**: `schema_version`, `occurred_at`, `resource`, and `data.payment`, `data.refund` and `data.dispute`. Existing fields are unchanged. Events recorded before the change are redelivered in their original form.
- **Nothing was re-sent.** Payments and refunds that existed before the change were marked as already announced, so no old event was sent again. A reusable link's earlier second payment that was never announced stays unannounced; read [transactions](/docs/transactions) to reconcile it.
