# 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. Its `units` say per Line how many were `ordered`,
`fulfilled`, `canceled` and `returned`, and how many may still ship or be canceled (`open`) or come
back (`returnable`).

## Find a buyer's Orders

By the buyer's email, across Channels, by the `sub` of their [identity](/docs/integrate/identity), or by
both. A buyer's Orders are the ones they placed signed in and the ones they placed as a guest with
their address, an earlier one included, each once:

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

Pages are newest first and carry `next`. With several identity systems registered, add the
`issuer` that `buyer` belongs to. A person of your team at some Locations finds only the Orders of
those. The email travels in the POST body; the list takes the `sub` alone, since an address does
not belong in a URL:

```ts
const signedIn = await admin.orders.list({ buyer: "user_8f2c", payment: ["captured"] });
```

## 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.

### Report on a period

A month's report does not read an Order at a time. Name the period, sort `oldest` and `expand`
the Orders: each entry then carries its Order whole, as `get()` reads it, with buyer, Lines,
options, appointments and history.

```ts
const page = await admin.orders.list({
  since: "2026-10-01T00:00:00+02:00",
  until: "2026-11-01T00:00:00+01:00",
  sort: "oldest",
  expand: "order",
  limit: 50,
});
// page.data[0].order.contact, page.data[0].order.quote.lines, then page.next
```

A page with whole Orders holds at most 50: the list knows which Orders belong in the period, and
each is read from the object that keeps it whole, so a page costs a few dozen reads in parallel.
An Order's time never changes, so pages follow each other without gaps once the list caught up;
for the last few seconds, read again later. A person of your team at some Locations reports only
the Orders of those, and one without the Orders area reads them without the buyer.

## 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 →](/docs/integrate/order-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 →](/docs/integrate/order-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",
  contract: "deliverOrder",
});
```

For a backend behind an `http()` [contract](/docs/integrate/remote-contracts). It checks that the environment signed the call
(RFC 9421, key from its published JWKS) and returns the typed 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 parsed against the named contract only once the
signature holds.

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 `target`, the full URL
OrbCart sent to, behind a proxy that rewrites it, and `keysTimeoutSeconds`.

## 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>

### Refund a deposit

Return a refundable security without refunding merchandise:

```ts
await admin.orders.refund(
  order.id,
  { lines: [{ line: "l_1", target: "deposit", quantity: 1 }] },
  { idempotencyKey: "returned-security-4711" },
);
```

`admin.orders.refunds(order.id)` reports each Line's independent remaining `quantity` and,
where it has a deposit, `depositQuantity` under `available.lines`. Pending and succeeded
refunds consume the selected entitlement; a failed attempt releases it. Retry the same attempt
with its original key, including after a disconnect or restart.

Without `target`, a whole-unit refund credits merchandise and up to that many outstanding
deposits as separate frozen credit Lines. A deposit already refunded is never refunded again.
`component` cannot be combined with `target: "deposit"`, and a component refund takes no deposit.
The admin refund screen has its own deposit selector. "Select everything" selects whole units
and only the extra deposit quantity they do not cover. A single atomic request accepts up to
200 selections, leaving room for separate merchandise and deposit targets on 100 Lines.
Neither this target nor a refund records
physical returns, evidence or a merchant's legal eligibility decision.

The receipt and `payment.refunded` event identify deposit credits by `target: "deposit"`.
Invoice-style providers receive the same merchandise/deposit references and separate tax rates
as the sale, rather than a combined credit with an ambiguous tax rate. Deposits do not change
fulfilled, canceled or returned merchandise quantities.

## 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.

## Cancel before shipping

```ts
await admin.orders.cancel(order.id, { reason: "Ordered twice" });
```

Without `lines`, every unit that hasn't shipped is canceled. OrbCart refunds what was captured for
those units, and the shipping once nothing is left to ship. An Order canceled whole before its
capture releases the authorization instead. Part of an Order can be canceled once its payment is
captured. Units your `inventory.commit` booked go back through
[`inventory.restock`](/docs/integrate/inventory#reserve-stock-during-checkout); a hold not yet booked is
released. `order.canceled` follows.

## Record a return

```ts
await admin.orders.recordReturn(order.id, {
  lines: [{ line: "l_1", quantity: 1 }],
  reason: "Too small",
  restock: true,
});
await admin.orders.refund(order.id, { lines: [{ line: "l_1", quantity: 1 }], reason: "Too small" });
```

Only shipped units come back. With `restock: true` they go back to your stock through
[`inventory.restock`](/docs/integrate/inventory#reserve-stock-during-checkout). The refund is its own
step, so you decide what goes back. `order.returned` follows.

## Record a payment received

An Order paid by bank transfer or on site starts awaiting its money (`payment.status` is
`pending_funds`, `payment.owed` the total). When the money arrives, record it, as a
reconciliation script does for each matching line of the bank statement:

```ts
await admin.orders.recordPayment(order.id, {
  amount: { amount: 8990, currency: "EUR" },
  receivedAt: "2026-11-06T09:30:00Z",
  reference: "TX-2026-110601",
});
```

Pass the bank's transaction ID as `reference`: a run that sees the same transfer again changes
nothing. A short payment leaves the rest owed. Once nothing is owed, the payment is `captured`
and an overdue Order is no longer overdue. `payment.captured` follows for each payment received.
More than is owed, or a record on an Order that owes nothing or is paid through a provider, is
refused. `receivedAt` is now when left out.

A refund of such an Order is recorded, not sent: you pay it back outside OrbCart, and
`admin.orders.refund` records that you did. Canceling units of an Order not paid in full first
lowers what is owed. When what it received, less what refunds gave back, then exceeds what the
units the buyer keeps cost, the cancel records the difference as one refund without lines. The
shipping counts as kept until every unit of the Order is canceled or a refund names it. A line
whose entire quantity was refunded is not refunded again on cancellation. Canceled whole, the Order gives back everything it
still holds. A repeat of the cancel with the same Idempotency-Key refunds nothing more.

For example, a buyer pays 104.85 € of an Order for a backpack (89.90 €), a guidebook (14.99 €)
and the shipping (4.95 €). The backpack comes back and you refund it, 89.90 €. When you then
cancel the guidebook, the cancel records a refund of 10.00 €: the 14.95 € still held less the
shipping. `payment.refunded` reads 99.90 € and `payment.owed` 0, as the Order's history and its
refunds list do.

## Confirm your ERP took an Order

Only needed when your ERP fetches Orders (`fetchOrders: true`) instead of receiving them through
[`deliverOrder`](/docs/integrate/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 Checkout view in the admin's Orders area 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](/docs/integrate/order-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 →](/docs/cart/http-api)