---
title: Process webhooks reliably
description: Receive a payment provider's webhooks on a route, check their signature, ignore repeated deliveries, answer at once and do the work in a durable handler.
related:
  - /http/receive-webhooks
  - /background/run-durable-work
  - /develop/store-secrets
---

At the end of this page you have an endpoint that takes a payment provider's webhooks and credits a wallet once for each payment. It uses an HTTP route, `verifyWebhook`, a secret, a message and a durable handler with steps.

A webhook sender retries a delivery that failed or took too long, so the same delivery can arrive twice. The endpoint here records each delivery's id to ignore repeats, answers at once, and leaves the work to a durable run that survives a crash halfway.

Start from a project set up as in the [Quickstart](/quickstart), with the TypeScript SDK installed.

## The files

- luna/
  - luna.config.ts
  - lunas/
    - index.ts
    - inbox.ts
    - wallet.ts

```ts luna/luna.config.ts
import { defineConfig } from "luna";

export default defineConfig({ lunas: "./lunas/index.ts" });
```

```ts luna/lunas/index.ts
export { Inbox } from "./inbox.ts";
export { Wallet } from "./wallet.ts";
```

## The wallet

```ts luna/lunas/wallet.ts
import { defineLuna, t, table } from "luna";

export const Wallet = defineLuna({
  name: "Wallet",
  key: { id: t.string() },
  schema: {
    balance: table({ cents: t.int() }, { singleRow: true }),
  },
  handlers: (h) => ({
    credit: h({ args: { cents: t.int() } }, (ctx, { cents }) => {
      const total = (ctx.db.balance.get()?.cents ?? 0) + cents;
      ctx.db.balance.set({ cents: total });
      return total;
    }),
    balance: h({ query: true }, (ctx) => ctx.db.balance.get()?.cents ?? 0),
  }),
});
```

- **`balance`** is a single-row table holding the wallet's balance in cents.
- **`credit`** adds to it and returns the new total. On its own it would add twice for a call made twice, which the inbox below prevents.

## The inbox

```ts luna/lunas/inbox.ts
import { defineLuna, t, table } from "luna";
import { verifyWebhook } from "luna/auth";
import { Wallet } from "./wallet.ts";

/** What the payment provider sends. */
type Delivery = { id: string; type: string; data: { wallet: string; cents: number } };

export const Inbox = defineLuna({
  name: "Inbox",
  key: { source: t.string() },
  schema: {
    deliveries: table(
      {
        id: t.string(),
        body: t.json<Delivery>(),
        run: t.string(),
        received: t.timestamp(),
        done: t.timestamp().optional(),
      },
      { primaryKey: ["id"] },
    ),
  },
  handlers: (h) => ({
    receive: h(
      { args: t.request(), route: { path: "POST /webhooks/:source", auth: "none" } },
      async (ctx, req) => {
        const body = await req.text();
        const signature = req.headers.get("x-signature") ?? "";
        if (!verifyWebhook(body, signature, ctx.env.WEBHOOK_SECRET)) {
          return new Response("bad signature", { status: 401 });
        }
        const delivery = JSON.parse(body) as Delivery;
        if (!ctx.db.deliveries.get(delivery.id)) {
          const run = ctx.send(Inbox, ctx.key).process({ id: delivery.id });
          ctx.db.deliveries.insert({ id: delivery.id, body: delivery, run, received: Date.now() });
        }
        return new Response(null, { status: 204 });
      },
    ),
    process: h({ args: { id: t.string() }, durable: true }, async (ctx, { id }) => {
      const delivery = ctx.db.deliveries.get(id);
      if (!delivery) return;
      const { type, data } = delivery.body;
      if (type === "payment.succeeded") {
        await ctx.step("credit", () =>
          ctx.call(Wallet, { id: data.wallet }).credit({ cents: data.cents }, { idempotencyKey: `delivery-${id}` }),
        );
      }
      await ctx.step("done", () => {
        ctx.db.deliveries.update({ where: { id }, set: { done: Date.now() } });
      });
    }),
  }),
});
```

- **`route`** serves `receive` at `POST /webhooks/:source`, and the `:source` part of the path picks the `Inbox` luna. `auth: "none"` lets the provider call it without a Luna key, because the signature proves who sent it.
- **`t.request()`** gives the handler the raw request. The body is read as text first, so the signature is checked against the exact bytes that were signed.
- **`verifyWebhook`** checks that `x-signature` is the HMAC-SHA256 of the body, in hex, under the secret `WEBHOOK_SECRET`. A wrong signature gets a 401 and changes nothing. Until the secret is set, every delivery fails and nothing is stored.
- **The repeat check** looks up the delivery's id. It runs after the handler's last `await`, so two copies of one delivery arriving together cannot both pass it.
- **`ctx.send`** starts the `process` run as a message, which is stored with the delivery's row. Both are kept or neither is, so a failed handler never leaves a delivery without its run. The route answers 204 at once.
- **`run`** keeps the message's id, which is also the id of its durable run.
- **`process`** is durable. Each step's result is recorded. A run that stops halfway replays the finished steps from that record and runs only the rest. A step that fails by chance is tried again, 3 times in all by default.
- **`idempotencyKey`** covers a crash inside the `credit` step after the wallet answered. The step runs again, and the wallet returns the first call's result without adding twice.

A delivery whose run failed keeps `done` empty. `ctx.runs(Inbox, { source }).get(run)` tells you why.

:::note
Code outside steps runs again each time the run goes on after a wait or a crash. Keep writes and calls inside steps, as `process` does.
:::

## Set the secret

Set the secret your provider signs with. The command asks for the value.

```bash
luna secrets set WEBHOOK_SECRET
```

## Point the provider at it

Run `luna dev`. Routes are served at an address of their own, which `luna status` prints after `Routes at`.

```bash
luna status
```

Give the provider `<ROUTES_URL>/webhooks/payments`, where `payments` names the sender. To send a signed delivery yourself, sign the body with the same secret.

```bash
BODY='{"id":"evt_1","type":"payment.succeeded","data":{"wallet":"ann","cents":500}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "<WEBHOOK_SECRET>" | awk '{print $NF}')
curl -X POST "<ROUTES_URL>/webhooks/payments" \
  -H "x-signature: $SIG" \
  -H "Content-Type: application/json" \
  -d "$BODY"
```

Send it twice. Both answer 204, and the wallet `ann` is credited once.

## Next steps

- [Receive webhooks](/http/receive-webhooks) covers signatures with a prefix or a timestamp.
- [Run durable work](/background/run-durable-work) explains steps, retries and replays.
- [Serve HTTP routes](/http/serve-http-routes) covers paths, methods and who may call a route.
