# Set up agent checkout

Add the middleware and one webhook handler, connect your store and send a test agent, so any agent's order reaches your shopper and your store gets the confirmation.

When an AI agent checks out at your store, the shopper should approve the exact order, and your store should hear that they did. This guide sets that up in four steps: add the middleware and one webhook handler, connect your store, send a test agent, and choose what a new passkey needs. The console walks the same steps at **Authorize → Set up checkout**, and each one shows done once the API has seen it.

**Before you begin:** you need a sandbox secret key (the console's setup page creates one into the snippet) and a store you can deploy code to. Setup and the test agent are free; [assessments and approvals meter as usual](https://provenanceauth.com/docs/account/plans-and-usage.md).

```bash
export PROVENANCE_API=https://sandbox-api.provenanceauth.com
export PROVENANCE_KEY=prv_test_ent_E7nT2vQ9bW4mK8sYd3cFjLh6gAe1pR5x
```

1. **The agent**: posts your checkout
2. **Your middleware**: answers with the approve link
3. **The shopper**: approves with a passkey
4. **Your webhook**: gets the confirmation

## 1. Add the middleware and the webhook handler

The middleware runs your traffic policy on every request. With `approvals: "hosted"`, an order that needs approval and carries no valid token is assessed, the approval is opened, and the agent gets one answer it can use whether or not it knows Provenance. `onApproved` verifies the webhook, re-fetches the checkout assessment and checks its cart against your own order before it calls you.

**This package isn't on npm yet. This package isn't on PyPI yet.** Until then, every request in these docs runs over HTTP against the [sandbox](https://provenanceauth.com/docs/get-started/sandbox.md).

With access to the private Provenance repository, which your Provenance contact grants, install from it:

```bash
git clone https://github.com/michaelnbane-jpg/provenance.git provenance
cd provenance && pnpm install && pnpm build
node scripts/check-publishable.mjs --out ../provenance-packs
cd ../your-project
npm install ../provenance-packs/provenanceauth-sdk-1.0.0.tgz ../provenance-packs/provenanceauth-rails-1.0.0.tgz ../provenance-packs/provenanceauth-identify-1.0.0.tgz
```

```bash
git clone https://github.com/michaelnbane-jpg/provenance.git provenance
pip install ./provenance/python/sdk ./provenance/python/identify
```

**Next.js**

```ts
// middleware.ts: agents that check out get the approve link; people never see a change.
import { Identify } from "@provenanceauth/identify";
import { identifyNext } from "@provenanceauth/identify/next";
import { orderFor } from "./lib/orders";

export const identify = new Identify({ apiKey: "prv_test_…", baseUrl: "https://api.provenanceauth.com" });
export const middleware = identifyNext(identify, { approvals: "hosted", orderFor });

// app/api/provenance/webhook/route.ts: the confirmation, checked against your own order.
import { nextWebhook } from "@provenanceauth/identify/webhooks";
import { identify } from "../../../../middleware";
import { findOrder, markApproved } from "../../../../lib/orders";

export const POST = nextWebhook(
  identify.onApproved((a) => markApproved(a.order_id, a.approval_context), { secret: "whsec_…", orderFor: findOrder }),
);
```

**Express**

```ts
// server.js: agents that check out get the approve link; people never see a change.
import express from "express";
import { Identify } from "@provenanceauth/identify";
import { identifyExpress } from "@provenanceauth/identify/express";
import { expressWebhook } from "@provenanceauth/identify/webhooks";
import { orderFor, findOrder, markApproved } from "./orders.js";

const identify = new Identify({ apiKey: "prv_test_…", baseUrl: "https://api.provenanceauth.com" });
const app = express();
app.post(
  "/api/provenance/webhook",
  express.raw({ type: "application/json" }),
  expressWebhook(identify.onApproved((a) => markApproved(a.order_id, a.approval_context), { secret: "whsec_…", orderFor: findOrder })),
);
app.use(identifyExpress(identify, { approvals: "hosted", orderFor }));
```

**FastAPI**

```python
# main.py: agents that check out get the approve link; people never see a change.
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from provenanceauth_identify import Identify
from provenanceauth_identify.asgi import IdentifyMiddleware
from provenanceauth_identify.webhooks import CheckoutWebhook
from orders import order_for, find_order, mark_approved

identify = Identify("prv_test_…", base_url="https://api.provenanceauth.com")
app = FastAPI()
app.add_middleware(IdentifyMiddleware, identify=identify, approvals="hosted", order_for=order_for)
webhook = CheckoutWebhook(identify, secret="whsec_…", order_for=find_order,
                          on_approved=lambda a: mark_approved(a["order_id"], a["approval_context"]))

@app.post("/api/provenance/webhook")
async def provenance_webhook(request: Request):
    status, body = webhook.handle(await request.body(), request.headers.get("provenance-signature"))
    return JSONResponse(body, status_code=status)
```

`orderFor` returns the order for the request: the same order id, total, currency, merchant id and origin you charge. Build it from your own cart, never from the request body. `findOrder` returns the same order by its id, for the webhook.

The checkout rule the setup page applies (the `agent_checkout_approval` traffic policy template) asks the shopper whenever anything other than a person in a browser places an order. Edit it in **Rules → Traffic**.

## 2. Connect your store

Register your webhook endpoint for `authorize.checkout_assessment.updated`: the checkout assessment is your one object for the order, updated once the shopper decides. The setup page does this when you paste your store's URL, and puts the signing secret into the snippet.

**curl**

```bash
curl -s -X POST $PROVENANCE_API/v1/webhook_endpoints \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://brightbox.example/api/provenance/webhook",
    "event_types": ["authorize.checkout_assessment.updated"]
  }'
```

**Node**

```ts
const endpoint = await (await fetch(`${process.env.PROVENANCE_API}/v1/webhook_endpoints`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://brightbox.example/api/provenance/webhook",
    event_types: ["authorize.checkout_assessment.updated"],
  }),
})).json();
```

**Python**

```python
endpoint = httpx.post(
    f"{os.environ['PROVENANCE_API']}/v1/webhook_endpoints",
    headers={"Authorization": f"Bearer {os.environ['PROVENANCE_KEY']}"},
    json={
        "url": "https://brightbox.example/api/provenance/webhook",
        "event_types": ["authorize.checkout_assessment.updated"],
    },
).json()
```

```json
{
  "object": "webhook_endpoint",
  "url": "https://brightbox.example/api/provenance/webhook"
}
```

`onApproved` gets `{ order_id, checkout_assessment_id, approval_context, approved_at, assessment }`, where `approval_context` is how the person approved ([approval context](https://provenanceauth.com/docs/concepts/approval-context.md)). An assessment whose cart isn't your order (`binding_mismatch`) or an order you don't know goes to `onRejected` instead; a rejected assessment, or a challenge nobody answered in time, goes to `onDeclined`. An order your review holds is acknowledged and waits.

## 3. Send a test agent

Muse is a test agent with no Provenance support. It opens your store, adds to cart, posts your checkout, reads the 401's `message` and relays `approve_url`. You approve, and Muse retries with the token. Run it from the setup page (it can text the link to your phone), with [`POST /v1/authorize/setup/test_agent`](https://provenanceauth.com/docs/api/checkout-setup.md#post-v1-authorize-setup-test-agent), or locally with `node examples/agents/muse/muse.mjs https://your-store.example/`.

Each step reads from what the API has seen:

**curl**

```bash
curl -s $PROVENANCE_API/v1/authorize/setup \
  -H "Authorization: Bearer $PROVENANCE_KEY"
```

**Node**

```ts
const setup = await (await fetch(`${process.env.PROVENANCE_API}/v1/authorize/setup`, {
  headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}` },
})).json();
```

**Python**

```python
setup = httpx.get(f"{os.environ['PROVENANCE_API']}/v1/authorize/setup", headers={"Authorization": f"Bearer {os.environ['PROVENANCE_KEY']}"}).json()
```

```json
{
  "object": "authorize_setup",
  "key_created": true
}
```

Test agents run with sandbox keys only, at most 5 an hour, and only against an https store URL that resolves to a public address.

### What the agent gets back

An agent that speaks Provenance reads `WWW-Authenticate: ProvenanceIntent`. Every other agent reads the body:

```json
{
  "type": "https://provenanceauth.com/problems/approval-required",
  "title": "Approval required",
  "status": 401,
  "message": "Ask the person you're shopping for to approve this order: https://app.provenanceauth.com/approve/c/Hq2vN8xK4tB7mW3sYd9cFj. Then retry this request.",
  "approve_url": "https://app.provenanceauth.com/approve/c/Hq2vN8xK4tB7mW3sYd9cFj",
  "status_url": "https://api.provenanceauth.com/v1/authorize/checkout_approvals/requests/Hq2vN8xK4tB7mW3sYd9cFj/status",
  "retry_url": "https://brightbox.example/checkout/place",
  "expires_at": "2026-11-06T18:18:10.000Z"
}
```

A browser agent (`Accept: text/html`) gets a page with the same words and the [checkout approval component](https://provenanceauth.com/docs/embeds.md#checkout-approval), which shows a QR code to a person at a desktop. When `customerFor` returns your signed-in customer's phone or email, we send them the link and the message says so ("We've sent the approval to the phone ending 42"). A cart the shopper already approved goes through with no prompt ([ask once](https://provenanceauth.com/docs/authorize/guides/ask-once.md)).

When the API can't be reached, `onUnavailable` decides: `"protocol"` (the default) answers the `ProvenanceIntent` 401, `"block"` answers 503. The order never goes through without an approval.

## 4. Choose what a new passkey needs

A passkey younger than `min_passkey_age` (24 hours by default), or one set up during this approval, is new. Choose what it needs in your checkout rules, per approval with `require`, or in the middleware with `newPasskey`:

| `new_passkey` | What happens |
| --- | --- |
| `step_up_contact` (default) | The person also types a 6-digit code we send to the customer contact you passed. With no contact (the agent relay), `no_contact` decides: `accept` (default) or `decline`. |
| `accept` | The approval counts, and `approval_context.passkey.status` says the passkey is `new`. |
| `require_existing` | The approval is declined with `decline_reason: "passkey_too_new"`, which the agent reads from `status_url`. |

**curl**

```bash
curl -s -X PUT $PROVENANCE_API/v1/authorize/policies \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "document": { "rules": [], "passkeys": { "new_passkey": "step_up_contact", "min_passkey_age": 86400 } } }'
```

**Node**

```ts
await fetch(`${process.env.PROVENANCE_API}/v1/authorize/policies`, {
  method: "PUT",
  headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ document: { rules: [], passkeys: { new_passkey: "step_up_contact", min_passkey_age: 86400 } } }),
});
```

**Python**

```python
httpx.put(
    f"{os.environ['PROVENANCE_API']}/v1/authorize/policies",
    headers={"Authorization": f"Bearer {os.environ['PROVENANCE_KEY']}"},
    json={"document": {"rules": [], "passkeys": {"new_passkey": "step_up_contact", "min_passkey_age": 86400}}},
)
```

```json
{
  "object": "policy_version",
  "active": true
}
```

Every approval reports the [passkey facts](https://provenanceauth.com/docs/authorize/concepts/approval-signals.md#passkey) whatever you choose, so your own rules can decide too.

## Errors you might see

| Error | What it means |
| --- | --- |
| [`parameter_invalid`](https://provenanceauth.com/docs/platform/errors.md#parameter_invalid) | A test agent's `store_url` isn't https or resolves to a private address, or a step-up code doesn't match (the message says how many tries are left). |
| [`rate_limit_exceeded`](https://provenanceauth.com/docs/platform/errors.md#rate_limit_exceeded) | More than 5 test agent runs in an hour. |
| [`approval_already_decided`](https://provenanceauth.com/docs/platform/errors.md#approval_already_decided) | The approval was decided before the code was entered. |

## See also

- [Assess an agent checkout](https://provenanceauth.com/docs/authorize/guides/assess-checkouts.md)
- [Ask your own customer](https://provenanceauth.com/docs/authorize/guides/ask-your-own-customer.md)
- [Approval signals](https://provenanceauth.com/docs/authorize/concepts/approval-signals.md)
- [Middleware options](https://provenanceauth.com/docs/identify/guides/verify-signed-agents.md#middleware-options)
