Here's a checkout endpoint that works fine for your own storefront:

place-order.ts

app.post("/api/orders", async (req, res) => { const cart = await carts.load(req.session.cartId); const order = await orders.createFromCart(cart); await payments.charge(order.total, req.body.paymentMethodId); res.json({ orderId: order.id }); }); 

It passes every test you have. Now put an AI agent in front of it. The agent sends the request, your PSP takes four seconds, the agent's HTTP client gives up at three and retries. You now have two orders and two charges. The agent reads the second response, tells the buyer "done," and never mentions the first one. Nobody did anything wrong from their own point of view. The endpoint just assumed its caller was a browser tab with a human watching a spinner.

That's the whole problem in miniature. An agent is a client that retries aggressively, holds no session cookie, can't see your page, reads every field you return literally, and acts on behalf of someone who isn't there. The protocols that have appeared for agent checkout, OpenAI and Stripe's Agentic Commerce Protocol (ACP) and Google and Shopify's Universal Commerce Protocol (UCP), look different on the surface. Underneath, they're asking your backend for the same five things. This article is about building those five things once, in your own domain, so that the protocols become thin adapters instead of rewrites.

If you want the protocol history (who released what and when, how MCP, ACP and UCP stack), I covered that in Adobe Commerce Added an MCP Layer, along with stale prices and prompt injection through product copy. I won't repeat it. This one stays below the protocol line.

First, a reality check on "agents now buy things"

The pitch you'll hear is that autonomous shopping agents already discover, compare and purchase, and the backend that "wins" is the one they can use. Parts of that are true. The part that's overstated is how finished the ground under it is.

Look at the status labels in the ACP repository itself. The README marks the protocol as beta. The Agentic Checkout RFC is labelled Draft. The Product Feeds RFC is a Proposal with version "unreleased." The spec has shipped dated versions (2025-09-29, 2025-12-12, 2026-01-16, 2026-01-30, 2026-04-17), and some of those carried breaking changes: the 2025-12-12 release renamed fulfillment_address to fulfillment_details and replaced a single fulfillment_option_id with a selected_fulfillment_options[] array. UCP, meanwhile, uses a different status vocabulary for the same lifecycle.

So I'd put it differently from the hype. The protocol details will keep moving for a while. What's already stable is the shape they all require from the merchant, and that shape is good backend design anyway. If you build it into your domain model, adopting ACP this quarter and UCP next quarter is adapter work. If you bolt ACP straight onto your existing cart controller, you'll rewrite it the next time the spec renames a field.

Here's the shape:

  1. A stable, purchasable item ID that discovery and checkout both agree on.
  2. A checkout session resource that returns the full authoritative state on every call.
  3. Strict idempotency on every write, with defined replay and conflict behaviour.
  4. Payment by scoped token, never by raw card or stored-card reference passed through the model.
  5. Explicit identities for the platform, the agent and the buyer, each authenticated differently.

Let's go through them in the order an agent hits them.

Product data: the variant ID is the whole game

Everyone talks about "machine-readable product data" as if the hard part is the richness of descriptions. It isn't. The hard part is that the ID an agent finds during discovery must be exactly the ID your checkout accepts.

The ACP Product Feeds proposal says this plainly. It splits a Product (the grouping concept) from a Variant (the thing you can actually buy), and requires that "Variant IDs SHOULD be stable across feed updates." If your catalog ID and checkout item ID differ, the merchant "MUST provide a deterministic mapping outside this RFC or ensure the feed Variant.id is accepted as an ACP checkout item ID."

Think about what that means for a typical platform. Magento has a configurable parent SKU and child simple SKUs. Shopify has products and variant GIDs. Plenty of custom backends use a product ID plus a bag of selected options that only become a concrete stock unit inside the cart service. That last design is the one that hurts: an agent can't pass "product 812 with color=red and size=M" to a checkout that expects a line item ID, unless you give it one.

A feed entry in the ACP proposal's shape looks like this. Note that prices are integers in minor units, and the variant ID is the checkout key:

feed-product.json

{ "id": "prod_classic_tee", "title": "Classic Tee", "url": "https://merchant.example/products/classic-tee", "variants": [ { "id": "sku124-red-m", "title": "Classic Tee - Red / Medium", "price": { "amount": 1999, "currency": "USD" }, "availability": { "available": true, "status": "in_stock" }, "variant_options": [ { "name": "Color", "value": "Red" }, { "name": "Size", "value": "Medium" } ] } ] } 

Two things about feeds catch people off guard.

The feed is push, not pull. In the ACP proposal, the Feed API is hosted by the agent platform and the merchant calls it: POST /feeds, PATCH /feeds/{id}/products for partial upserts, or a full-replacement file drop of metadata.json plus a products.jsonl. The spec is explicit that "Agents MUST NOT call Product Feed API endpoints on merchants." So "exposing" your catalog is really an outbound sync job with its own retry, backoff and change-detection, not an endpoint you open. Plan it like you'd plan a search-index sync, because that's what it is.

The feed is never authoritative. The same proposal lists "authoritative checkout pricing" as a non-goal: feed prices are "discovery-time signals," and agents "MUST NOT represent feed price or availability as guaranteed." Availability in a feed doesn't reserve inventory either. That's a relief, honestly. It means the feed can lag a bit, as long as your checkout tells the truth and says so loudly when the truth differs.

OpenAI's own product feed spec for ChatGPT names nine required fields: item_id, title, description, url, brand, seller_name, image_url, availability and price, and it accepts JSONL, TSV/CSV and gzipped variants. It also has per-row switches, is_eligible_search and is_eligible_checkout, so you can let an item be found without letting it be bought through the agent. Use that switch. Made-to-order items, age-restricted products and anything with a configurator probably belong in "searchable, not agent-checkoutable" on day one.

Don't forget the page itself

Not every agent uses a feed. Some read your product page like a crawler does, which is why schema.org markup still matters. Google's merchant listing docs require only name, image and offers on the Product, and price (greater than zero) plus priceCurrency on the Offer. The useful stuff for an agent sits in the recommended set: gtin, availability, itemCondition, shippingDetails, hasMerchantReturnPolicy.

product-jsonld.json

{ "@context": "https://schema.org", "@type": "Product", "name": "Classic Tee - Red / Medium", "sku": "sku124-red-m", "gtin13": "0123456789012", "image": ["https://cdn.merchant.example/products/classic-tee/main.jpg"], "offers": { "@type": "Offer", "price": "19.99", "priceCurrency": "USD", "availability": "https://schema.org/InStock", "itemCondition": "https://schema.org/NewCondition" } } 

Put the same variant ID in sku that your feed and checkout use. One ID, three surfaces.

Warning
Google's docs note that dynamically generated markup "can make Shopping crawls less frequent and less reliable, which can be an issue for fast-changing content like product availability and price." If your JSON-LD is injected client-side by a headless storefront, render it on the server. The same logic applies to any agent that fetches HTML without running your JavaScript.

The checkout session is a state machine, not an endpoint

The single biggest structural change is this: agents don't "place an order." They drive a checkout session through a lifecycle, and every call returns the whole current state.

ACP defines five operations:

  • POST /checkout_sessions to create (returns 201)
  • POST /checkout_sessions/{id} to update items, fulfillment details or selected shipping
  • GET /checkout_sessions/{id} to retrieve
  • POST /checkout_sessions/{id}/complete to pay, which "MUST create an order"
  • POST /checkout_sessions/{id}/cancel, which returns 405 if the session is already completed or canceled

UCP's checkout capability (dev.ucp.shopping.checkout) has the same five logical operations with different status names. Put them side by side and you can see the common model:

Meaning ACP status UCP status
Missing info or unresolved issues not_ready_for_payment incomplete
Needs the human, outside the API (messages with requires_buyer_input / requires_buyer_review) requires_escalation + continue_url
Can be paid ready_for_payment ready_for_complete
Payment/issuer step in flight authentication_required complete_in_progress
Done completed completed
Dead canceled canceled

My strong opinion: model this table in your domain, with your own status names, and map to each protocol at the edge. Don't store ready_for_payment in your database because ACP happens to say it. The next protocol will say something else.

A few rules fall out of the specs that are worth baking in from the start.

Every response is the full, authoritative state. ACP's first stated goal is that the agent "renders an authoritative cart state on every response." Line items carry base_amount, discount, subtotal, tax and total; the session carries totals[], fulfillment_options[], messages[] and policy links[]. There's no "OK, call GET to see what happened." That rules out the common pattern where an update endpoint returns 204 and the frontend refetches.

Money is integers in minor units. ACP: "Amounts MUST be integers in minor units." $19.99 is 1999. If any part of your pricing pipeline still does float math and rounds at the end, the agent will see the result of that rounding in a field it treats as exact.

Errors tell the agent who can fix them. Since the 2026-02-04 change, ACP messages can carry a resolution of recoverable (the agent can fix it via the API), requires_buyer_input or requires_buyer_review. That field is small and does a lot of work. An out-of-stock line is recoverable if you offer a substitute variant. A missing age confirmation is requires_buyer_review, and the agent should stop and ask instead of guessing. UCP makes the same split with a status: requires_escalation, where the business "MUST provide continue_url" so the human can finish in your UI.

Sessions expire. UCP's expires_at defaults to six hours from creation if the platform doesn't send one. Pick your own TTL deliberately, and tie any soft inventory hold to it. Remember the feed never reserved anything; if you reserve at all, the session is where it happens.

Architecture diagram of one domain checkout session state machine (incomplete, payable, paying, completed, needs human, canceled) with an ACP adapter and a UCP adapter mapping protocol statuses onto it, fed by a variant ID feed, an idempotency store and a scoped payment token

Update semantics: the protocols disagree, so your domain shouldn't care

Here's a gotcha that will bite anyone who writes one update handler for both protocols.

ACP's checkout update is a partial update with a precise rule about null: in its idempotency section, "null value vs absent key" are "Different: null means 'clear this field'; absent means 'do not modify'." The spec even tells SDK authors to make sure their serializers preserve that distinction.

UCP's Update Checkout is a full replacement: the platform must "send the entire checkout resource," and it "will replace the existing checkout session state on the business side."

And ACP's newer cart capability (POST /carts, PUT /carts/{id}) is full replacement too: "The agent MUST send the complete desired cart state." Cart totals there are explicitly estimates, and carts have no payment data at all.

So you have three write semantics for what is conceptually one basket. The fix is boring: your domain exposes intent-level commands (setLines, setAddress, selectShipping, clearAddress), and each adapter translates its protocol's semantics into those commands. A JSON merge in the controller layer is how you end up with an agent that accidentally wipes an address by sending null, or wipes a line item by omitting it.

The ACP cart RFC is candid about the next problem: full replacement without concurrency control means two writers can race. It says "future protocol versions MAY introduce optimistic concurrency (e.g., If-Match / ETag)." You don't have to wait. Keep a version column on the session and reject stale writes internally, even if the protocol doesn't carry the version yet.

Idempotency is the product, not a middleware afterthought

Back to the opener: the duplicate order. For a long time this was "recommended." In ACP's 2026-04-17 release it became mandatory. The changelog entry changed the Idempotency-Key parameter "from required: false to required: true on both Agentic Checkout and Delegate Payment APIs." The rules it now spells out are worth reading line by line, because each one maps to a design decision.

  • Every POST needs a key. Missing key: 400 with code idempotency_key_required. Keys are opaque strings up to 255 characters, UUID v4 recommended.
  • Scope is identity plus path. Servers "MUST scope keys to the authenticated identity + endpoint path." The same key on /complete and on /cancel are different keys.
  • Equivalence is semantic JSON equality of the body. Key order doesn't matter, 1.0 equals 1, but array order does, and null differs from absent. Headers are excluded. The spec suggests RFC 8785 (JSON Canonicalization Scheme) plus SHA-256 as an implementation.
  • Same key, same body: replay. Return "the original response with the same HTTP status code," ideally with Idempotent-Replayed: true, and never re-run side effects like payment capture or inventory reservation.
  • Same key, different body: 422 with idempotency_conflict. Permanent, don't retry.
  • Same key, still running: 409 with idempotency_in_flight and a Retry-After header.
  • 5xx responses are never cached. A retry after a 5xx "MUST be processed as a fresh request."
  • Keep keys at least 24 hours.

The 400/422/409 split tracks the IETF Idempotency-Key header draft, which recommends the same three codes. That draft never became an RFC (its last revision, -07, is from October 2025), so the ACP text is currently the more complete normative source.

Now the surprising part. Compare that 5xx rule with Stripe, the company that co-maintains ACP. Stripe's API docs say its idempotency layer saves "the resulting status code and body of the first request made for any given idempotency key, regardless of whether it succeeds or fails. Subsequent requests with the same key return the same result, including 500 errors." Opposite behaviour, same header name.

Neither is wrong. Stripe is protecting a single money movement where "the first attempt failed" is itself a durable fact; ACP is protecting an agent that needs a retry to actually retry. The lesson for you is that "we support Idempotency-Key" means nothing until you've written down which of these you do, and your checkout sits between both: ACP semantics on the way in, Stripe semantics on the way out.

I walked through the general version of this store in Idempotency Keys: The One-Line Fix That Saves You From Duplicate Side Effects. Here it is again with ACP's rules on Postgres. The key design choice is committing the idempotency record and the business write in the same transaction, which ACP's implementation guidance recommends to avoid "ghost keys (key stored, operation failed) or lost keys (operation succeeded, key not stored)."

idempotency_keys.sql

CREATE TABLE idempotency_keys ( caller_id text NOT NULL, -- authenticated platform identity path text NOT NULL, -- e.g. /checkout_sessions/{id}/complete key text NOT NULL CHECK (length(key) <= 255), request_hash bytea NOT NULL, -- sha256 of RFC 8785 canonical body status text NOT NULL DEFAULT 'in_flight', -- in_flight | done http_status int, response_body jsonb, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (caller_id, path, key) ); -- Retention floor is 24h; sweep anything older. CREATE INDEX idempotency_keys_created_at ON idempotency_keys (created_at); 

idempotent.ts

import { createHash } from "node:crypto"; import canonicalize from "canonicalize"; import type { Pool, PoolClient } from "pg"; type Result = { status: number; body: unknown; replayed?: boolean }; export async function idempotent( pool: Pool, scope: { callerId: string; path: string; key: string | undefined }, body: unknown, handler: (tx: PoolClient) => Promise<Result>, ): Promise<Result> { if (!scope.key) { return { status: 400, body: { type: "invalid_request", code: "idempotency_key_required", message: "Idempotency-Key header is required on all POST requests" } }; } const hash = createHash("sha256").update(canonicalize(body) ?? "").digest(); // Claim the key in its own short transaction so concurrent retries see "in_flight". const claim = await pool.query( `INSERT INTO idempotency_keys (caller_id, path, key, request_hash) VALUES ($1, $2, $3, $4) ON CONFLICT (caller_id, path, key) DO NOTHING RETURNING key`, [scope.callerId, scope.path, scope.key, hash], ); if (claim.rowCount === 0) { const { rows } = await pool.query( `SELECT request_hash, status, http_status, response_body FROM idempotency_keys WHERE caller_id = $1 AND path = $2 AND key = $3`, [scope.callerId, scope.path, scope.key], ); const prev = rows[0]; if (!Buffer.from(prev.request_hash).equals(hash)) { return { status: 422, body: { type: "invalid_request", code: "idempotency_conflict", message: "Idempotency-Key has already been used with a different request body" } }; } if (prev.status === "in_flight") { return { status: 409, body: { type: "invalid_request", code: "idempotency_in_flight", message: "A request with this Idempotency-Key is currently being processed" } }; } return { status: prev.http_status, body: prev.response_body, replayed: true }; } const tx = await pool.connect(); try { await tx.query("BEGIN"); const result = await handler(tx); // business writes use the same tx if (result.status >= 500) { await tx.query("ROLLBACK"); await pool.query(`DELETE FROM idempotency_keys WHERE caller_id=$1 AND path=$2 AND key=$3`, [scope.callerId, scope.path, scope.key]); // 5xx must not be cached return result; } await tx.query( `UPDATE idempotency_keys SET status='done', http_status=$4, response_body=$5 WHERE caller_id=$1 AND path=$2 AND key=$3`, [scope.callerId, scope.path, scope.key, result.status, JSON.stringify(result.body)], ); await tx.query("COMMIT"); return result; } catch (err) { await tx.query("ROLLBACK"); await pool.query(`DELETE FROM idempotency_keys WHERE caller_id=$1 AND path=$2 AND key=$3`, [scope.callerId, scope.path, scope.key]); throw err; } finally { tx.release(); } } 

The caller adds the Idempotency-Key echo, Idempotent-Replayed: true on replays and a Retry-After on 409. Why RFC 8785 instead of JSON.stringify? Because JSON.stringify preserves key insertion order, so two semantically identical bodies from different agent SDKs would hash differently and you'd throw a 422 at an honest retry. JCS sorts keys and normalizes numbers, which is exactly the equivalence ACP asks for, while keeping null and absent keys distinct.

The part this code doesn't solve: your PSP call

Look at handler(tx). If it calls your payment provider, that call is outside your database transaction. Rolling back the SQL doesn't roll back an authorization at the PSP. ACP names this directly: when an operation "triggers foreign state mutations (e.g., PSP authorization), servers SHOULD implement recovery-point semantics," recording intermediate state so retries "can resume rather than restart."

In practice: persist "payment attempt started, PSP idempotency key = X" and commit it before calling the PSP, then call the PSP with that derived key. A retry that finds the recovery point reuses the same PSP key, and the PSP's own idempotency (the Stripe behaviour above, which caches even failures) guarantees you don't charge twice. Two idempotency layers with different semantics, stacked on purpose.

Note
One inconsistency to watch: ACP's MCP transport binding (docs/mcp-binding.md in the spec repo) still lists meta.idempotency_key as not required, "Recommended for create and complete," and still lists the request_not_idempotent error type that the REST spec removed. If you expose checkout over MCP (tools named create_checkout_session, complete_checkout_session and so on), enforce the REST rules anyway. Your database doesn't care which transport the retry came through.

Sequence diagram of an agent retrying POST /complete with the same Idempotency-Key: the first call times out, the retry gets 409 idempotency_in_flight, the PSP charges once using a derived key, and the third attempt gets 200 with Idempotent-Replayed: true

Payment: accept a scoped token, and freeze the total before it's issued

The agent never hands you a card number through the model. In ACP, the buyer's payment credential goes to a delegated-payment endpoint (POST /agentic_commerce/delegate_payment, implemented by the PSP), which returns a token usable only within an Allowance: reason must be one_time, plus a max_amount in minor units, a currency, the checkout_session_id, the merchant_id and an expires_at. The token "MUST become invalid at or after allowance.expires_at." Your /complete call receives it in payment_data.instrument.credential, for example as { "type": "spt", "token": "spt_123" }.

On Stripe the concrete version is a Shared Payment Token. Stripe's seller docs say the agent grants it with usage_limits (currency, max_amount, expires_at), and, importantly, "the agent sets the maximum amount to match the total amount of the transaction."

Read that sentence again with your tax engine in mind. The token's ceiling is whatever total your session showed the buyer. If your /complete handler recalculates tax, re-rates shipping or re-applies a promotion and lands one cent higher, the charge exceeds the grant. The buyer approved one number; you're trying to charge another. That isn't a bug in the protocol. It's the protocol working as designed, and it forces a rule on your backend: the total is frozen at ready_for_payment and /complete charges exactly that frozen total or refuses. If something genuinely changed (a price moved, stock ran out), send the session back to a not-payable state with a message, and let the agent get a new approval.

Here's what a complete handler looks like against Stripe's documented REST endpoints, using plain fetch so nothing depends on a preview SDK type:

complete-checkout.ts

const STRIPE = "https://api.stripe.com/v1"; const auth = { Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}` }; export async function completeCheckout(session: CheckoutSession, sptId: string) { if (session.status !== "payable") { return { status: 400, body: { type: "invalid_request", code: "invalid", message: "Session is not ready for payment" } }; } // 1. Check the grant against the total we froze when the session became payable. const grant = await fetch(`${STRIPE}/shared_payment/granted_tokens/${sptId}`, { headers: { ...auth, "Stripe-Version": "2026-04-22.preview" }, }).then((r) => r.json()); if (grant.deactivated_at || grant.usage_limits.max_amount < session.frozenTotalMinor || grant.Source:https://dev.to/andriiboyko/structuring-your-commerce-backend-so-an-ai-agent-can-actually-check-out-504e

Related posts