# Order events

Tell your systems what happened to an Order and to the purchase before it, such as a confirmation to send or a payment to book.

An event is a fact: the Order was created, a payment was captured, a payment ended without an
Order, a Cart stood still. Attach a function, an HTTP endpoint or another Worker under `events` and
every one of them reaches it, at least once. It is optional. Without `events` nothing is delivered,
and the events stay in the [event list](#fetch-instead-of-receive).

OrbCart sends no emails itself. The events tell your mail system what is due:
[Sending the buyer's emails →](/integrations/buyer-emails).

## Receive events

```ts title="src/worker.ts"
export default defineCommerce({
  channels,
  offers,
  events: {
    mails: async (event) => {
      await mailQueue.add(event.id, event); // take it, store it, return
    },
    ledger: {
      run: (event, { signal }) => accounting.book(event, { signal }),
      types: ["payment.captured", "payment.refunded"],
      timeoutMs: 5_000, // at most 10 seconds, which is also the default
    },
  },
});
```

Each receiver has a name that stays the same across deployments. It identifies the receiver
in the delivery protocol. `types` limits what it gets: one type, or every type below a
prefix like `order.*`. Without `types` a receiver gets every event.

## Receive events over HTTP

An endpoint of yours, such as a middleware in front of your ERP, takes events as signed requests.
Attach it with `http()`:

```ts title="src/worker.ts"
import { defineCommerce, http, service } from "@orbcart/runtime";

export default defineCommerce({
  channels,
  offers,
  events: {
    erp: http((vars) => vars.get("MIDDLEWARE_URL"), { types: ["order.*", "payment.*"] }),
    audit: http("https://audit.nordgrat.de/events", { previews: true, timeoutMs: 5_000 }),
    mails: service("MAILER", { types: ["order.created"] }),
  },
});
```

The address is a string, or a function that reads it from the variables and secrets of the
deployment, so each environment calls its own endpoint. If the function returns nothing, or an
address that is not allowed, the attempt fails as `invalid_target` and is retried like any other.
Only `https` on port 443 is allowed, with a name instead of an IP address, no user name or
password, no private name such as `localhost`, `.internal` or `.local`, and never this
environment's own address. Under `wrangler dev`, `http` and `localhost` work too.

Each delivery is a `POST` of the event as a CloudEvents JSON body
(`Content-Type: application/cloudevents+json`). Acknowledge with **any 2xx within 10 seconds**.
A redirect, any other status or a timeout counts as failed, and OrbCart never follows a redirect.
Answer `429` or `503` with `Retry-After&#x60; to ask for time, up to an hour. Answer
&#x2A;*`410 Gone`** to say you want no more: the receiver is paused until someone resumes it.
OrbCart stores the status and the first kilobyte of every answer in the delivery protocol, so keep
personal data out of your error bodies.

### Verify a delivery

Every delivery is signed with the environment's key. There is no secret to share: you verify
against the keys the environment publishes. In the endpoint:

```ts title="middleware/events.ts"
import { verifyEvent } from "@orbcart/admin";

export async function handle(request: Request): Promise<Response> {
  const event = await verifyEvent(request, { url: "https://commerce.nordgrat.de" });

  if (event.type === "order.created") {
    await erp.register(event.subject, { idempotencyKey: event.id });
  }
  return new Response(null, { status: 204 });
}
```

`verifyEvent` throws an `EventVerificationError` with a `code` when the delivery is not what
the environment signed, so answer those with a 4xx and do not process the event. It runs on
Workers, Node and Deno. It reads the request from a copy, so the body stays readable, and it
fetches `/.well-known/jwks.json` of `url` once, caches the keys, and asks again for an unknown
key at most once a minute.

If your endpoint sits behind a proxy that rewrites the `Host` header, pass the host OrbCart sent
to as `authority`: `verifyEvent(request, { url, authority: "middleware.nordgrat.de" })`.

| Code                    | Means                                                                    |
| ----------------------- | ------------------------------------------------------------------------ |
| `signature_missing`     | No signature, or one that cannot be read.                                |
| `wrong_purpose`         | Signed for something other than an event.                                |
| `unsupported_algorithm` | Not `ecdsa-p256-sha256`.                                                 |
| `missing_component`     | The signature leaves out something it must cover.                        |
| `outside_window`        | Made more than 5 minutes ago, expired, or from more than a minute ahead. |
| `digest_mismatch`       | The body is not the one that was signed.                                 |
| `unknown_key`           | The environment publishes no such key, also after asking again.          |
| `keys_unavailable`      | The keys could not be fetched and none is known.                         |
| `signature_invalid`     | The signature does not match: another body digest, path, host or key.    |
| `event_invalid`         | The body is no event, or not the one the `Webhook-Id` names.             |

For another language, any library for [RFC 9421](https://www.rfc-editor.org/rfc/rfc9421)
works. What OrbCart signs:

* `ecdsa-p256-sha256` with the key from `/.well-known/jwks.json`; `keyid` is its `kid`
  and `tag` is `orbcart-event`.
* The covered components are `@method`, `@authority`, `@path`, `@query`, `content-type`,
  `content-digest`, `webhook-id` and `webhook-timestamp`. A delivery cannot be redirected to another
  endpoint, or to the same one with other query parameters. `Content-Digest` is the SHA-256 of the body
  ([RFC 9530](https://www.rfc-editor.org/rfc/rfc9530)).
* `Webhook-Id` is the event's `id`, the same on every attempt. `Webhook-Timestamp` and `created`
  are the time of **this attempt**: every attempt is signed anew, and `expires` is five minutes after.
* A recorded request is worthless after that window. Inside it, the `id` protects you: a
  replayed request carries the id you already deduplicate by.

Each environment signs with its own key, so a middleware that verifies against `live` rejects an
event from `test` even if it reaches it by mistake.

## Receive events in another Worker

`service("MAILER")` delivers through a Service Binding of the same Worker. The event arrives
as `POST /events` with the CloudEvents JSON body, without a signature: only your account can
reach a binding. Acknowledge with any 2xx, like an HTTP endpoint.

## What an event looks like

An event is a [CloudEvents 1.0](https://cloudevents.io) event:

```json
{
  "specversion": "1.0",
  "id": "evt_01J8Z3W6Q4XB7N2M5K9RTV0HCE_3",
  "type": "order.created",
  "source": "https://commerce.nordgrat.de",
  "subject": "ord_01J8Z3W6Q4XB7N2M5K9RTV0HCE",
  "time": "2026-10-02T10:15:02.000Z",
  "environment": "live",
  "channel": "de",
  "dataschema": "https://commerce.nordgrat.de/v1/openapi.json#/webhooks/order.created",
  "data": {
    "order": { "id": "ord_01J8Z3W6Q4XB7N2M5K9RTV0HCE", "number": "NG-2026-004711", "version": 3 },
    "total": { "amount": 8990, "currency": "EUR" },
    "lines": [{ "line": "l_1", "reference": "BACKPACK-30-GREEN", "quantity": 1 }]
  }
}
```

`dataschema` points into your environment's own [OpenAPI description](/api-reference#endpoints), which
holds every type under `webhooks`; it is there when the environment knows its public address.

An event carries **no personal data**: no names, emails, addresses, phone numbers, tracking
numbers, notes, reasons in words or extension values. It does carry what you report yourself
as `carrier` and `reference` (up to 100 and 200 characters), so keep personal data out of
those. Load the Order for the rest, with your secret key:

```ts
const order = await admin.orders.get(event.subject); // for an event whose subject is an Order
```

That also gives you the current state, so a late event never works with stale data.

### What `subject` names

`subject` is the Order whenever the event concerns an Order that exists, and the Cart before. An
Order and its Cart share one key, so `ord_01J8…` and `cart_01J8…` belong together. The `data`
always names what exists: `data.order.id` for an Order, `data.cart` for a Cart, and the Payment
or Quote it is about. Events of one purchase are numbered together, in the order OrbCart told
them: the number at the end of `id` rises, and it has gaps.

### The catalog

| Type                    | When                                                     | `data`                                                           |
| ----------------------- | -------------------------------------------------------- | ---------------------------------------------------------------- |
| `quote.created`         | A Quote was made. The same Quote again is no new event.  | `cart`, `quote`, `total`                                         |
| `quote.accepted`        | The buyer agreed to a Quote, and its Payment begins.     | `cart`, `quote`, `payment`, `total`                              |
| `payment.authorized`    | The amount is reserved.                                  | `cart`, `payment`, `quote`, `amount`, `method`, `provider`       |
| `payment.pending_funds` | A slower method was accepted, the money comes later.     | as `payment.authorized`                                          |
| `payment.failed`        | A Payment ended without money, or a capture was refused. | as `payment.authorized`, `reason`, `order` once there is one     |
| `payment.canceled`      | A Payment was canceled, by the buyer or by OrbCart.      | as `payment.authorized`, `reason` when OrbCart canceled, `order` |
| `payment.captured`      | Money was collected, also in part.                       | `order`, `payment`, `amount`, `provider`                         |
| `payment.refunded`      | A refund succeeded.                                      | `order`, `payment`, `refund`, `amount`, `lines`                  |
| `payment.refund_failed` | A refund could not be settled.                           | `order`, `payment`, `refund`, `amount`                           |
| `order.created`         | The Order arose.                                         | `order`, `total`, `lines`, `journey`                             |
| `order.fulfilled`       | Units were shipped, picked up or delivered.              | `order`, `lines`, `carrier`, `reference`                         |
| `order.handed_off`      | Your ERP took the Order.                                 | `order`, `reference`                                             |
| `order.issue_opened`    | Something needs a person, such as `handoff_failed`.      | `order`, `issue`                                                 |
| `order.issue_resolved`  | It is resolved.                                          | `order`, `issue`, `resolvedBy` when one activity did             |
| `cart.abandoned`        | A Cart with lines stood still and has no Order.          | `cart`, `lines`, `journey`                                       |
| `cart.canceled`         | A Cart without an Order ended and is deleted.            | `cart`, `reason`                                                 |

Each Payment event also names `providerReference` once the provider has one. Never the provider's
own words: `reason` is a code.

* **`payment.failed`** is told once for a Payment: when the Payment itself failed (`reason` is
  `declined`, `authentication_failed` or `expired`), or when the provider refused to capture money
  an Order is owed. With today's providers a Payment that can have its capture refused is authorized or
  captured, and neither can fail afterwards, so the two do not tell the same Payment twice.
* **`payment.canceled`** has a `reason` when OrbCart canceled the attempt: `payment_window_elapsed`
  (nobody finished paying), `cart_changed` or `payment_method_changed` (the buyer changed their mind
  while an action was open), `amount_mismatch`. A cancellation that came from the provider has none.
* **`order.issue_opened`*&#x2A; and &#x2A;*`order.issue_resolved`** are told once for each change of an Order's
  issues. `issue` is its `type` and what it is about (`payment`, `refund`). An Order that arose before
  issues told keeps the ones it has quietly.
* **`cart.abandoned`** comes once per spell of standing still: when a Cart with lines had no change for
  the Channel's idle period, 24 hours unless you set `abandonedAfterHours` (1 to 720). The Cart itself stays
  as it is. A buyer who changes it starts the next spell. Reading a Cart as a merchant is no change.
  Carts without lines and Carts with an Order are never told.
* **`cart.canceled`** comes once, when a Cart without an Order ends. `reason` is `expired` when it had no
  change for the Channel's inactivity period, 180 days unless you set `expiresAfterDays`, or `discarded`
  when the agent whose checkout it was canceled it. The Cart is then deleted with everything in it, so
  loading it answers `cart_not_found`; its buyer's next visit starts a fresh Cart. A Cart whose Order
  arose never ends this way.
* **`journey`** on `order.created` and `cart.abandoned` tells how the purchase went, without anything
  the buyer typed: `channel`, `origin` (`storefront`, or `agent` for an agent platform's checkout),
  `steps` (`lines`, `quote`, `address`, `shipping`, `payment`, `order`, each with the time it was first
  reached; a step never reached is absent), `method` (`id` of the latest Payment attempt, and whether it
  ran as an `express` checkout) and `friction`, counts of `quoteChanged` (the buyer had to agree again),
  `declined`, `challenged` (a Payment asked the buyer to act at the provider, 3-D Secure for a card),
  `unknown` and `recovered` (what OrbCart cleared up without the buyer). On `order.created`, `resumed` is
  `true` when the Cart had been told as abandoned before. The last step on `cart.abandoned` is where the
  buyer stopped. A Cart stored before journeys were kept has none on `cart.abandoned` until it changes.

The list grows. &#x2A;*Ignore a type you do not know.**

## What OrbCart promises

* **At least once.** Your function may be called again with the same event. The `id` is
  always the same, so deduplicate by it. That is your only duty.
* **Acknowledged by returning.** Return without throwing within 10 seconds. Anything else
  counts as failed. Take the event, store it and return; do the work afterwards.
* **Retried for 72 hours.** After 5 seconds, 1, 5 and 30 minutes, then every hour. After
  72 hours the event is `failed` in the event list and stays there for 30 days.
* **A receiver that stays away is probed, not hammered.** Once nothing succeeded for an hour
  there is one try at a time, an hour apart, with an event that is due. An event your receiver
  rejects on every try never holds up the others. When it works again, the backlog follows in
  order, six at a time.
* **No order guaranteed.** Events of an Order usually arrive in order, but after a retry
  not necessarily. `data.order.version` rises with every change, so you can tell which is newer.
* **Events are not duties.** Handing an Order to your ERP is [`deliverOrder`](/integrations/inventory#hand-orders-to-your-erp),
  which retries until it succeeds. An event can be ignored, so do not hang a duty on one.

## Fetch instead of receive

A system that cannot receive calls reads the list. Newest first, seconds behind, with how
far each receiver's delivery came:

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

page.data[0].deliveries; // [{ receiver: "mails", status: "delivered", attempts: 1 }]
```

A delivery shows `pending` with `attempts: 0` while OrbCart is still trying. Its status and
the number of attempts are written when the delivery ends: `delivered`, or `failed` after
72 hours.

| Filter    | Example                         | Lists events…               |
| --------- | ------------------------------- | --------------------------- |
| `type`    | `["order.*", "payment.failed"]` | of these types or prefixes. |
| `subject` | `"ord_01J8…"`                   | of one Order or Cart.       |
| `channel` | `["de"]`                        | in these Channels.          |
| `since`   | `"2026-10-01T00:00:00Z"`        | that happened since.        |

The cursor follows the order in which events reached the list, so an event that arrives
late is never skipped. Events stay in the list for 30 days.

`source` is the environment's `PUBLIC_URL`, such as `https://commerce.nordgrat.de`. An
environment without that variable names itself with `urn:orbcart:{merchant}:{environment}`.

## Repair a receiver

Everything an operator does in the Explorer is also in the Admin SDK. Owners and developers may
change receivers; everyone on the team may read them.

```ts
const { data } = await admin.receivers.list();
// [{ name: "erp", kind: "http", state: "failing", backlog: 41, lastSuccess: "2026-10-02T08:14:00.000Z" }]

await admin.events.resend("evt_01J8Z3W6Q4XB7N2M5K9RTV0HCE_3", { receiver: "erp" }); // one event again
await admin.events.replay({ since: "2026-10-01T00:00:00Z", receiver: "erp" }); // everything since

await admin.receivers.pause("erp"); // during an ERP migration; events wait, their 72 hours run on
await admin.receivers.resume("erp"); // delivers the backlog at once
```

* `state` is `active`, `failing` (an hour without an acknowledgement, so only a probe goes out) or
  `paused`. `backlog` counts events not yet acknowledged and not yet given up on.
* **Resend and replay** hand the same events, with the same `id`, to the receiver again, each with
  72 hours from now. Without `receiver`, every receiver that wants the type gets them.
  A replay hands over at most 500 events per call; while the answer has `next`, pass it as `after`.
  Events stay available for 30 days.
* A receiver that is **paused** gets no attempts until it is resumed. `410 Gone` from an HTTP
  receiver pauses it the same way.

## In tests and previews

Functions and Service Bindings are called in every environment. **A preview environment
(`preview-…`) calls no HTTP endpoint** unless the receiver says `previews: true`, because a preview
isolates state but not outgoing calls: without the rule, every preview of your code would call the
middleware of production. The events of a preview are still kept and listed.

Events of a test environment name it: `environment` is `"test"` and `source` is its own address,
so a test Order is never taken for a real one, and its signature is made with the test key.