# 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](/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](/configuration) · [Shipping](/commerce/shipping) ·
[Discounts](/commerce/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.                  |
| `tax` on a Channel    | Tax for reduced rates or markets outside the EU. | `"eu-standard"`, the EU's daily rates. |
| `deliverOrder`        | Hand each paid Order to your ERP.                | Your ERP fetches Orders, or nobody.    |
| `identity` (settings) | Trust your shop's login.                         | Every buyer is a guest.                |

```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](/integrations) ·
[Stock & ERP hand-off](/integrations/inventory) · [Tax](/integrations/tax) ·
[Signed-in buyers](/integrations/identity) · Recipe:
[Prices and stock from your ERP](/recipes/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](/integrations/remote-contracts)

### 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](/integrations/events) ·
[Sending the buyer's emails](/integrations/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](/commerce/extensions) · Recipe: [A gift message, end to end](/recipes/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` and `deliveryAddress`.                      |
| 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](/sdks/react) ·
Recipes: [Add to cart](/recipes/add-to-cart), [A checkout without React](/recipes/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](/commerce/shipping#dhl-packstation-and-pickup-points)

## What you cannot extend yet

| You want                                        | Today                                                                                                                    |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| A payment provider of your own                  | Not yet. Stripe, Adyen, Mollie, PAYONE and PayPal are built in, and their contract is internal. You map methods to them. |
| Shipping prices from a carrier's API            | Not yet. Shipping is rules per country, by weight and restriction.                                                       |
| 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.                                    |
| Fields of your own inside `<Checkout>`          | No slot yet. Ask in the bag, or build the page with `useCheckout()`.                                                     |
| 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](/status) says what comes next. Start building with the [Recipes](/recipes).