# Extend OrbCart

Every place your code plugs into OrbCart, from one line of configuration to a package of your own, and what cannot be extended yet.

OrbCart has no generic hooks such as `beforeQuote`. Every extension point has a name and one job, so
it stays clear who decides a price, a tax amount or a stock level ([How it works](/docs/cart/how-it-works)).
The points below go from shallow to deep. Most shops stop after the third.

| Step | Extension point                                              | Use it for                                                   |
| ---- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 1    | [Configuration](#configure)                                  | Markets, shipping, discounts, legal texts, contact fields.   |
| 2    | [Contracts in your Worker](#answer-contracts-in-your-worker) | Prices, stock, tax and the hand-off, from your systems.      |
| 3    | [Contracts elsewhere](#answer-them-from-another-system)      | The same, answered by your middleware or another Worker.     |
| 4    | [Events](#react-to-events)                                   | Telling your systems what happened: mails, accounting.       |
| 5    | [Extensions](#add-fields-of-your-own)                        | Values OrbCart does not know, such as a gift message.        |
| 6    | [The React kit](#shape-the-storefront)                       | Look, wording and parts of your own in the checkout.         |
| 7    | [Packages](#package-it-for-other-shops)                      | One extension for many shops, such as the DHL pickup finder. |

### Configure

A shop is one `defineCommerce` call, and most needs are a declaration, not code. A market is a
Channel, free shipping is a discount, freight for a canoe is a shipping rule:

```ts title="src/worker.ts" members="ChannelConfig"
shipping: {
  DE: [
    { id: "standard", title: "Standard (DHL)", price: 495, excludes: ["bulky"] },
    { id: "freight", title: "Freight", price: 4900, requires: ["phone"], only: ["bulky"] },
  ],
},
discounts: [
  { id: "free-shipping", scope: "shipping", percentage: 100, minimumSubtotal: 5000, methods: ["standard"] },
],
```

OrbCart checks the whole configuration when the Worker starts, so a typo fails the deploy, never a
buyer. [Configuration](/docs/shop/configuration) · [Shipping](/docs/shop/shipping) ·
[Discounts](/docs/shop/discounts)
### Answer contracts in your Worker

A contract is one function with one job. OrbCart calls it with every Line at once, a context and a
time budget, and checks each answer against the contract. Only `offers` is required:

| Contract                     | Your job                                                                                            | Without it                                               |
| ---------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| `offers`                     | Prices and facts for the Lines of a Cart.                                                           | Required.                                                |
| `inventory`                  | Check stock, or hold it from Quote to Order.                                                        | Stock limits nothing.                                    |
| `appointments`               | Hold and book an appointment for a Line.                                                            | No merchant appointment service.                         |
| `pickupLocations`            | Provide Locations where buyers can collect an Order.                                                | Pickup can use Locations declared in shipping.           |
| `tax` on a Channel           | Tax for markets outside the EU or a tax service.                                                    | The built-in tax tables.                                 |
| `shippingRates` on a Channel | [Price a shipping method](/docs/shop/shipping#prices-from-your-carrier-or-erp) from your carrier or ERP. | The prices in your shipping rules.                       |
| `deliverOrder`               | Hand each paid Order to your ERP.                                                                   | Enable `fetchOrders` if your ERP fetches Orders instead. |
| `fetchOrders` (setting)      | Acknowledge that your ERP fetches Orders instead of receiving a call.                               | No automatic handoff without `deliverOrder`.             |
| `identity` (settings)        | Trust your shop's login.                                                                            | Every buyer is a guest.                                  |
| `orderActions`               | [Your own actions on an Order](/docs/integrate/order-actions), such as a parcel label.                   | Support has Ship, Cancel, Take back and Refund.          |
| `paymentProviders`           | [A payment provider of your own](/docs/shop/payment-provider), as a preview.                             | The built-in providers.                                  |

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

export default defineCommerce({
  channels,
  offers: (lines, { currency }) => pricing.offers(lines, { currency }),
  deliverOrder: async (order, { signal }) => {
    const salesOrder = await erp.createSalesOrder(order, { idempotencyKey: order.id, signal });
    return { reference: salesOrder.number };
  },
});
```

A contract that throws counts as unreachable, and the buyer never sees a guess. One that changes
something, such as `deliverOrder`, is called at least once with a stable key, `order.id` here: being
idempotent on it is your only duty. [Offers](/docs/integrate/offers) ·
[Stock & ERP hand-off](/docs/integrate/inventory) · [Tax](/docs/integrate/tax) ·
[Signed-in buyers](/docs/integrate/identity) · Recipe:
[Prices and stock from your ERP](/docs/integrate/erp-prices-and-stock)
### Answer them from another system

Any contract can live outside the Worker: `http()` calls an endpoint of yours, `service()` another
Worker. The arguments, the time budget and the checks stay the same, and every HTTP call is signed:

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

export default defineCommerce({
  channels,
  offers: service("PRICES"),
  deliverOrder: http("https://middleware.nordgrat.de/orders"),
});
```

Your endpoint checks each call with `verifyRequest()` from `@orbcart/admin`, on Workers, Node or
Deno. [Contracts in another system](/docs/integrate/remote-contracts)

When OrbCatalog keeps your goods and your own code prices what only your shop sells, such as a
fitting in the workshop, attach both. The catalog stays the authority for every reference it knows:

```ts title="src/worker.ts" members="CommerceConfig"
import { http } from "@orbcart/runtime";

offers: {
  catalog: http("https://catalog.nordgrat.de/orbcart/offers"),
  merchant: {
    references: ["BOOT-FITTING"],
    offers: (lines) =>
      lines.map((line) => ({
        reference: line.reference,
        title: "Schuhanpassung in der Werkstatt",
        price: { amount: 2500, currency: "EUR" },
        taxCategory: "standard",
        supply: {
          type: "b2c_work_on_movable_goods",
          location: {
            id: "loc_munich",
            name: "Nordgrat Werkstatt München",
            address: {
              line1: "Werkstattweg 1",
              postalCode: "80331",
              city: "München",
              country: "DE",
            },
          },
        },
      })),
  },
},
```

This fitting is work on the buyer's own boots, not work included in selling new boots. Use your
catalog Location's `id`, `name` and `address` for `supply`, never buyer configuration.
[Scope and tax rules →](/docs/integrate/tax#work-performed-at-your-location)

A buyer puts three headlamps and a boot fitting in the Cart, then quotes and orders:

1. OrbCart asks the catalog for every Line, signed, and your function only for the references you
   named, both at once, each within its own time budget. A Cart without your references never
   waits for your function.
2. The headlamp's offer is the catalog's as it came: price, compare-at price, tags, expiry, sale
   window, shipping restrictions and limits. Express is gone if the lamp's battery excludes it, and
   three lamps become the two the catalog allows, a change the buyer sees.
3. The fitting is yours only where the catalog answers `unknown` for it. If the catalog offers a
   reference you named, both answers are ignored and the line cannot be bought (`answer_invalid`)
   until one of you gives it up. Any other answer of the catalog, such as out of stock, not offered,
   malformed or none at all, stays the catalog's, and yours is not used.
4. If either side throws or runs out of time, the Quote is refused as `provider_unavailable`, and
   the buyer's next try asks both again. Nothing is guessed. An answer of either side that is no
   list, or an entry that names no reference, makes every Line of the Cart unavailable
   (`answer_invalid`), as from any `offers` provider.
5. When the catalog invalidates the headlamp, the next Quote has its new price. A buyer who accepts
   an older Quote gets `quote_changed` with the new price; placed Orders keep theirs.
6. Publishing a product invalidates its SKUs as well as its tag, so a fitting the catalog starts
   selling cannot keep a cached merchant price. Merchant offers in this composition last at most
   15 minutes, even with a longer `expiresAt`; a shorter expiry stays shorter. This lifetime also
   bounds the ownership check when an invalidation is missed. Catalog offers keep their own expiry.

The diagnostics record both sides as one `offers` call: a violation's position counts entries of the
combined answer, and a side that runs out of its own time budget is recorded as `threw` with a
`TimeoutError`, not `timed_out`.

A shipping discount's `minimumSubtotal` counts only eligible shipped Lines before discounts,
never the fitting. If the discount names `references` or `tags`, only matching shipped Lines
count. Its `methods` still limit which shipping methods receive the discount.
### React to events

Events tell your systems what happened: an Order arose, a payment was captured, a Cart stood still.
Each arrives at least once, with an `id` to deduplicate by; over HTTP, it is signed:

```ts title="src/worker.ts" members="CommerceConfig"
import { http } from "@orbcart/runtime";

events: {
  mails: http("https://mail.nordgrat.de/orbcart", { types: ["order.created", "cart.abandoned"] }),
  ledger: { run: (event, { signal }) => accounting.book(event, { signal }), types: ["payment.*"] },
},
```

Events carry no personal data, so load the Order with your secret key. OrbCart sends no emails:
your mail system sends them from these events. Never hang a duty on an event; handing an Order to
the ERP is `deliverOrder`, which retries until it succeeds. [Order events](/docs/integrate/order-events) ·
[Sending the buyer's emails](/docs/integrate/buyer-emails)
### Add fields of your own

An extension is a typed value on a Line or the Cart, declared once with a schema. OrbCart checks it on
every write, keeps it in the Quote and freezes it in the Order:

```ts title="src/commerce.ts" members="CommerceConfig"
import { z } from "zod";

extensions: {
  engraving: { on: "line", schema: z.object({ text: z.string().trim().min(1).max(20) }) },
  giftMessage: { on: "cart", schema: z.string().max(200) },
},
```

A Line extension reaches `offers`, which may charge for it. A Cart extension never changes an
amount. [Extensions](/docs/shop/extensions) · Recipe: [A gift message, end to end](/docs/shop/gift-message)
### Shape the storefront

The React kit hands over control in layers, each one deeper:

| Layer     | How                                                                                    |
| --------- | -------------------------------------------------------------------------------------- |
| Look      | `--orbcart-*` tokens and `data-part` selectors. Never class names.                     |
| Wording   | `labels` and `words`, over the built-in German and English.                            |
| Parts     | Slots such as `lineImage`, `paymentHelp`, `deliveryAddress` and `fields`.              |
| Page      | `CheckoutDetails`, `CheckoutPayment` and the other regions as children, in your order. |
| Markup    | `Cart`, `Line`, `Totals`, `DiscountCode` and more, or `useCheckout()` for all of it.   |
| Framework | The checkout store `cart.checkout()`, which `<Checkout>` runs on.                      |

A slot is your component, drawn where the checkout's own would be. The checkout keeps the draft, the
checks and the submission. This delivery address offers to send the parcel to the shop for pickup and
keeps the buyer's own address for the bill:

```tsx title="app/delivery-address.tsx" browser
import { AddressFields } from "@orbcart/react";
import type { DeliveryAddressProps } from "@orbcart/react";

const store = {
  company: "Nordgrat Store",
  line1: "Leopoldstraße 12",
  line2: "",
  postalCode: "80802",
  city: "München",
  region: "",
  country: "DE",
};

export function DeliveryAddress({ heading, onReplace, ...fields }: DeliveryAddressProps) {
  return (
    <>
      <legend data-part="orbcart-checkout-address-heading">{heading}</legend>
      <button
        type="button"
        onClick={() => onReplace({ ...fields.value, ...store }, { preserveBillingAddress: true })}
      >
        Pick it up at our Munich store
      </button>
      <AddressFields {...fields} />
    </>
  );
}
```

Pass it as `<Checkout cart={cart} deliveryAddress={DeliveryAddress} />`. [React checkout](/docs/shop/react-checkout) ·
Recipes: [Add to cart](/docs/shop/add-to-cart), [A checkout without React](/docs/shop/checkout-without-react)
### Package it for other shops

There is no plugin registry. A plugin is a package that fills the seams above: a component for a kit
slot, a contract a shop attaches, or a helper for the shop's server. `@orbcart/plugin-dhl` is the
model, with one entry point per place it runs:

| Entry point                      | Holds                                                       | Runs in            |
| -------------------------------- | ----------------------------------------------------------- | ------------------ |
| `@orbcart/plugin-dhl`            | `PickupSearch`, `PickupLocation`: schemas both sides share. | Browser and server |
| `@orbcart/plugin-dhl/react`      | `DhlPickupProvider` and `DhlDeliveryAddress` for the slot.  | Browser            |
| `@orbcart/plugin-dhl/server`     | `findDhlLocations()`, with the shop's DHL key.              | The shop's server  |
| `@orbcart/plugin-dhl/styles.css` | Styles on the kit's `--orbcart-*` tokens.                   | Browser            |

Four rules keep a plugin safe to install:

- **Depend on public packages only.** The kit and the runtime never depend on a plugin.
- **Keep secrets in a server entry point.** The DHL key never reaches a browser bundle.
- **Decide nothing OrbCart owns.** A plugin may fill an address; prices, tax and stock stay with
  OrbCart and your contracts.
- **Leave the shop working without it.** Removing the slot removes the plugin.

An ERP connector has the same shape: a package that exports `offers`, `inventory` and
`deliverOrder`. [DHL pickup points](/docs/shop/shipping#dhl-packstation-and-pickup-points)

## What you cannot extend yet

| You want                                        | Today                                                                                                                 |
| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Express buttons of your own payment provider    | Not yet. [A provider of your own](/docs/shop/payment-provider) carries payment methods; express and wallets stay built in. |
| Shipping methods a carrier defines itself       | Not yet. You declare the methods; [your system prices them](/docs/shop/shipping#prices-from-your-carrier-or-erp).          |
| A rule before the Quote, such as a B2B approval | No hook, by design. A contract for checkout rules comes once shops need the same one.                                 |
| Extension values from an AI agent               | Not over UCP. The agent hands the checkout to the buyer.                                                              |
| A "€20.10 to free shipping" hint                | The Cart does not carry the distance to a threshold yet.                                                              |
| Emails sent by OrbCart                          | By design not. Your mail system sends them from events.                                                               |

The [status page](/docs/cart/status) says what comes next. Start building with the [Recipes](/docs/shop/recipes).