Webhook receiver with signature verification (Hono and Express)
Receive LayerHop order webhooks in Hono or Express, verify the LayerHop-Signature HMAC on the raw body, reject replays, deduplicate events and respond within 10 seconds.
This recipe is a small webhook server that receives LayerHop order events (order.submitted, order.filled, order.refunded, order.failed, order.dropped), verifies the LayerHop-Signature header (HMAC-SHA256 over "<t>.<raw body>"), ignores duplicates and answers 200 quickly. It is shown in Hono and Express, with the SDK helper and with plain node:crypto, and in Python.
What do I need first?#
- A public HTTPS endpoint URL (use a tunnel such as
cloudflaredwhile developing: localhost URLs are rejected). - An endpoint added in the dashboard under Webhooks. Copy its signing secret (
whsec_...) intoLAYERHOP_WEBHOOK_SECRET. - Orders built with one of your API keys and reported with
POST /v1/orders/{quoteId}/submitted, otherwise no webhook is sent.
1. Receive and verify with Hono#
// server.ts (npm i hono @hono/node-server @layerhop/sdk)
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { constructWebhookEvent, WebhookSignatureError } from "@layerhop/sdk"; // SDK 0.7.0+
const app = new Hono();
const seen = new Set<string>(); // use a database or Redis in production
app.post("/layerhop/webhook", async (c) => {
const raw = await c.req.text(); // the raw body, never re-serialized JSON
let event;
try {
event = await constructWebhookEvent(process.env.LAYERHOP_WEBHOOK_SECRET!, c.req.header("LayerHop-Signature"), raw);
} catch (e) {
if (e instanceof WebhookSignatureError) return c.text("bad signature", 400);
throw e;
}
if (seen.has(event.id)) return c.text("duplicate"); // deliveries can repeat
seen.add(event.id);
queueMicrotask(() => handle(event)); // answer first, do slow work after
return c.text("ok");
});
async function handle(event: { type: string; data: any }) {
if (event.type === "order.filled") console.log("credit", event.data.order.recipient, event.data.order.dstAmount);
if (event.type === "order.refunded" || event.type === "order.failed") console.log("alert", event.data.order.quoteId, event.data.order.statusDetail);
}
serve({ fetch: app.fetch, port: 3000 });2. Receive and verify with Express and no SDK#
Express must give you the raw bytes: mount express.raw on this route, not express.json.
// npm i express
import express from "express";
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")); // two during a secret rotation
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));
}
const app = express();
const seen = new Set<string>();
app.post("/layerhop/webhook", express.raw({ type: "application/json" }), (req, res) => {
const raw = (req.body as Buffer).toString("utf8");
if (!verifyLayerHop(process.env.LAYERHOP_WEBHOOK_SECRET!, req.header("LayerHop-Signature"), raw)) return res.status(400).send("bad signature");
const event = JSON.parse(raw);
if (seen.has(event.id)) return res.send("duplicate");
seen.add(event.id);
res.send("ok"); // acknowledge within 10 seconds
if (event.type === "order.filled") console.log("filled", event.data.order.quoteId, event.data.order.dstTxHash);
});
app.listen(3000);3. Or verify in Python#
# pip install flask layerhop
from flask import Flask, request, abort
from layerhop import construct_webhook_event
app = Flask(__name__)
SECRET = "whsec_..." # from the dashboard
@app.post("/layerhop/webhook")
def hook():
try:
event = construct_webhook_event(SECRET, request.get_data(), request.headers.get("LayerHop-Signature"))
except Exception:
abort(400)
# deduplicate on event["id"], then handle event["type"]
return "ok"How does it work?#
LayerHop sends a POST with a JSON body { id, type, createdAt, data } and the headers LayerHop-Event, LayerHop-Delivery and LayerHop-Signature: t=<unix seconds>,v1=<hex>. The receiver recomputes HMAC-SHA256(secret, "<t>.<raw body>"), compares it with every v1 in constant time and rejects timestamps more than 5 minutes off. Anything but a 2xx within 10 seconds is retried for 24 hours. Full details, event types and payload fields are in Webhooks.
How do I test it?#
In the dashboard press Send test event (POST /v1/dashboard/webhooks/{id}/test), or use an lh_test_ key and run a whole test-mode order: events arrive at your test endpoints, signed like live ones. You can also run the local mock API, which sends signed webhooks without an account (Local development).
Why does my signature check fail?#
The usual cause is a parsed-and-re-serialized body: verify the exact bytes that arrived. Also check you use the endpoint's own secret (each endpoint has one, and rotating gives two v1 values for a while), and that your server clock is correct.
Why do I get the same event twice?#
Delivery is at least once, and deliveries can be out of order. Deduplicate on event.id and treat data.order.status as the source of truth. See Order tracking.
Next: Webhooks, Next.js + wagmi recipe, API reference.
Last updated