---
title: "Receive webhooks"
description: "Create an endpoint, verify each delivery, and keep the orders it names copied from the API."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.sherpo.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Receive webhooks

This guide receives `order.created` and `order.refunded` in a Cloudflare Worker and keeps an `orders` table in D1, with a schedule that reads the orders back for what no event brings. The same steps work on any server: verify the signature, read the order from the API and write it, one refresh of an order at a time, then answer `2xx`. [Keep orders in sync](/merchant-api/guides/sync-orders) explains why; [webhooks](/merchant-api/webhooks) covers every event and rule.

1. **Create the endpoint** with a token holding `organization:write` and the order events' read scopes (`customer:read`, `transaction:read`, `product:read` and `revenue:read`), plus `organization:read` to list its deliveries, and keep the `secret` it answers:

   ```bash
   curl -X POST 'https://api.sherpo.io/merchant/v1/stores/STORE_ID/webhooks' \
     -H "Authorization: Bearer $SHERPO_TOKEN" \
     -H 'Content-Type: application/json' \
     -d '{
     "url": "https://example.com/sherpo/webhooks",
     "events": [
       "order.created",
       "order.refunded"
     ],
     "description": "Order sync"
   }'
   ```

   ```js
   const answer = await sherpo('POST', '/v1/stores/STORE_ID/webhooks', {
     body: {
       "url": "https://example.com/sherpo/webhooks",
       "events": [
         "order.created",
         "order.refunded"
       ],
       "description": "Order sync"
     },
   });
   ```

   Answers `201`, abridged:

   ```json
   {
     "webhook": {
       "id": "c4b3a291-8f7e-4d6c-8b5a-49382716a5b4",
       "url": "https://example.com/sherpo/webhooks",
       "description": "Order sync",
       "events": [
         "order.created",
         "order.refunded"
       ],
       "enabled": true,
       "connection_ended_at": null,
       "created_at": "2026-11-03T10:00:00.000Z",
       "updated_at": "2026-11-03T10:00:00.000Z"
     },
     "secret": "whsec_3Jx9b2kQ7mVt4ZpR8nYc1LwE6aHs0DfG"
   }
   ```

   Store it as a secret of your Worker: `wrangler secret put SHERPO_WEBHOOK_SECRET`.

2. **Verify each delivery** against the raw body before parsing it:

   ```js
   // rawBody is the request body exactly as received, before any JSON parsing.
   async function verifyWebhook(secret, rawBody, signatureHeader, toleranceSeconds = 300) {
     if (!secret) throw new Error('The webhook secret is missing.');
     const fields = Object.fromEntries(
       (typeof signatureHeader === 'string' ? signatureHeader : '').split(',').map((field) => field.split('=', 2)),
     );
     const t = Number(fields.t);
     if (!Number.isInteger(t) || !/^[0-9a-f]{64}$/.test(fields.v1 ?? '')) return false;
     if (Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
     const encoder = new TextEncoder();
     const key = await crypto.subtle.importKey(
       'raw',
       encoder.encode(secret),
       { name: 'HMAC', hash: 'SHA-256' },
       false,
       ['verify'],
     );
     const signature = new Uint8Array(
       fields.v1.match(/../g).map((byte) => parseInt(byte, 16)),
     );
     // verify compares in constant time.
     return crypto.subtle.verify('HMAC', key, signature, encoder.encode(t + '.' + rawBody));
   }
   ```

3. **Copy each order from the API, one refresh at a time.** The event only says the order changed: the Worker reads the order from the API and writes that, and every read and write of one order goes through its own Durable Object, one refresh after another, so the newest read writes last. The event's `id` is recorded once its order is written; a failure answers an error, so the delivery is tried again. A schedule copies the orders too, in batches that pick up where the last one stopped, for what no event brings, such as a refund a payment processor takes back; [keep orders in sync](/merchant-api/guides/sync-orders#2-copy-what-exists) explains how.

   Give the Worker a second token, with `transaction:read` and `revenue:read`, as `SHERPO_TOKEN`: one that never expires, or one you replace before it does, since every order event fails while it is refused. Give it the store's id as `SHERPO_STORE`, and put `verifyWebhook` from step 2 in the same file.

   ```js
   // Bindings: DB (D1), ORDER_COPIES (Durable Objects of OrderCopy), and the secrets SHERPO_WEBHOOK_SECRET,
   // SHERPO_TOKEN (transaction:read and revenue:read) and SHERPO_STORE. verifyWebhook is the check above.
   import { DurableObject } from 'cloudflare:workers';

   const BASE = 'https://api.sherpo.io/merchant';
   // The schedule, as the configuration's crons name it.
   const START_RECENT = '0 3 * * *';
   const START_ALL = '0 4 * * 1';
   const CONTINUE = '5,15,25,35,45,55 * * * *';
   // A run refreshes at most this many orders, and takes none past this long, so it ends within its time.
   const BATCH = 500;
   const RUN_MS = 8 * 60 * 1000;
   // A run holds a copy this long at most, so one cut off frees it for the next.
   const LEASE_MS = 15 * 60 * 1000;

   export default {
     async fetch(request, env) {
       if (request.method !== 'POST') return new Response(null, { status: 405 });
       const body = await request.text();
       const signature = request.headers.get('Sherpo-Signature') ?? '';
       if (!(await verifyWebhook(env.SHERPO_WEBHOOK_SECRET, body, signature)))
         return new Response('Bad signature', { status: 400 });
       const event = JSON.parse(body);
       // An event says the order changed; its copy comes from the API. A failure throws, so the delivery is retried.
       if (event.type === 'order.created' || event.type === 'order.refunded')
         await refreshOrder(env, event.data.order.id);
       await env.DB.prepare('INSERT INTO webhook_events (id, type) VALUES (?, ?) ON CONFLICT (id) DO NOTHING')
         .bind(event.id, event.type)
         .run();
       return new Response(null, { status: 204 });
     },

     // Daily, a copy of the last three days starts; weekly, a copy of every order; between them, the copies go on.
     async scheduled(controller, env) {
       if (controller.cron === START_RECENT)
         return startCopy(env, 'recent', new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString());
       if (controller.cron === START_ALL) return startCopy(env, 'all', null);
       if (controller.cron === CONTINUE) return continueCopies(env);
       throw new Error(`No order copy runs on the schedule ${controller.cron}.`);
     },
   };

   // Starts a copy of the orders since a time, or of every order; one of that kind still running goes on.
   async function startCopy(env, kind, since) {
     await env.DB.prepare("INSERT INTO order_copies (kind, since, cursor) VALUES (?, ?, '') ON CONFLICT (kind) DO NOTHING")
       .bind(kind, since)
       .run();
   }

   // Goes on with the running copies, the last days' first, within one run's batch and time.
   async function continueCopies(env) {
     const run = { lease: crypto.randomUUID(), started: Date.now(), left: BATCH };
     const { results } = await env.DB.prepare("SELECT kind FROM order_copies ORDER BY kind = 'all'").all();
     const failures = [];
     for (const { kind } of results) {
       // Taken only while no other run holds it, so two runs never work one copy.
       const copy = await env.DB.prepare(
         'UPDATE order_copies SET lease = ?, leased_until = ? WHERE kind = ? AND (leased_until IS NULL OR leased_until < ?) ' +
           'RETURNING since, cursor, last_id',
       )
         .bind(run.lease, run.started + LEASE_MS, kind, run.started)
         .first();
       if (copy === null) continue;
       let error = null;
       try {
         await copySome(env, run, kind, copy);
       } catch (thrown) {
         error = thrown;
         failures.push(thrown);
       }
       await env.DB.prepare('UPDATE order_copies SET leased_until = NULL, error = ? WHERE kind = ? AND lease = ?')
         .bind(error === null ? null : String(error.message), kind, run.lease)
         .run();
     }
     // A failed copy keeps its place and its error, and fails the run, so it shows among the Worker's cron events.
     if (failures.length > 0)
       throw new AggregateError(failures, `Order copies failed: ${failures.map((failure) => failure.message).join('; ')}`);
   }

   // Refreshes one copy's orders from where it stopped, keeping its place after each order.
   async function copySome(env, run, kind, copy) {
     let { cursor, last_id: lastId } = copy;
     const going = () => run.left > 0 && Date.now() - run.started < RUN_MS;
     while (going()) {
       const query = new URLSearchParams([['sort', 'occurred'], ['direction', 'asc'], ['limit', '100']]);
       if (copy.since !== null) query.append('filter[occurred_at][gte]', copy.since);
       if (cursor !== '') query.append('cursor', cursor);
       const page = await call(env, `/v1/stores/${env.SHERPO_STORE}/orders?${query}`, true);
       // A run that stopped within this page refreshed the orders up to its last one.
       const done = page.items.findIndex((order) => order.id === lastId);
       for (const order of page.items.slice(done + 1)) {
         if (!going()) return;
         await refreshOrder(env, order.id, true);
         run.left -= 1;
         lastId = order.id;
         await keep(env, run, kind, cursor, lastId);
       }
       if (page.cursor === null) {
         await env.DB.prepare('DELETE FROM order_copies WHERE kind = ? AND lease = ?').bind(kind, run.lease).run();
         return;
       }
       cursor = page.cursor;
       lastId = null;
       await keep(env, run, kind, cursor, lastId);
     }
   }

   // Keeps a copy's place, while this run still holds it.
   async function keep(env, run, kind, cursor, lastId) {
     const { meta } = await env.DB.prepare('UPDATE order_copies SET cursor = ?, last_id = ? WHERE kind = ? AND lease = ?')
       .bind(cursor, lastId, kind, run.lease)
       .run();
     if (meta.changes === 0) throw new Error(`The ${kind} copy was taken by another run.`);
   }

   // Reads an order from the API and writes it, through the one object that copies that order.
   export async function refreshOrder(env, id, patient = false) {
     await env.ORDER_COPIES.get(env.ORDER_COPIES.idFromName(id)).refresh(id, patient);
   }

   export class OrderCopy extends DurableObject {
     #last = Promise.resolve();

     // One refresh at a time: each read starts once the previous copy is written, so the newest read writes last.
     refresh(id, patient) {
       const run = this.#last.then(() => copyOrder(this.env, id, patient));
       this.#last = run.catch(() => {});
       return run;
     }
   }

   async function copyOrder(env, id, patient) {
     const order = await call(env, `/v1/stores/${env.SHERPO_STORE}/orders/${encodeURIComponent(id)}`, patient);
     // Amounts are null for a token without revenue:read: fail rather than store a wrong 0.
     if (order.total === null || order.refunded === null)
       throw new Error('The order has no amounts: give SHERPO_TOKEN revenue:read.');
     await env.DB.prepare(
       'INSERT INTO orders (id, number, total, currency, exponent, refunded) VALUES (?, ?, ?, ?, ?, ?) ' +
         'ON CONFLICT (id) DO UPDATE SET total = excluded.total, refunded = excluded.refunded',
     )
       .bind(order.id, order.number, order.total, order.currency, order.exponent, order.refunded)
       .run();
   }

   // Reads from the API with the Worker's token. A patient read waits out a 429, as long as its Retry-After
   // says up to a minute, or longer each time without one; anything else throws with the API's reason.
   async function call(env, path, patient = false, attempt = 1) {
     const response = await fetch(BASE + path, { headers: { Authorization: `Bearer ${env.SHERPO_TOKEN}` } });
     if (response.ok) return response.json();
     const after = response.headers.get('Retry-After');
     const wait = after === null ? 2 ** attempt : Number(after);
     if (response.status === 429 && patient && attempt < 5 && wait <= 60) {
       await response.body?.cancel();
       await new Promise((resolve) => setTimeout(resolve, wait * 1000));
       return call(env, path, patient, attempt + 1);
     }
     const problem = await response.json().catch(() => ({}));
     throw new Error(`${path} answered ${response.status}${problem.detail ? `: ${problem.detail}` : ''}.`);
   }
   ```

   The tables it writes, in D1, with the first copy of every order its first scheduled run starts:

   ```sql
   CREATE TABLE webhook_events (id TEXT PRIMARY KEY, type TEXT NOT NULL);
   CREATE TABLE orders (id TEXT PRIMARY KEY, number INTEGER, total INTEGER, currency TEXT, exponent INTEGER, refunded INTEGER NOT NULL);
   CREATE TABLE order_copies (kind TEXT PRIMARY KEY, since TEXT, cursor TEXT NOT NULL, last_id TEXT, lease TEXT, leased_until INTEGER, error TEXT);
   INSERT INTO order_copies (kind, since, cursor) VALUES ('all', NULL, '');
   ```

   Its configuration, with the Durable Object, the database and the schedule (in UTC):

   ```jsonc
   {
     "name": "sherpo-orders",
     "main": "src/index.js",
     "compatibility_date": "2026-05-01",
     "durable_objects": { "bindings": [{ "name": "ORDER_COPIES", "class_name": "OrderCopy" }] },
     "migrations": [{ "tag": "v1", "new_sqlite_classes": ["OrderCopy"] }],
     "d1_databases": [{ "binding": "DB", "database_name": "sherpo-orders", "database_id": "<your database id>" }],
     "triggers": { "crons": ["0 3 * * *", "0 4 * * 1", "5,15,25,35,45,55 * * * *"] }
   }
   ```

## Test it

- Create the endpoint: the next order in your store is delivered as it happens.
- <a href="/merchant-api/reference/list-webhook-deliveries/">`GET /webhook_deliveries`</a> shows each delivery's attempts, the status your endpoint answered and the last error.
- <a href="/merchant-api/reference/resend-webhook-delivery/">`POST /webhook_deliveries/{delivery}/resend`</a> sends one again, with the same `id`, so your endpoint should change nothing the second time.

## Answer fast

Answer within 5 seconds, or the attempt counts as failed and is retried. Here the order's refresh is what records the event, so it runs before the answer, and a slow one only costs a retry; never move it after the answer (into `ctx.waitUntil`), which would answer `2xx` for an order never written. Other slow work can go after the answer.

## When the secret leaks

Roll it with <a href="/merchant-api/reference/roll-webhook-secret/">`POST /webhooks/{webhook}/secret/roll`</a>, store the new one, and the old one signs nothing more.

```bash
curl -X POST 'https://api.sherpo.io/merchant/v1/stores/STORE_ID/webhooks/c4b3a291-8f7e-4d6c-8b5a-49382716a5b4/secret/roll' \
  -H "Authorization: Bearer $SHERPO_TOKEN"
```

```js
const answer = await sherpo('POST', '/v1/stores/STORE_ID/webhooks/c4b3a291-8f7e-4d6c-8b5a-49382716a5b4/secret/roll');
```

Source: https://docs.sherpo.io/merchant-api/guides/receive-webhooks/index.mdx
