# Webhooks

Webhooks tell your server when an order changes, so your records stay right when no user is watching. Maxy sends one signed `order.updated` event for each change of `state` or `btcTxId`, within about 15 seconds.

## Register an endpoint

Register your HTTPS endpoint once. The answer carries the signing secret, once: store it. `BASE` and `KEY` are as on [Get a quote](https://maxy.co/docs/buy-btc#get-a-quote). A URL that is not HTTPS on a public host answers `invalid_input`, and a sixth endpoint answers `conflict`: delete one first with `DELETE /webhooks/{id}`.

```sh
curl -s -X POST "$BASE/webhooks" \
  -H "x-maxy-key: $MAXY_API_KEY" -H "content-type: application/json" \
  -d '{ "url": "https://your.app/maxy/webhooks" }'
```

```ts
const res = await fetch(`${BASE}/webhooks`, {
  method: 'POST',
  headers: { 'x-maxy-key': KEY, 'content-type': 'application/json' },
  body: JSON.stringify({ url: 'https://your.app/maxy/webhooks' }),
});
const { id, secret } = await res.json(); // store secret: it is shown once
```

```python
r = requests.post(f"{BASE}/webhooks", json={"url": "https://your.app/maxy/webhooks"}, headers={"x-maxy-key": KEY})
hook = r.json()  # hook["secret"] is shown once: store it
```

- Answer `2xx` within 10 seconds. Otherwise Maxy retries 8 times over about 23 hours.
- Delivery is at least once: process each event `id` once.
- Two events can arrive out of order: order them by `createdAt`.
- Maxy sends events for orders placed with your key, until the order ends, or for 3 days. `POST /orders/watch` adds any other order.
- `POST /webhooks/{id}/test` sends a signed test event. `POST /webhooks/{id}/events/{eventId}/replay` resends one. `GET /webhooks/{id}/events` lists the last 25.

On a laptop, with no tunnel: `npx maxy webhooks listen --forward-to http://localhost:3000/maxy/webhooks`.

## Verify a webhook

Check every event's signature before you trust it, so nobody else can fake one. `Maxy-Signature` is `t=<unix seconds>,v1=<hex>`, where `v1` is HMAC-SHA256 of `<t>.<raw body>`, keyed with the endpoint secret. `alreadyProcessed` and `recordOrderState` are yours.

```ts
import express from 'express';
import { verifyWebhook, type MaxyWebhookEvent } from '@maxy-labs/sdk';

const app = express();
app.post('/maxy/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
  let event: MaxyWebhookEvent;
  try {
    event = await verifyWebhook(req.body.toString(), req.header('maxy-signature'), process.env.MAXY_WEBHOOK_SECRET!);
  } catch {
    return res.sendStatus(400); // a bad or stale signature: not from Maxy, or a replay
  }
  // Your own store: deliveries repeat, so dedupe on the event id.
  if (await alreadyProcessed(event.id)) return res.sendStatus(200);
  if (event.type === 'order.updated') await recordOrderState(event.data.orderId, event.data.state, event.data.btcTxId);
  res.sendStatus(200);
});
```

```python
import hmac, hashlib, time

def verify(raw_body: bytes, header: str, secret: str, tolerance=300, now=None) -> bool:
    parts = dict(p.strip().split("=", 1) for p in header.split(","))
    t, sig = int(parts["t"]), parts["v1"]
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    now = time.time() if now is None else now
    return hmac.compare_digest(expected, sig) and abs(now - t) <= tolerance
```

Verify the raw body before you parse it, compare in constant time, and reject a `t` more than 5 minutes from now.

Test your verifier against the published vector, `webhook-test-vector.json` in your kit's `examples` folder, at the vector's own time: it must accept the vector, refuse it with one byte changed, and refuse it at `t + 301`. `verify-webhook.mjs` and `verify_webhook.py` in the same folder check all three. If a secret leaks, delete the endpoint and create a new one.

## Event fields

| Field | Type | Meaning |
| --- | --- | --- |
| `id` | string | The event id, `evt_` and 24 hex digits. Dedupe on it |
| `type` | string | `order.updated` or `webhook.test` |
| `createdAt` | string | When the event was made, RFC 3339 in UTC |
| `data` | object | Below |
| `sandbox` | boolean | `true` on a sandbox event; absent on a live one |

`data` carries the order, as `GET /status` returns it, plus `previousState`:

| Field | Type | Meaning |
| --- | --- | --- |
| `orderId` | string | The order id |
| `route` | string | `evm-btc-escrow`, `evm-btc-gasless`, `btc-evm`, `sol-btc`, `btc-sol` or `cross-evm` |
| `chainId` | number or null | The EVM chain the order was paid on |
| `state` | string | One of the nine states |
| `previousState` | string or null | The state Maxy reported before this one |
| `rawStatus` | string | The solver's own status, for support |
| `isComplete` | boolean | `true` in a final state |
| `btcTxId` | string or null | The Bitcoin payment, once sent |
| `txs` | array | `{ label, hash }` for each transaction of the order |
| `sandbox`, `scenario` | | On sandbox events only |

`POST /webhooks/{id}/test` sends a `webhook.test` event instead, with `webhookId` and `message`.

---
Source: https://maxy.co/docs/webhooks (Maxy Docs › Orders › Follow an order)
