# Webhooks

> Get a signed HTTPS callback when an order is submitted, filled, refunded or fails — event types, payload, headers, HMAC signature verification, retries, replay and testing.

Source: https://docs.layerhop.com/guides/webhooks

LayerHop webhooks are signed HTTPS `POST` requests that tell your backend when an order changes state (`order.submitted`, `order.filled`, `order.refunded`, `order.failed`, `order.dropped`), so you do not have to poll. Add an endpoint in the [dashboard](https://dashboard.layerhop.com), verify the `LayerHop-Signature` header (HMAC-SHA256) on each request, and answer with a `2xx` within 10 seconds; failed deliveries are retried for 24 hours.

## Which orders send webhooks?

Webhooks are sent for orders that belong to your account: orders quoted or built with one of your [API keys](/guides/dashboard-and-api-keys). Orders without a key have no account and send no webhooks. LayerHop's worker tracks each order after its source transaction is reported, so make sure your integration calls [`POST /v1/orders/{quoteId}/submitted`](/api-reference#report-the-broadcast-transaction) (SDK: `reportSubmitted`) after the wallet broadcasts. `POST /v1/orders/submit` reports automatically.

Endpoints belong to a mode: endpoints created with the dashboard's **Test mode** on receive only events for [test-mode](/guides/test-mode) orders, and live endpoints only live events. Every event has a `livemode` field.

## 1. Add an endpoint

1. Sign in to [dashboard.layerhop.com](https://dashboard.layerhop.com), open **Webhooks** and add an HTTPS URL (or call [`POST /v1/dashboard/webhooks`](/api-reference#create-a-webhook-endpoint)).
2. Optionally pick the events you want. An endpoint with no events selected receives **all** of them.
3. Copy the signing secret (`whsec_…`). It is shown when the endpoint is created and signs every request to that endpoint. Keep it on your server.

| URL rule | Why |
|---|---|
| Must be `https://` | Payloads travel encrypted. |
| Public host only: no `localhost`, `.local`, `.internal`, private, loopback or link-local IPs | Checked when you save the URL, and again on the resolved IP at every delivery. |
| No credentials in the URL, at most 2048 characters | |
| Redirects are not followed | A `3xx` response counts as a failed attempt. |

## Which events are there?

| Type | Sent when |
|---|---|
| `order.submitted` | LayerHop starts tracking a source transaction you reported. |
| `order.filled` | The destination side completed. For same-chain swaps, the transaction confirmed successfully. |
| `order.refunded` | The provider refunded the user on the source chain. |
| `order.failed` | The source transaction reverted, the provider reported a failure, or the order was not settled within 24 hours (`statusDetail: "timeout"`). |
| `order.dropped` | The reported source transaction never reached the network (dropped, cancelled or replaced in the wallet). No funds moved and nothing is refunded; `statusDetail` says why. Reporting the replacement hash moves the order back to `submitted`. See [dropped transactions](/concepts/order-tracking#what-happens-when-a-transaction-is-dropped). |
| `checkout.session.processing` | A payment for a [checkout session](/guides/checkout) was sent and is being tracked. `data.session`. |
| `checkout.session.completed` | The session is `paid`: delivery to your address was verified on chain. `data.session`. |
| `checkout.session.payment_failed` | The payment attempt failed or was refunded by the provider; the session is open again. `data.session`. |
| `checkout.session.expired` | The session expired unpaid. `data.session`. |
| `checkout.session.refunded` | A [refund](/guides/refunds) of a paid session completed. `data.session` (with the new `refundedAmount`) and `data.refund` (`id`, `amount`, `status`, `reason`, `txHash`, `to: { chainId, token, address }`, `createdAt`). |
| `invoice.sent` | You sent or re-sent an [invoice](/guides/invoices). `data.invoice`. |
| `invoice.paid` | The checkout session paying an invoice is `paid`. `data.invoice` (`id`, `number`, `status`, `amount`, `settlement`, `customerEmail`, `customerName`, `sessionId`, `subscriptionId`, `paidAt`) and `data.session`. |
| `subscription.created` | You created a [subscription](/guides/subscriptions). `data.subscription`. |
| `subscription.renewed` | A subscription period's invoice was issued and emailed. `data.subscription` and `data.invoice`. |
| `subscription.past_due` | A subscription invoice is unpaid past its due date; reminders are going out. `data.subscription` and `data.invoice`. |
| `subscription.canceled` | A subscription was canceled: by you, at the end of its period, or after 7 days past due (`cancellationReason: "unpaid"`). `data.subscription`. |
| `limit_order.opened` | A [limit order](/guides/limit-and-recurring-orders)'s create transaction landed; it is `open`. `data.limitOrder`. |
| `limit_order.filled` | A limit order filled, partly or fully (one event per fill). `data.limitOrder` and `data.fill` (the fill's order). |
| `limit_order.cancelled` | The wallet's cancel of a limit order landed. `data.limitOrder`. |
| `limit_order.expired` | A limit order reached its expiry. `data.limitOrder`. |
| `limit_order.failed` | A limit order's transaction never showed up on chain. `data.limitOrder`. |
| `x402.payment.settled` | An [x402](/guides/x402) payment settled on chain. `data.payment`. |
| `webhook.test` | You pressed **Send test** in the dashboard. Not subscribable; always delivered to the endpoint you test. |

Orders that are built but never reported become `expired` after one hour. No webhook is sent for that. See [Order tracking](/concepts/order-tracking) for the full lifecycle.

## What does a delivery contain?

Each delivery is a `POST` with a JSON body:

```json
{
  "id": "evt_01hx…",
  "type": "order.filled",
  "createdAt": "2026-10-17T12:00:00.000Z",
  "data": {
    "order": {
      "quoteId": "q_…",
      "status": "filled",
      "statusDetail": null,
      "provider": "relay",
      "channel": "api",
      "partnerId": null,
      "srcChainId": 8453,
      "srcToken": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "dstChainId": 7565164,
      "dstToken": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
      "sender": "0x…",
      "recipient": "9xQe…",
      "amount": "100000000",
      "dstAmount": "99650000",
      "ourFeeBps": 10,
      "partnerFeeBps": 0,
      "srcTxHash": "0x…",
      "dstTxHash": "5Kz…",
      "createdAt": "2026-10-17T11:58:10.000Z",
      "updatedAt": "2026-10-17T12:00:00.000Z"
    }
  }
}
```

Amounts are integer strings in base units. A `webhook.test` event has `data: { "test": true, "endpointId": "whe_…" }` instead of an order.

| Header | Value |
|---|---|
| `LayerHop-Event` | The event type, for example `order.filled` |
| `LayerHop-Delivery` | The delivery id (`whd_…`), the same across retries of one delivery |
| `LayerHop-Signature` | `t=<unix seconds>,v1=<hex signature>` |
| `Content-Type` | `application/json` |
| `User-Agent` | `LayerHop-Webhooks/1` |

## 2. Verify the signature

`v1` is the hex HMAC-SHA256 of `"<t>.<raw body>"`, keyed with your endpoint secret. To verify a request:

1. Read the **raw** request body. Do not parse and re-serialize the JSON first.
2. Recompute the HMAC and compare it to each `v1` in constant time. Accept the request if any matches: during a [secret rotation](#rotate-a-signing-secret) the header has two.
3. Reject requests whose `t` is more than 5 minutes from your clock, which stops replays.

### With the TypeScript SDK

`@layerhop/sdk` (0.7.0+) verifies and parses in one call. It works in Node, edge runtimes and browsers (Web Crypto):

```ts
import { constructWebhookEvent, WebhookSignatureError } from "@layerhop/sdk";

app.post("/webhooks/layerhop", async (c) => {
  const raw = await c.req.text(); // the raw body, not re-serialized JSON
  try {
    const event = await constructWebhookEvent(process.env.LAYERHOP_WEBHOOK_SECRET!, c.req.header("LayerHop-Signature"), raw);
    if (event.type === "order.filled") { /* credit the user */ }
    return c.text("ok");
  } catch (e) {
    if (e instanceof WebhookSignatureError) return c.text("bad signature", 400);
    throw e;
  }
});
```

`verifyWebhookSignature(secret, header, rawBody)` returns a boolean if you only need the check.

### Node.js / TypeScript without the SDK

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyLayerHop(secret: string, header: string | undefined, rawBody: string, toleranceSec = 300): boolean {
  const pairs = (header ?? "").split(",").map((p) => p.trim().split("=", 2) as [string, string]);
  const t = Number(pairs.find(([k]) => k === "t")?.[1]);
  const sigs = pairs.filter(([k]) => k === "v1").map(([, v]) => Buffer.from(v ?? "", "hex"));
  if (!sigs.length || !Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > toleranceSec) return false;
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
  return sigs.some((got) => got.length === expected.length && timingSafeEqual(got, expected));
}

// Hono / any framework that gives you the raw body
app.post("/layerhop/webhook", async (c) => {
  const raw = await c.req.text();
  if (!verifyLayerHop(process.env.LAYERHOP_WEBHOOK_SECRET!, c.req.header("LayerHop-Signature"), raw)) return c.text("bad signature", 400);
  const event = JSON.parse(raw);
  // handle event.type, deduplicate on event.id, then respond quickly
  return c.text("ok");
});
```

### Python

The [Python SDK](/sdks/python) ships the check:

```python
from layerhop import verify_webhook_signature, construct_webhook_event

# Flask
@app.post("/layerhop/webhook")
def hook():
    body = request.get_data()  # raw bytes
    if not verify_webhook_signature(SECRET, body, request.headers.get("LayerHop-Signature")):
        abort(400)
    event = construct_webhook_event(SECRET, body, request.headers.get("LayerHop-Signature"))
    ...
```

Without the SDK, using only the standard library:

```python
import hashlib, hmac, time

def verify(secret: str, header: str | None, raw_body: bytes, tolerance_sec: int = 300) -> bool:
    pairs = [p.strip().split("=", 1) for p in (header or "").split(",") if "=" in p]
    sigs = [v for k, v in pairs if k == "v1"]  # two during a secret rotation
    try:
        t = int(next(v for k, v in pairs if k == "t"))
    except (StopIteration, ValueError):
        return False
    if not sigs or abs(time.time() - t) > tolerance_sec:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, s) for s in sigs)
```

### Go, Rust, Swift, Kotlin and C#

| SDK | Function |
|---|---|
| [TypeScript](/sdk) | `await verifyWebhookSignature(secret, header, rawBody)` returns `true` when valid; `await constructWebhookEvent(..)` also parses the event (throws `WebhookSignatureError`) |
| [Go](/sdks/go) | `layerhop.VerifyWebhookSignature(secret, body, header, 0, time.Time{})` returns `nil` when valid (0 and a zero time mean the 5-minute default and now) |
| [Rust](/sdks/rust) | `layerhop::webhook::verify(secret, body, header)` returns `Ok(())` when valid |
| [Kotlin](/sdks/kotlin) | `Webhooks.verifySignature(secret, body, header)` returns `true` when valid; `Webhooks.constructEvent(..)` also parses the event |
| [C#](/sdks/csharp) | `Webhooks.VerifySignature(secret, body, header)` returns `true` when valid; `Webhooks.ConstructEvent(..)` also parses the event |
| [Swift](/sdks/swift) | `try Webhook.verifySignature(secret: secret, body: body, header: header)` throws `WebhookSignatureError` when invalid |

All SDK helpers accept several `v1` values in one header, so a future secret rotation does not break them.

## How do retries work?

Respond with any `2xx` status within **10 seconds** to acknowledge a delivery, and do slow work after you respond. Anything else is retried: a non-2xx status, a timeout, a connection error or a redirect.

| Attempt | When |
|---|---|
| 1 | Right away (the worker checks for due deliveries every few seconds) |
| 2 | 1 minute after attempt 1 failed |
| 3 | 5 minutes later |
| 4 | 30 minutes later |
| 5 | 2 hours later |
| 6 | 6 hours later |
| 7 | 24 hours later, then the delivery is marked `failed` |

- Deliveries can arrive more than once and out of order. Deduplicate on the event `id`, and treat `data.order.status` as the source of truth.
- Disabling an endpoint stops its pending retries.
- The dashboard keeps each delivery's status, attempt count, HTTP code, latency, next retry and the first 2 KB of your response. Filter an endpoint's deliveries by status, event type and date ([`GET …/deliveries?status=failed&eventType=order.filled&from=…`](/api-reference#list-deliveries)), and open a delivery to see the exact request (URL, headers, body) and the event.
- Events and their deliveries are kept for **30 days**, then deleted (an event with a delivery still being retried stays until that delivery is final).
- Each endpoint shows its health for the last 24 hours and 7 days: success rate, failures, average and p95 latency ([`GET …/stats`](/api-reference#endpoint-health)).
- **Replay** any delivery from the dashboard (or [`POST …/deliveries/{deliveryId}/replay`](/api-reference#replay-a-delivery)). A replay is a new delivery with a new `LayerHop-Delivery` id for the same event `id`.

## 3. Test your endpoint

- In the dashboard, open the endpoint and press **Send test event**, then pick a type ([`POST /v1/dashboard/webhooks/{id}/test`](/api-reference#send-a-test-event) with `{ "type": "order.filled" }`). You receive a signed, realistic sample of that event (`"sample": true` in the payload) or a plain `webhook.test` ping, and the result appears in the deliveries list.
- In test mode you can also run the whole flow for real: an [`lh_test_` key](/guides/test-mode) creates orders and checkout payments that send genuine test events to your test endpoints.

## Test locally with the CLI

Develop your handler on your laptop, with no tunnel and no public URL. The [CLI](/cli) streams your account's events from LayerHop and forwards each one to a local URL, signed exactly like a real delivery:

```bash
npx @layerhop/cli login                        # once: paste a test key (lh_test_…), saved with mode 600
export LAYERHOP_WEBHOOK_SECRET=whsec_dev_123   # optional: the secret your handler verifies with
npx @layerhop/cli listen --forward-to http://localhost:3000/webhooks
```

```text
Ready. Forwarding test-mode events to http://localhost:3000/webhooks
Webhook signing secret for this session: whsec_dev_123 (yours)
10:02:11  --> order.filled [evt_01m5…]  <-- 200 (14 ms)
```

In a second terminal, fire sample events (test keys only, so samples never reach live endpoints):

```bash
npx @layerhop/cli trigger order.filled
npx @layerhop/cli trigger checkout.session.completed
```

`listen` takes `--events order.filled,order.failed` to forward only some types, and `--secret` (or `LAYERHOP_WEBHOOK_SECRET`) to choose the signing secret; without one it prints a new secret per session. Triggered events also go to your registered test endpoints, and they show up in the dashboard's **Events** page.

Send any event again, with the same `id` and payload, to your subscribed endpoints and every running `listen` ([`POST /v1/webhooks/events/{id}/resend`](/api-reference#resend-an-event-with-an-api-key)):

```bash
npx @layerhop/cli events resend evt_01m5…
```

`listen` reconnects on its own. When it does, it asks for the events created while it was away (up to an hour back, [`GET /v1/webhooks/stream?since=`](/api-reference#stream-your-webhook-events)), so a dropped connection loses nothing. Instead of `login` you can pass `--api-key` or set `LAYERHOP_API_KEY`. `listen`, `trigger` and `events resend` also work against the offline mock API (`layerhop dev`, see [Local development](/guides/local-development)).

## Rotate a signing secret

Rotate an endpoint's secret without downtime: **Rotate secret** in the dashboard ([`POST /v1/dashboard/webhooks/{id}/rotate-secret`](/api-reference#rotate-the-signing-secret)) shows the new `whsec_…` once, and for a grace period (24 hours by default, up to 7 days, or none) every delivery is signed with **both** secrets:

```text
LayerHop-Signature: t=1760781731,v1=<signature with the new secret>,v1=<signature with the old secret>
```

`verifyWebhookSignature` in every SDK accepts the header if any `v1` matches, so deploy the new secret whenever you like during the grace period. After it ends only the new secret signs.

## Event log and resending

The dashboard's **Events** page lists every event of your account (live or test), with a delivery summary per event ([`GET /v1/dashboard/events`](/api-reference#list-events)). Open one to see its payload and every delivery, and **Resend** it to all subscribed endpoints or to one ([`POST /v1/dashboard/events/{id}/resend`](/api-reference#resend-an-event)). A resend is a new delivery of the same event `id`, so idempotent handlers process it once. Running `layerhop listen` sessions get resent events too.
