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

> ## Agent Instructions
> Laces is event registration software for every kind of event, not only races. Use the event's own wording.
> There is one environment, production: payments made through the API are real. Money is integer minor units; read the event's currency.
> Collecting payments with no Laces event uses POST /payments, then POST /orders/{orderId}/pay: start at /guides/collect-payments. Never call pay to test: there is no sandbox.
> Never put a client secret in browser code or an LLM chat. Branch on error_code, not on message.
> Overview of Laces: https://laces.run/llms.txt

# Webhooks for payments: verify and fulfil once

> Laces webhooks for payments on your own site: order.paid, order.failed and order.refunded payloads, signature check, duplicates and catching missed orders.

A verified webhook tells your server **when to look**. Proof of payment is a
server-side read of the order that says `paid` now (scope `orders:read`).

> [!NOTE]
>
> **Every request on this page** goes to `https://connect.laces.run/v1`, from
> your **server**, with `Authorization: Bearer <token>`. Laces must first turn
> on payments for your organization, and your API key needs `payments:write`,
> `orders:write` and `orders:read`. Never send an
> organization id: Laces takes the organization from the token. The client
> secret stays on your server, never in a browser or an LLM chat. **There is
> no sandbox: a pay request moves real money.**

## Set it up

In the Laces app ([app.laces.run](https://app.laces.run)), an owner or admin
opens **Settings → Developers → Webhooks**, adds a public `https` URL, picks
the events, and copies the signing secret (`LCSWHSEC-…-X`, shown once) to your
server. **Send test event** posts a signed `ping`, with no money involved.

> [!NOTE]
>
> Webhooks go to **every** subscribed endpoint of your organization, for
> **every** order: ticket orders and payments, whoever created them. Once
> Laces turns payments on, endpoints you already have start receiving payment
> orders, and API keys with `orders:read` start seeing them in reads and lists.
> Branch on `data.order.order_type`.

## What is different from a ticket order

| | Payment | Ticket order |
| - | - | - |
| `data.order.order_type` | `"partner_payment"` | Absent |
| `event_id`, at the top and on the order | **Absent** | Present |
| `ticket_count`, `registrations` | **Absent** | Ticket fields |
| `partner_reference`, `description`, `product`, `metadata`, `source_url`, `source_site`, `requested_amount`, `requested_currency`, `payer_country` on the order | Present (`product`, `metadata`, `source_url`, `source_site` and `payer_country` only when set) | Absent |

`source_site` is the host of `source_url`, or of the key's default site. It
says where you said the buyer was; it is not proof. No payload carries the
buyer's name, email or phone: read the order for those.

## The payloads

```json order.paid theme={null}
{
  "id": "LCSWHD-9F3A7C21B4D85E60A1C2D3E4F5061728",
  "type": "order.paid",
  "created": 1795594530,
  "attribution": {
    "channel": "partner_api",
    "api_client_id": "LCSCLI-EXAMPLECLNT2345EXAMP",
    "checkout_session_id": null,
    "partner_reference": "SHOP-ORDER-8812"
  },
  "data": {
    "order": {
      "id": "Pm4xT9cL",
      "order_code": "LC-3N8V5K",
      "order_type": "partner_payment",
      "status": "paid",
      "currency": "UGX",
      "subtotal": 50000,
      "discount_total": 0,
      "donation_total": 0,
      "laces_fee": 2500,
      "total": 52500,
      "failure_kind": null,
      "partner_reference": "SHOP-ORDER-8812",
      "description": "Club jersey, size L",
      "product": "jersey",
      "metadata": { "cart_id": "c-8812", "size": "L" },
      "source_url": "https://shop.example.com/jerseys/home",
      "source_site": "shop.example.com",
      "requested_amount": 50000,
      "requested_currency": "UGX",
      "attribution": {
        "channel": "partner_api",
        "api_client_id": "LCSCLI-EXAMPLECLNT2345EXAMP",
        "checkout_session_id": null,
        "partner_reference": "SHOP-ORDER-8812"
      },
      "hold_expires_at": null,
      "prompt_expires_at": null,
      "created_at": "2026-11-25T08:14:03.000Z"
    }
  }
}
```

```json order.failed theme={null}
{
  "id": "LCSWHD-1B7D90E3A6F24C58D0E9B2C4A7F31566",
  "type": "order.failed",
  "created": 1795594530,
  "attribution": {
    "channel": "partner_api",
    "api_client_id": "LCSCLI-EXAMPLECLNT2345EXAMP",
    "checkout_session_id": null,
    "partner_reference": "SHOP-ORDER-8812"
  },
  "data": {
    "order": {
      "id": "Pm4xT9cL",
      "order_code": "LC-3N8V5K",
      "order_type": "partner_payment",
      "status": "failed",
      "currency": "UGX",
      "subtotal": 50000,
      "discount_total": 0,
      "donation_total": 0,
      "laces_fee": 2500,
      "total": 52500,
      "failure_kind": "timed_out",
      "partner_reference": "SHOP-ORDER-8812",
      "description": "Club jersey, size L",
      "product": "jersey",
      "metadata": { "cart_id": "c-8812", "size": "L" },
      "source_url": "https://shop.example.com/jerseys/home",
      "source_site": "shop.example.com",
      "requested_amount": 50000,
      "requested_currency": "UGX",
      "attribution": {
        "channel": "partner_api",
        "api_client_id": "LCSCLI-EXAMPLECLNT2345EXAMP",
        "checkout_session_id": null,
        "partner_reference": "SHOP-ORDER-8812"
      },
      "hold_expires_at": null,
      "prompt_expires_at": null,
      "created_at": "2026-11-25T08:14:03.000Z"
    }
  }
}
```

```json order.refunded (the price only) theme={null}
{
  "id": "LCSWHD-C40E8A17F5B2936D7E1A0C9B8D6F2431",
  "type": "order.refunded",
  "created": 1795594530,
  "attribution": {
    "channel": "partner_api",
    "api_client_id": "LCSCLI-EXAMPLECLNT2345EXAMP",
    "checkout_session_id": null,
    "partner_reference": "SHOP-ORDER-8812"
  },
  "data": {
    "order": {
      "id": "Pm4xT9cL",
      "order_code": "LC-3N8V5K",
      "order_type": "partner_payment",
      "status": "refunded",
      "currency": "UGX",
      "subtotal": 50000,
      "discount_total": 0,
      "donation_total": 0,
      "laces_fee": 2500,
      "total": 52500,
      "failure_kind": null,
      "partner_reference": "SHOP-ORDER-8812",
      "description": "Club jersey, size L",
      "product": "jersey",
      "metadata": { "cart_id": "c-8812", "size": "L" },
      "source_url": "https://shop.example.com/jerseys/home",
      "source_site": "shop.example.com",
      "requested_amount": 50000,
      "requested_currency": "UGX",
      "attribution": {
        "channel": "partner_api",
        "api_client_id": "LCSCLI-EXAMPLECLNT2345EXAMP",
        "checkout_session_id": null,
        "partner_reference": "SHOP-ORDER-8812"
      },
      "hold_expires_at": null,
      "prompt_expires_at": null,
      "created_at": "2026-11-25T08:14:03.000Z"
    },
    "refund": { "id": "rf_8hQ2", "amount": 50000, "status": "completed" }
  }
}
```

```json order.refunded (part) theme={null}
{
  "id": "LCSWHD-7A52D1C9E08B4F36A1D7C5E2B9F04813",
  "type": "order.refunded",
  "created": 1795594530,
  "attribution": {
    "channel": "partner_api",
    "api_client_id": "LCSCLI-EXAMPLECLNT2345EXAMP",
    "checkout_session_id": null,
    "partner_reference": "SHOP-ORDER-8812"
  },
  "data": {
    "order": {
      "id": "Pm4xT9cL",
      "order_code": "LC-3N8V5K",
      "order_type": "partner_payment",
      "status": "partially_refunded",
      "currency": "UGX",
      "subtotal": 50000,
      "discount_total": 0,
      "donation_total": 0,
      "laces_fee": 2500,
      "total": 52500,
      "failure_kind": null,
      "partner_reference": "SHOP-ORDER-8812",
      "description": "Club jersey, size L",
      "product": "jersey",
      "metadata": { "cart_id": "c-8812", "size": "L" },
      "source_url": "https://shop.example.com/jerseys/home",
      "source_site": "shop.example.com",
      "requested_amount": 50000,
      "requested_currency": "UGX",
      "attribution": {
        "channel": "partner_api",
        "api_client_id": "LCSCLI-EXAMPLECLNT2345EXAMP",
        "checkout_session_id": null,
        "partner_reference": "SHOP-ORDER-8812"
      },
      "hold_expires_at": null,
      "prompt_expires_at": null,
      "created_at": "2026-11-25T08:14:03.000Z"
    },
    "refund": { "id": "rf_2kL7", "amount": 20000, "status": "completed" }
  }
}
```

* **`order.paid` can be late or out of order.** Read the order and fulfil only
  if it is `paid` now: it may have been refunded since.
* **`order.failed` says an attempt failed, not that the buyer gave up.** It can
  arrive while they are already trying again, and the order can still become
  `paid`. It is sent **once per order**: a second failure sends nothing. Its
  `data.order.status` is `failed` or `expired`. It is not sent for a try that
  never reached the payment provider. Don't release stock or places on it: at
  your own deadline, read the order.
* **An abandoned payment sends nothing.** Read the order.
* **`refund.amount` is in the order's `currency`**, minor units. For a
  cross-border payment that is the buyer's currency, not `requested_currency`.
  `refunded` means the price is back; less is `partially_refunded`. Act on
  `refund.amount`, not only on the status. Order reads don't show refunded
  amounts, and a refund that fails sends nothing. The fee can come back later,
  and one charge of an order paid twice can be returned without an event: see
  [Refunds](https://docs.laces.run/concepts/fees.md#refunds).
* **`order.refunded` is not proof that the buyer has the money.** Where your balance
  is too low and you pay the buyer directly, it is sent when Laces records the
  refund, before you have paid them.

## A complete handler (Node, Express)

```js webhook.js theme={null}
import crypto from "node:crypto";
import express from "express";
import { laces } from "./laces.js";
import { db } from "./db.js"; // your own store, see below

const SECRET = process.env.LACES_WEBHOOK_SIGNING_SECRET;
const CLIENT_ID = process.env.LACES_CLIENT_ID;
if (!SECRET || !CLIENT_ID) throw new Error("Laces webhook settings are missing");

function verifyLacesSignature(rawBody, header, secret, toleranceSec = 300) {
  let t = null;
  const sigs = [];
  for (const part of String(header || "").split(",")) {
    const i = part.indexOf("=");
    if (i < 0) continue;
    const k = part.slice(0, i).trim();
    const v = part.slice(i + 1).trim();
    if (k === "t" && /^\d{1,12}$/.test(v)) t = Number(v);
    if (k === "v1") sigs.push(v);
  }
  if (t === null || sigs.length === 0) return false;
  if (Math.abs(Date.now() / 1000 - t) > toleranceSec) return false;

  const expected = Buffer.from(
    crypto.createHmac("sha256", secret).update(`${t}.${rawBody}`, "utf8").digest("hex"),
  );
  return sigs.some((s) => {
    const got = Buffer.from(s);
    return got.length === expected.length && crypto.timingSafeEqual(got, expected);
  });
}

export const app = express();

// express.raw, NOT express.json: the signature covers the raw bytes.
app.post("/laces/webhook", express.raw({ type: "application/json" }), async (req, res) => {
  try {
    const raw = req.body.toString("utf8");
    if (!verifyLacesSignature(raw, req.header("X-Laces-Signature"), SECRET)) {
      // 503, not 400: Laces keeps trying, so events sent while you change the
      // signing secret are not lost.
      return res.status(503).send("bad signature");
    }
    const delivery = req.header("X-Laces-Delivery");
    if (!(await db.seenDelivery(delivery))) {
      await handleEvent(JSON.parse(raw));
      await db.markDelivery(delivery); // only AFTER the work: a crash means a retry
    }
    res.status(200).send("ok"); // within 10 seconds
  } catch (err) {
    console.error(err);
    res.status(500).send("try again"); // Laces sends it again later
  }
});

// Safe to run twice and in any order.
export async function handleEvent(event) {
  const order = event.data?.order;
  if (!order) return; // ping: {"type":"ping","data":{"message":"..."}}
  if (order.order_type !== "partner_payment") return handleTicketOrder(event);

  // Every order of the organization is sent here. Ignore other API keys' orders.
  if (order.attribution.api_client_id !== CLIENT_ID) return;

  // An order id you saved, or your own reference (you may not have saved the id yet).
  const purchase =
    (await db.findByLacesOrderId(order.id)) ??
    (await db.findByReference(order.partner_reference));
  if (!purchase) return db.saveForReview(null, order, "unknown payment");

  if (event.type === "order.refunded") {
    return refundPayment(purchase, order, event.data.refund);
  }
  if (event.type === "order.paid") return fulfilIfPaid(purchase, order.id);
  // order.failed: an attempt failed, and the buyer may already be trying again.
  // Release nothing here; releaseIfOver() below does.
}

// The only place a refund event becomes a review, for payments and ticket
// orders. Safe to run again.
export async function refundPayment(purchase, order, refund) {
  const result = await db.recordRefund(purchase.id, order, refund);
  if (result !== "short") return; // undone, or nothing to undo
  const why = order.status === "refunded"
    ? "refunded, but our saved refunds are less than the price"
    : `part refund ${refund.id}`;
  await db.saveForReview(purchase.id, order, why);
}

// Also called by your job and your return page. Reads the order as it is NOW,
// so an old or late event can't fulfil something refunded since.
export async function fulfilIfPaid(purchase, orderId) {
  // Under 10 seconds in all, so the webhook is answered in time. orders:read
  const order = await laces("GET", `/orders/${orderId}`, { timeoutMs: 6000 });
  if (order.status === "partially_refunded" && !purchase.fulfilled) {
    return db.saveForReview(purchase.id, order, "part refunded before we fulfilled");
  }
  if (order.status !== "paid") return; // refunded meanwhile, or not paid yet
  if (
    order.partner_reference !== purchase.reference ||
    order.requested_amount !== purchase.amount ||
    order.requested_currency !== purchase.currency
  ) {
    return db.saveForReview(purchase.id, order, "not what we asked for");
  }
  await fulfil(purchase, order);
}

// Every way to fulfil ends here: payments, ticket orders, your jobs.
export async function fulfil(purchase, order) {
  const why = {
    paid_by_other_order: "paid twice: refund one",
    undone: "paid after an undo: refund, or rebook by hand",
    released: "paid after release: refund, or rebook by hand",
  }[await db.fulfilOnce(purchase.id, order)];
  if (why) await db.saveForReview(purchase.id, order, why);
}

// Run it when YOUR deadline for the stock or places has passed. It holds the
// lock of pay and retryPayment, so nobody starts paying while it decides.
export function releaseIfOver(purchase) {
  return db.withLock(purchase.id, async () => {
    if ((await db.stateOf(purchase.id)).fulfilled) return;
    const attempts = [
      ...(await db.attemptsOf(purchase.id)),
      ...(await db.ticketOrdersOf(purchase.id)), // [] if you never sold event tickets
    ];
    for (const attempt of attempts) {
      if (!attempt.orderId) continue; // pay was never called on it
      const order = await laces("GET", `/orders/${attempt.orderId}`, { timeoutMs: 6000 });
      if (order.status === "paid") {
        if (order.order_type === "partner_payment") return fulfilIfPaid(purchase, order.id);
        return handleTicketOrder({ type: "order.paid", data: { order } });
      }
      if (["cart", "payment_initiated", "prompt_sent"].includes(order.status)) return; // ask later
      if (!["failed", "expired", "cancelled", "refunded"].includes(order.status)) {
        return db.saveForReview(purchase.id, order, "not clear if it is over"); // part refunded, disputed
      }
      if (Date.now() - (attempt.unansweredAt ?? 0) < 3 * 60_000) return; // a pay may be running
    }
    await db.release(purchase.id); // a late order.paid then goes to review
  });
}

// A person closes a "paid after ..." review by giving the buyer their purchase.
export async function rebookIfPaid(purchase, orderId) {
  const order = await laces("GET", `/orders/${orderId}`, { timeoutMs: 6000 });
  return order.status === "paid" ? db.rebook(purchase.id, order) : "not_paid";
}

async function handleTicketOrder(event) {
  // Your code for event orders, if you have any. Moving from them? See
  // "Move from event orders": it must use fulfil and refundPayment too.
}
```

Your `db` must do this:

**The price** below is `subtotal - discount_total + donation_total`, on ticket
orders and payments alike (on a payment it equals `subtotal`). `stateOf` reads
`fulfilled`, `undone` and `released` of the purchase, shared by its ticket orders
and payments. `fulfilOnce`, `recordRefund`, `undo`, `rebook`, `release` and
`adopt` are **one transaction each that locks the purchase's row**. They are
short and never take `withLock`, which can be held for minutes.

* `fulfilOnce(purchaseId, order)`: sets `fulfilled` to `order.id` if it is empty
  and the purchase is not released. Only `rebook` changes it later. Returns
  `"fulfilled"`, or does nothing and returns `"already"` (this same order did
  it, undone since or not), `"refunded"` (there are refunds saved for
  `order.id`, and they reach the price), `"undone"` (another order did it and it
  was undone), `"paid_by_other_order"`, or `"released"` (nothing did it, and the
  stock or places were given back).
* `rebook(purchaseId, order)`: only if the purchase is released or undone, and no
  refunds saved for `order.id` reach the price. Takes stock or places again,
  clears `undone` and `released`, sets `fulfilled` to `order.id`. In any other
  case it changes nothing, so twice is the same as once and a purchase that
  stands is never overwritten.
* `undo(purchaseId, orderId)`: **once**, and only if `purchase.fulfilled` is
  `orderId` and `purchase.undone` is empty: sets `purchase.undone` to `orderId`
  and takes the goods or places back. A person who undoes by hand uses it too.
  `purchase.fulfilled` stays set.
* `recordRefund(purchaseId, order, refund)`: saves the refund once per
  `refund.id`, with `order.id`, then looks at all the refunds saved for that
  order, also when this one was saved before:
  * `purchase.undone` is `order.id`: returns `"recorded"`. The fee coming back
    later, or an event after an undo by hand, changes nothing.
  * They are less than the price: returns `"short"`, for a person to adjust.
  * They reach the price: does what `undo` does, in this same transaction, so a
    crash can't save the refund without the undo. Returns `"undone"`, or
    `"recorded"` if another order fulfilled the purchase, or none did. So
    refunding the second of two paid orders never undoes a real purchase.
* `priceIsBack(order)`: do the refunds saved for `order.id` reach the price?
* `saveForReview(purchaseId, order, why)`: a person looks at it, **once per
  order and reason**, also after they closed it. Unknown payments go there too.
* `attemptsOf(purchaseId)`: its payments. `ticketOrdersOf(purchaseId)`: its event
  orders, `{ orderId, unansweredAt? }`. Keep them apart: a payment retry can't
  reuse a ticket order.
* `release`: gives kept stock or places back, once, and sets `released`. Never if
  `fulfilled` is set, so it does nothing after an undo, which already gave them back.
* `adopt`, `findByTicketOrderId`, `saveTicketOrder`: only if you
  [move from event orders](https://docs.laces.run/payments/move-from-event-orders.md).
  `adopt(purchaseId, orderId, { undone })` sets `fulfilled`, and `undone` if
  asked, only where `fulfilled` is empty. `saveTicketOrder(purchaseId, orderId)`
  adds the order to `ticketOrdersOf` once.
* `seenDelivery`, `markDelivery`: the `X-Laces-Delivery` ids you have handled.

The secret is the **whole** string, with `LCSWHSEC-` and `-X`. **Roll signing
secret** has no overlap: the old one stops at once, and queued events are signed
with the new one, so deploy the new secret straight away. The `503` above keeps
Laces trying meanwhile; a `400` stops after 3 tries. Those `503`s still count
towards the 50 failures in a row that switch the endpoint off. Other languages:
[Webhooks](https://docs.laces.run/guides/webhooks.md#how-do-i-verify-the-webhook-signature).

## Delivery

Answer any `2xx` within 10 seconds. Otherwise Laces tries again after about 1
minute, 5 minutes, 30 minutes, 2, 6 and 12 hours: 7 attempts in all. Redirects
are not followed. Network errors, timeouts, `5xx`, `408` and `429` use every
attempt; any other `4xx` stops after 3. After 50 failures in a row the
endpoint is switched off until you re-enable it in the app.

## Reconcile: catch what you missed

Every few minutes, read each purchase you are still waiting for
(`GET /orders/{orderId}`, scope `orders:read`). Once a day, list the payments
and compare them with your records:

```bash theme={null}
export LACES_BASE="https://connect.laces.run/v1"

TOKEN=$(curl -s -X POST "$LACES_BASE/oauth/token" \
  -u "$LACES_CLIENT_ID:$LACES_CLIENT_SECRET" \
  -d "grant_type=client_credentials" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["access_token"])')
```

```bash theme={null}
curl -s "$LACES_BASE/orders?order_type=partner_payment&limit=100" \
  -H "Authorization: Bearer $TOKEN"
```

```json Response 200 theme={null}
{
  "code": 200,
  "message": "Orders retrieved successfully",
  "data": {
    "orders": [
      {
        "id": "Pm4xT9cL",
        "order_code": "LC-3N8V5K",
        "order_type": "partner_payment",
        "status": "paid",
        "currency": "UGX",
        "subtotal": 50000,
        "discount_total": 0,
        "donation_total": 0,
        "laces_fee": 2500,
        "total": 52500,
        "failure_kind": null,
        "partner_reference": "SHOP-ORDER-8812",
        "description": "Club jersey, size L",
        "product": "jersey",
        "metadata": { "cart_id": "c-8812", "size": "L" },
        "source_url": "https://shop.example.com/jerseys/home",
        "source_site": "shop.example.com",
        "requested_amount": 50000,
        "requested_currency": "UGX",
        "buyer": { "name": "Amina Nakato", "email": "amina@example.com", "phone": "+256763494235" },
        "attribution": {
          "channel": "partner_api",
          "api_client_id": "LCSCLI-EXAMPLECLNT2345EXAMP",
          "checkout_session_id": null,
          "partner_reference": "SHOP-ORDER-8812"
        },
        "hold_expires_at": null,
        "prompt_expires_at": null,
        "created_at": "2026-11-25T08:14:03.000Z"
      }
    ],
    "next_cursor": "eyJzIjoxNzk1NTk0NDQzLCJuIjowLCJpZCI6IlBtNHhUOWNMIn0"
  }
}
```

**Keep going until `next_cursor` is `null`.** A page can be short, or even
empty, and still have a next page.

```js laces.js theme={null}
// Node 18+. Server only: it uses the client secret.
const BASE = process.env.LACES_BASE ?? "https://connect.laces.run/v1";
const TIMEOUT_MS = 60_000; // a pay call can take a while

let cached = { token: null, exp: 0 };
async function getToken(signal) {
  if (cached.token && Date.now() < cached.exp - 60_000) return cached.token;
  const basic = Buffer.from(
    `${process.env.LACES_CLIENT_ID}:${process.env.LACES_CLIENT_SECRET}`,
  ).toString("base64");
  const res = await fetch(`${BASE}/oauth/token`, {
    method: "POST",
    headers: {
      Authorization: `Basic ${basic}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: "grant_type=client_credentials",
    signal,
  });
  const body = await res.json();
  if (!res.ok) throw new Error(`token: ${body.error}`);
  cached = { token: body.access_token, exp: Date.now() + body.expires_in * 1000 };
  return cached.token;
}

export async function laces(method, path, { body, idempotencyKey, timeoutMs = TIMEOUT_MS } = {}) {
  const signal = AbortSignal.timeout(timeoutMs); // the whole call, token included
  for (let refreshed = false; ; refreshed = true) {
    const res = await fetch(`${BASE}${path}`, {
      method,
      headers: {
        Authorization: `Bearer ${await getToken(signal)}`,
        ...(body && { "Content-Type": "application/json" }),
        ...(idempotencyKey && { "Idempotency-Key": idempotencyKey }),
      },
      ...(body && { body: JSON.stringify(body) }),
      signal,
    });
    const json = await res.json().catch(() => ({}));
    if (res.ok) return json.data;
    if (json.error_code === "invalid_token" && !refreshed) {
      cached = { token: null, exp: 0 }; // once: the token was refused before any work
      continue;
    }
    const err = new Error(json.error_code ?? `http_${res.status}`);
    err.status = res.status;
    err.code = json.error_code ?? null; // stable: branch on this
    err.details = json.details ?? null;
    err.retryAfter = Number(res.headers.get("Retry-After")) || null;
    err.requestId = res.headers.get("X-Request-Id"); // quote this to support
    throw err;
  }
}
```

```js reconcile.js theme={null}
import { laces } from "./laces.js";
import { db } from "./db.js"; // your own store
import { fulfilIfPaid } from "./webhook.js";

// Newest first. Stops at payments CREATED before `since`, so go back as far as
// you give refunds: an old payment can be refunded today.
export async function reconcile(since) {
  let cursor = null;
  let failed = 0;
  pages: do {
    const query = new URLSearchParams({ order_type: "partner_payment", limit: "100" });
    if (cursor) query.set("cursor", cursor);
    const page = await laces("GET", `/orders?${query}`);
    for (const order of page.orders) {
      if (Date.parse(order.created_at) < since.getTime()) break pages;
      try {
        await check(order);
      } catch (err) {
        failed += 1; // the others still get checked
        console.error(order.id, err);
      }
    }
    cursor = page.next_cursor;
  } while (cursor !== null);
  if (failed) throw new Error(`${failed} payments not checked: run again`);
}

async function check(order) {
  if (order.attribution.api_client_id !== process.env.LACES_CLIENT_ID) return;
  if (!["paid", "partially_refunded", "refunded", "chargeback_flagged"].includes(order.status)) return;
  const purchase =
    (await db.findByLacesOrderId(order.id)) ??
    (await db.findByReference(order.partner_reference));
  if (!purchase) return db.saveForReview(null, order, "paid, unknown to us");
  if (order.status === "paid") {
    if (purchase.fulfilled !== order.id) await fulfilIfPaid(purchase, order.id);
  } else if (order.status === "chargeback_flagged") {
    await db.saveForReview(purchase.id, order, "disputed");
  } else if (order.status === "partially_refunded" || !(await db.priceIsBack(order))) {
    // The status is in the reason, so a missed last part is a new review.
    await db.saveForReview(purchase.id, order, `${order.status}: check the amount in the app`);
  }
}
```

Reads carry no refunded amount, so a **second** missed part refund of an order
that is still `partially_refunded` can't be seen here. Check the app when you
close such a review.

`order_type=ticket` lists ticket orders only. Without the filter you get both.
`event_id` never matches a payment.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.