# AI agents

Let shopping agents check out in your shop over UCP and follow their orders. The buyer agrees on your checkout, or in their agent's app with AP2.

AI agents buy through the same Carts, Quotes and Orders as your storefront. They
speak the [Universal Commerce Protocol](https://ucp.dev) (UCP). You add one
setting; OrbCart serves the protocol.

## Turn it on

Add `agents` to the one Channel that serves them:

```ts title="src/worker.ts" members="Channels"
de: {
  currency: "EUR",
  pricesIncludeTax: true,
  locale: "de-DE",
  payments: { card: "adyen", google_pay: "adyen" },
  orderPage: "https://shop.example.com/orders",
  agents: {
    continueUrl: "https://shop.example.com/checkout/continue",
  },
},
```

`orderPage` is required with `agents`: UCP links every Order to it. [The order page →](/commerce/order-page)

Agents now find your shop at `https://<your-worker>/.well-known/ucp`.

At most one Channel per environment serves agents, because the UCP profile names
one endpoint.

## How a purchase works

### The agent builds the checkout

A signed agent platform creates a checkout session, adds Lines, an address and a
shipping method. OrbCart prices everything with your `offers` function, exactly
like for your storefront.

### The buyer agrees

With the default `consent: "storefront"`, the agent sends the buyer a link to your
`continueUrl`. The buyer reviews the Quote on **your** checkout and pays there.

### You get an Order

The same Order as any other, with the same `deliverOrder` hand-off. Its
[`order.created`](/integrations/events#the-catalog) event says `journey.origin: "agent"`.

## Build the continue page

The link carries a short-lived `handoff` code. Redeem it, keep the Cart token in your
[cart cookie](/commerce#in-a-cookie) like any other, drop the code from the address and show the
checkout:

```ts title="app/routes/checkout.continue.ts" browser
import { CommerceError } from "@orbcart/client";
import { redirect } from "react-router";
import type { LoaderFunctionArgs } from "react-router";
import { cartCookie } from "../cart-cookie.server";
import { commerce } from "../commerce";

export async function loader({ request }: LoaderFunctionArgs) {
  const handoff = new URL(request.url).searchParams.get("handoff");
  if (!handoff) return redirect("/");

  try {
    const cart = await commerce.continueCheckout(handoff);
    return redirect("/checkout", {
      headers: {
        "Set-Cookie": await cartCookie.serialize(cart.token),
        "Referrer-Policy": "no-referrer", // the code never leaves in a Referer
      },
    });
  } catch (error) {
    // A link that ran out opens the shop, never an error page.
    if (error instanceof CommerceError) return redirect("/");
    throw error;
  }
}
```

Your checkout page then shows the agent's Cart, with its Lines, address and shipping, like the
buyer's own.

## Try it

With your commerce Worker running under [`orbcart dev`](/sdks/cli):

```sh title="Terminal"
curl -s http://localhost:8787/.well-known/ucp | jq '.ucp.capabilities | keys'
```

```json
[
  "dev.ucp.shopping.checkout",
  "dev.ucp.shopping.discount",
  "dev.ucp.shopping.fulfillment",
  "dev.ucp.shopping.order"
]
```

Nordgrat also lists `dev.ucp.common.payment.ap2_mandate`, because it lets buyers agree inside the
agent with [`consent: "mandate"`](#let-buyers-agree-inside-the-agent).

## Let buyers agree inside the agent

With `consent: "mandate"`, the buyer can also agree in their agent's app. The
platform proves it with the buyer's **AP2 checkout mandate** and pays with **Google Pay**:

```ts members="ChannelConfig"
agents: {
  continueUrl: "https://shop.example.com/checkout/continue",
  consent: "mandate",
  googlePay: { merchantId: "BCR2DN4T...", merchantName: "Example Shop" },
},
```

* Map `google_pay` to `adyen` in the Channel's `payments`.
* `merchantId` comes from the Google Pay & Wallet Console. In test, Google ignores it.
* OrbCart only accepts closed mandates that the buyer confirmed in person, signed within the last five minutes. It never issues mandates.

<Callout type="warn" title="Your legal call">
  Whether an order button inside an agent's app meets your legal duties, such as § 312j BGB in
  Germany, is yours to judge. `consent: "storefront"` keeps the final step on your own checkout.
</Callout>

## Order updates

The platform that started a checkout hears of its Order. It lists UCP's order
capability in its profile with a `webhook_url`; OrbCart sends the full Order to
that address when the Order is created, fulfilled or refunded. There is nothing
to configure and no code to write.

* **Always the current state.** Each update shows the Order as it is when OrbCart sends it. A platform that was away gets the latest state, not a replay of every change.
* **Signed with your keys.** The request carries an HTTP message signature (RFC 9421) made with a key from your UCP profile, which is the same key set as your `/.well-known/jwks.json`. A new signature goes out with every attempt.
* **Tried for 72 hours.** OrbCart repeats a failed update with the same `Webhook-Id`, so the platform can drop duplicates. `Webhook-Timestamp` is the time of the change and stays the same too; a replay window belongs on the signature's `created` and `expires`, which are fresh each time. A `410` answer ends updates for that Order.
* **No personal data.** The update holds Lines, quantities, totals, tracking and the withdrawal policy. It leaves out the delivery address.
* **`permalink_url`** is the buyer's link to the Order: your `orderPage` and the Order's token. It stays the same for as long as the Order exists.

A platform that gives no `webhook_url` can read its Orders instead with
`GET /ucp/orders/{id}`. Only the platform that made an Order can read it.

## Who can call

Only **signed** agent platforms. Each request carries an HTTP message signature
and a `UCP-Agent` header naming the platform's profile. OrbCart fetches that
profile, checks the signature against its keys and records the platform with the
Cart. Unsigned requests get nothing.

## Endpoints

| Method | Path                                   | What it does                            |
| ------ | -------------------------------------- | --------------------------------------- |
| `GET`  | `/.well-known/ucp`                     | Your shop's UCP profile.                |
| `POST` | `/ucp/checkout-sessions`               | Start a checkout.                       |
| `GET`  | `/ucp/checkout-sessions/{id}`          | Read it.                                |
| `PUT`  | `/ucp/checkout-sessions/{id}`          | Change Lines, address, shipping, codes. |
| `POST` | `/ucp/checkout-sessions/{id}/complete` | Pay with an AP2 mandate.                |
| `POST` | `/ucp/checkout-sessions/{id}/cancel`   | Cancel it.                              |
| `GET`  | `/ucp/orders/{id}`                     | Read an Order the platform made.        |

## Good to know

* **Same rules as your storefront.** Prices, tax, stock, discounts and shipping come from the same code. Agents can't compute anything.
* **Extensions stay with the buyer.** UCP has no field for your [extensions](/commerce/extensions). If one needs a new value, the agent hands the checkout to the buyer.
* **Canceling ends the checkout.** The answer shows it as it was, with `status: "canceled"`; after that the checkout is gone and reading it answers `404`. You get [`cart.canceled`](/integrations/events) with `reason: "discarded"`. Once a payment runs or the Order arose, a cancel answers `409 checkout_not_cancelable`.

[Test the whole flow →](/testing)