# Orders & refunds

Read Orders, give money back and report shipments from your backend.

`@orbcart/admin` runs on your server. It uses the environment's **secret key**.
Never import it into browser code.

## Connect

```ts title="lib/admin.ts"
import { createAdmin } from "@orbcart/admin";

export const admin = createAdmin({
  url: env.ORBCART_URL,
  key: env.ORBCART_SECRET_KEY,
});
```

## Find an Order

By number, ID or just the number's digits:

```ts
const order = await admin.orders.get("NG-2026-004711");
```

`get()` reads the Order itself, always current. By the buyer's email, across
Channels:

```ts
const { data } = await admin.orders.search({ email: "anna@example.com" });
```

## List Orders

```ts
const page = await admin.orders.list({ attention: true, sort: "newest", limit: 50 });
const next = page.next ? await admin.orders.list({ attention: true, after: page.next }) : undefined;
```

| Filter        | Example                    | Lists Orders…              |
| ------------- | -------------------------- | -------------------------- |
| `attention`   | `true`                     | that need a person.        |
| `payment`     | `["authorized", "failed"]` | by payment state.          |
| `fulfillment` | `["unfulfilled"]`          | by shipping state.         |
| `refunds`     | `["partial", "full"]`      | with refunds.              |
| `handoff`     | `["pending"]`              | your ERP hasn't taken yet. |
| `channel`     | `["de"]`                   | in these Channels.         |

To show how many Orders match, add `count: true`. The answer then carries `count: { value, capped }`
for all matching Orders, whatever the page. It counts up to 1000: `capped: true` means "1000 or more".
It is a number to show, from the list a few seconds behind; read an Order itself to decide.

The list is a fast index without personal data. It can lag a few seconds behind
a purchase. Use `get()` when the current state matters.

## Fetch events

```ts
const page = await admin.events.list({ type: ["order.*"], limit: 50 });
```

For a system that fetches events instead of receiving them. Newest first, seconds behind,
without personal data; each entry shows how far every receiver's delivery came.
[Events →](/integrations/events#fetch-instead-of-receive)

## Operate receivers

```ts
await admin.receivers.list(); // name, kind, state, backlog, lastSuccess
await admin.events.resend(eventId, { receiver: "erp" });
await admin.events.replay({ since: "2026-10-01T00:00:00Z", receiver: "erp" });
await admin.receivers.pause("erp");
await admin.receivers.resume("erp");
```

For what the code defines under `events`, and for repairing after an outage. Reading is for every
member; `resend`, `replay`, `pause` and `resume` are for owners and developers. A receiver that
verifies deliveries uses `verifyEvent()` from the same package.
[Events →](/integrations/events#repair-a-receiver)

## Verify a contract call

```ts
import { verifyRequest } from "@orbcart/admin";

const { body, requestId, idempotencyKey } = await verifyRequest(request, {
  url: "https://commerce.nordgrat.de",
});
```

For a backend behind an `http()` [contract](/integrations/remote-contracts). It checks that the environment signed the call
(RFC 9421, key from its published JWKS) and returns the JSON body, the request ID to find the call
in the diagnostics, and for a contract that changes something the `idempotencyKey`: the same in
every retry, so be idempotent on it. The body is read only once the signature holds. It is
unvalidated JSON: parse it against what the contract sends.

It throws a `RequestVerificationError` with a `code`, the way `verifyEvent()` throws an
`EventVerificationError`. Both extend `VerificationError`, so a handler for both catches one class.
A signature made for an event never passes `verifyRequest()`, and the other way round
(`wrong_purpose`). The options are those of `verifyEvent()`, including `authority` behind a proxy.

## Refund

Name what goes back. OrbCart calculates the amount from the Order's frozen prices,
including discounts and tax. You never send an amount:

```ts
const refund = await admin.orders.refund(
  order.id,
  { lines: [{ line: "l_1", quantity: 1 }], reason: "return" },
  { idempotencyKey: "return-4711-backpack" },
);

refund.status; // "succeeded" | "pending" | "failed"
refund.amount; // { amount: 8990, currency: "EUR" }
```

More shapes:

```ts alternatives value="RefundInput"
{ lines: [{ line: "l_2", component: "GROUNDSHEET" }] } // one part of a bundle
{ lines: [], shipping: true }                         // the shipping cost only
{ lines: [{ line: "l_1" }], shipping: true }          // a Line and the shipping
```

**Preview first** when a person confirms the amount:

```ts
const preview = await admin.orders.previewRefund(order.id, { lines: [{ line: "l_1" }] });
await admin.orders.refund(order.id, { lines: [{ line: "l_1" }], expectedAmount: preview.amount });
```

The refund is refused if the amount changed in between.

<Callout title="Idempotency keys">
  Keep the same `idempotencyKey` when you retry the **same** refund after a crash. Use a new key for
  a new refund. `pending` means the provider hasn't confirmed yet. OrbCart keeps asking.
</Callout>

## Report shipments

```ts
await admin.orders.fulfill(order.id, {
  lines: [{ line: "l_1", quantity: 1 }],
  reference: "DELIVERY-80012",
  carrier: "DHL",
  tracking: "00340434161094042557",
});
```

The same `reference` twice changes nothing.

## Confirm your ERP took an Order

Only needed when your ERP fetches Orders (`fetchOrders: true`) instead of receiving them through
[`deliverOrder`](/integrations/inventory#or-let-your-erp-fetch-orders). The full polling loop is
there:

```ts
await admin.orders.acknowledge(order.id, { reference: "SO-2026-1234" });
```

## Carts that need a person

Sometimes a problem happens before an Order exists, such as a refund the provider
refused after the buyer left. Those Carts are listed:

```ts
const page = await admin.carts.needingAttention();
const { issues, history } = await admin.carts.get(page.data[0].id);
```

## End a promotion

```ts
await admin.offers.invalidate({ tags: ["summer-sale"] });
await admin.offers.invalidate({ references: ["BACKPACK-30-GREEN"] });
```

Open Carts ask your `offers` function again. Placed Orders keep their prices.

## See where buyers get stuck

```ts
const { funnel, checkout, friction, payments } = await admin.insights.checkout({
  days: 14,
  channel: ["de"],
  origin: "storefront", // or "agent"
});
```

Counts, never Carts: the funnel from the first line to the Order with where purchases stopped, how long
the checkout took (median and slowest tenth, apart from the time buyers took to decide), what got in
their way, and how they paid, with wallets apart. There is no personal data in it, so the secret key and
every member may read it. Declines and 3-D Secure count under `friction`, not per method: a
journey keeps only the method a purchase ended on. The Explorer's Checkout view draws the same answer.

The environment keeps 30 days of events, so that is the longest period. `window` says what was
counted: when it is shorter than asked, or when more than 10,000 events were in it and the oldest were
left out, `window.limit` says why. Carts from before journeys were recorded are not in the numbers
(`withoutJourney` counts them). To keep more than 30 days, attach an ordinary
[events receiver](/integrations/events) and store the `journey` of `order.created` and
`cart.abandoned` yourself.

## Inspect the environment

```ts
const { mode, channels } = await admin.environment.get();
```

Shows the mode, the jurisdiction and every Channel with its payment methods, as
deployed. Useful in a health check.

[See every HTTP endpoint →](/api-reference)