# Shipping

Declare delivery and store pickup, with prices and authoritative Catalog Locations.

Shipping lives in the Channel. The countries you list are the countries you ship
to. Every other country gets `ship_to_unsupported`.

```ts title="src/worker.ts" members="ChannelConfig"
shipping: {
  DE: [
    { id: "standard", title: "Standard (DHL)", price: 495, deliveryTime: "2-4 business days" },
    { id: "express", title: "Express", price: 1290, deliveryTime: "1 business day" },
  ],
  AT: [{ id: "standard", title: "Standard", price: 790, deliveryTime: "3-5 business days" }],
},
```

Prices are in minor units of the Channel's currency. `495` is €4.95.

## Collect at a store

A pickup rule names a Catalog Location by its ID, not its name or a copied address.
Provision the Location through Catalog's save API with a stable ID, or keep an explicit
mapping to the ID already provisioned. Mark it as `pickup` and assign it to the Channel.
One rule is one selectable method at one Location:

```ts members="ChannelConfig"
shipping: {
  DE: [
    { id: "standard", title: "Delivery", price: 495 },
    { type: "pickup", id: "collect-munich", title: "Collection", location: "loc_muenchen0001", price: 0 },
  ],
},
```

Attach the Locations contract beside `offers` in `defineCommerce`:

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

pickupLocations: http((vars) => `${vars.get("CATALOG_URL")}/orbcart/pickup-locations`),
```

This signed contract reads Catalog's primary,
not the cached public Location list. Only administratively open, pickup-enabled
Locations serving the Channel are offered; opening hours do not close a method.
The rule's country must match the Location's country. `price: 0` is free; positive
prices, weight tiers and the same `requires`, `only` and `excludes` work for pickup too.

The buyer still calls `cart.setShipping("collect-munich")`. Pickup is never
preselected. Its option includes `location: { id, name, address }`; the React kit
shows collection as one card whose picker searches stores by name, city or postal
code, and may start at the buyer's own store ([Delivery or pickup](/docs/shop/react-checkout#delivery-or-pickup)).
Pickup is offered before an address is entered, and so are the deliveries of a
Channel that delivers to one country alone; choosing pickup establishes the
Location's country when the cart has none. Only the country is needed for pickup,
not a delivery postal address. Switching
back to delivery keeps the address the buyer already entered and requires it again.

A cart shows the Locations its Worker read within the last minute, so adding to it and
reading it again do not ask Catalog each time; a Location that closes or moves shows
within that minute. A quote, a payment preparation and an acceptance always ask Catalog
anew and never offer what it no longer lists.

The selected Location is frozen into the signed quote and order. Before a new
payment, even a current quote checks the Location again: a closure, Channel/service
change or changed address requires a fresh quote rather than charging old consent.
An unavailable Catalog is retryable, not an empty list. Already-started payments
and historical orders keep their frozen Location. Payment eligibility is unchanged;
pickup goods are still physical goods, not a cart that ships nothing.

This does not allocate inventory at the selected store: the existing inventory
contract remains aggregate. Flat pickup pricing is not a quantity-surcharge rule.

## Delivery rule options

| Option         | Required | Example               | What it does                                                           |
| -------------- | -------- | --------------------- | ---------------------------------------------------------------------- |
| `id`           | yes      | `"express"`           | Your ID. Unique per country.                                           |
| `title`        | yes      | `"Express"`           | What the buyer sees. One text, or one per language.                    |
| `price`        | yes      | `1290`                | Minor units. `0` for free shipping. Or tiers by weight, or `"quoted"`. |
| `deliveryTime` |          | `"1 business day"`    | Your text, also per language. Shown as is, never calculated.           |
| `requires`     |          | `["phone"]`           | Contact fields this method needs, such as a phone number for freight.  |
| `excludes`     |          | `["lithium_battery"]` | Offer restrictions this method cannot carry.                           |
| `only`         |          | `["bulky"]`           | Offered only when a Line carries one of these restrictions.            |

## In several languages

`title` and `deliveryTime` take one text for every buyer, or one text per language. The
buyer reads the one of the page they are on:

```ts members="ChannelConfig"
shipping: {
  DE: [
    {
      id: "standard",
      title: { de: "Standardversand (DHL)", en: "Standard (DHL)" },
      price: 495,
      deliveryTime: { de: "2-4 Werktage", en: "2-4 working days" },
    },
  ],
},
```

Your storefront names the page's language once, `createCommerce({ url, key, language: "en" })`
([Carts](/docs/shop/carts#connect-once)). OrbCart takes the exact tag, then the same language of
another region (`en-GB` reads `en`), then the first language you wrote, so write the language
of your own market first: an agent or a client that names none reads it. The language only
picks text. The methods on offer, their prices and a Quote's totals are the same in every
language, and a Quote keeps the text of the language it was made in, also when the buyer
agrees to it from a client that names another.

## Which method is selected?

The buyer's choice. Until they choose, the cheapest delivery once its country is known, never pickup; a Channel that delivers to one country knows it from the start. The Cart shows what's
on offer right now:

```ts browser
current.shippingMethods; // [{ id: "standard", ... }, { id: "express", ... }]
current.shipping; // { id: "standard" }

await cart.setShipping("express");
```

## Keep goods off a method

Mark goods in your `offers` function:

```ts members="OfferedReference"
shipping: { weightInGrams: 180, restrictions: ["lithium_battery"] },
```

Then exclude the restriction on the rule that cannot carry it:

```ts items="ShippingRuleConfig"
{ id: "express", title: "Express", price: 1290, excludes: ["lithium_battery"] },
```

Express disappears from `shippingMethods` for that Cart. `cart.changes` explains why
with a `shipping_unavailable` entry that names the method's `option`, `optionType`
and `title` with the Lines that keep it off, so you can tell the buyer; the React
checkout shows such a method disabled, with those Lines. If no method is left for
a country, the Quote fails with `not_shippable` and `problem.lines` names the
Lines to remove.

## Price by weight

Give `price` as tiers, lightest first:

```ts items="ShippingRuleConfig"
{
  id: "standard",
  title: "Standard (DHL)",
  price: [
    { upToGrams: 2000, price: 495 },
    { upToGrams: 10000, price: 695 },
    { price: 995 }, // any weight above
  ],
},
{ id: "express", title: "Express", price: [{ upToGrams: 10000, price: 1290 }] },
```

- **The weight** is every shipped unit together, from `weightInGrams` in your Offers.
- **The first tier that fits** sets the price.
- **A last tier without `upToGrams`** covers any weight. With a limit, like express above, the method
  disappears for heavier Carts and `cart.changes` says why (`reason: "too_heavy"`). Keep one method open
  for any weight, so a large order always ships.
- **An Offer without `weightInGrams`** counts as 0 g. Your logs name it as `weight_missing`.

## Bulky goods by freight

Mark the goods with a restriction such as `bulky`, keep it off the parcel methods with `excludes`, and offer
freight with `only`:

```ts items="ShippingRuleConfig"
{ id: "standard", title: "Standard (DHL)", price: 495, excludes: ["bulky"] },
{ id: "freight", title: "Freight", price: 4900, requires: ["phone"], only: ["bulky"] },
```

A Cart with a canoe gets freight alone. A pair of socks never sees it. Put `bulky` in `excludes` on every
parcel method, or the cheaper parcel is preselected for the canoe.

## Prices from your carrier or ERP

A price that depends on the postal code, the carrier's tariff or a customer's agreement comes from
your system. Give the rule `price: "quoted"` and attach `shippingRates` to the Channel:

```ts title="src/worker.ts" members="ChannelConfig"
shipping: {
  DE: [
    { id: "standard", title: "Standard (DHL)", price: 495, excludes: ["bulky"] },
    { id: "freight", title: "Freight", price: "quoted", requires: ["phone"], only: ["bulky"] },
  ],
},
shippingRates: async ({ shipTo, lines, methods, currency }, { signal }) => {
  const rates = await forwarder.rates(
    {
      postalCode: shipTo.postalCode,
      pieces: lines.reduce((sum, line) => sum + line.quantity, 0),
      grams: lines.reduce((sum, line) => sum + (line.weightInGrams ?? 0) * line.quantity, 0),
    },
    { signal },
  );

  return methods.flatMap((id) => {
    const rate = rates[id];

    return rate ? [{ id, price: { amount: rate.cents, currency }, expiresAt: rate.validUntil }] : [];
  });
},
```

You still declare the methods. Your system prices them:

- **When it is called.** For every Quote of a Cart that ships to an address, when a rule with
  `price: "quoted"` suits it. A Cart of socks never calls it.
- **What it gets.** The delivery address as far as the buyer gave it, the Lines that ship with
  their weight and restrictions, their subtotal, and the IDs of the methods to price. The
  context names the Cart and, where known, the buyer.
- **What it answers.** One price per method, in the Channel's currency, with your own
  `deliveryTime` and an `expiresAt` if you like. A method you leave out is not offered. A price in
  another currency, for a method that was not asked or given twice drops that method.
- **When it fails.** OrbCart asks once more. After that the Quote is refused as
  `provider_unavailable` and the buyer can retry. No price is guessed and no other method takes
  the place of the one the buyer chose.
- **How long it holds.** A Quote expires no later than the rate.

Before a Quote the Cart lists the method without a `price`, and the estimate says `excludes:
["shipping"]`. The Quote prices it and lists every method with its price in `shippingMethods`.
While a delivery still waits for its price, nothing is preselected beside it: the buyer chooses.
A quoted delivery without an alternative is selected at once.

`shippingRates` attaches like every contract: a function, `http()` or `service()`.
[Contracts in another system](/docs/integrate/remote-contracts)

Not yet: quoted prices for pickup, methods your carrier defines itself, and a quoted method in an
AI agent's options before the Quote.

## Goods that take longer

A rule's `deliveryTime` is the parcel's time. Goods that ship later, such as an engraving, say so with their own
`deliveryTime` in your `offers` function. The buyer sees both: the Line's time on the Line, the method's beside
the method. See [Offers](/docs/integrate/offers#say-when-goods-take-longer).

## Digital goods

Leave out `shipping` in the Offer. A Cart with only digital goods needs no
delivery address and no shipping method.

## Many countries, one price

A small helper keeps long lists readable. This is how Nordgrat ships to price zones
across the EU:

```ts
function zone(countries: string[], price: number, deliveryTime: string) {
  const standard = { id: "standard", title: "Standard (DHL)", price, deliveryTime };
  return Object.fromEntries(countries.map((country) => [country, [standard]]));
}
```

The channel then lists its own countries and spreads the zones:

```ts continues members="ChannelConfig"
shipping: {
  DE: [standard, express],
  ...zone(["BE", "NL", "LU", "DK"], 890, "3-5 business days"),
  ...zone(["FR", "IT", "ES", "SE"], 990, "4-6 business days"),
},
```

## Free shipping from €50

Use a [discount](/docs/shop/discounts) with `scope: "shipping"`. Name the methods it frees in `methods`,
so express stays paid:

```ts members="ChannelConfig"
discounts: [
  { id: "free-shipping", scope: "shipping", percentage: 100, minimumSubtotal: 5000, methods: ["standard"] },
],
```

Without a `code`, it applies automatically.

## DHL Packstation and pickup points

`@orbcart/plugin-dhl` adds a pickup finder to the React checkout, for Germany.
The buyer picks a Packstation or post office on a map, and it becomes the
delivery address:

```tsx browser
import { DhlDeliveryAddress, DhlPickupProvider } from "@orbcart/plugin-dhl/react";
import "@orbcart/plugin-dhl/styles.css";

<DhlPickupProvider enabled countries={["DE"]} searchUrl="/pickup/locations" locale="de-DE">
  <Checkout cart={cart} locale="de-DE" deliveryAddress={DhlDeliveryAddress} />
</DhlPickupProvider>;
```

Each Packstation shows a green, yellow or red dot for how much space it usually has.
The search runs on your server, at the `searchUrl` you name, with your DHL API key:

```ts title="app/routes/pickup.locations.ts"
import { env } from "cloudflare:workers";
import { PickupSearch } from "@orbcart/plugin-dhl";
import { findDhlLocations } from "@orbcart/plugin-dhl/server";

export async function action({ request }: { request: Request }) {
  // Only your own checkout may spend your DHL quota.
  if (request.headers.get("Origin") !== new URL(request.url).origin) {
    return new Response(null, { status: 403 });
  }
  const search = PickupSearch.safeParse(await request.json());
  if (!search.success) return Response.json({ error: "invalid_query" }, { status: 400 });

  const result = await findDhlLocations({
    apiKey: env.DHL_API_KEY,
    search: search.data,
    signal: request.signal,
  });
  const headers = { "Cache-Control": "private, no-store" };
  return result.status === "success"
    ? Response.json({ locations: result.locations }, { headers })
    : Response.json({ error: result.error }, { status: 503, headers });
}
```

Use DHL's API Key, not the API Secret, with a Location Finder Unified subscription. Keep
`@orbcart/plugin-dhl/server` out of browser code. `cart/plugin-dhl/README.md` lists the error
codes and what the finder does not promise yet. [How a plugin is shaped →](/docs/shop/extend#package-it-for-other-shops)

[Set up discounts →](/docs/shop/discounts)