> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentcard.com/llms.txt
> Use this file to discover all available pages before exploring further.

# opencommerce SDK quickstart

> Run agent-cards init to create your account and install the opencommerce SDK: give your agent the buy tool, store cards and make payments online.

One integration buys from 5,026 online stores, from Amazon, Walmart, Target and DoorDash: you integrate once instead of once per store. Agentcard takes 1% of each completed order. More on coverage and pricing in the [opencommerce FAQ](https://opencommerce.sh/faq?utm_source=docs\&utm_medium=docs\&utm_campaign=opencommerce).

Give your agent one tool that buys for your shoppers at real stores. The shopper tells your agent what they want, Agentcard finds it and builds the cart, and Agentcard places the order once the shopper approves it. Your server hears about each step, so your agent can tell the shopper in its own voice.

This page starts with the one command that sets everything up, then takes you to a sandbox run and live purchases. The code comes down to four things: one client, one tool for each shopper, one turn for each message, and one place to hear from Agentcard.

What you end up with: a shopper texts your agent "two packs of AA batteries from Amazon", sees product cards, picks one, adds a card with a link, approves the payment with a passkey, and reads "order placed" in the same chat, with nothing else to type.

> [!NOTE]
>
> The SDK is TypeScript. If your agent runs in another language or another framework, the same purchase flow is one endpoint over plain HTTP: see [Buy over HTTP](https://docs.agentcard.com/purchase-api/http.md).

## Install the SDK

Run `init` in your app's folder:

```bash theme={null}
npx agent-cards init
```

> [!NOTE]
>
> `init` is the only way to create an Agentcard account. The website and the dashboard can't create one. `init` also replaces the manual setup, so you don't run `npm install` or copy credentials from the dashboard.

[`init`](https://docs.agentcard.com/tools/cli/init) asks which stores your agent buys from, then, after one yes, does the rest:

* signs you in, or creates your Agentcard account and your company in the browser,
* installs the SDK,
* puts your production credentials in your env file, kept out of git,
* has Agentcard's agent build the buy tool into your code, and ends with the command that starts your app.

In an empty folder, `init` first sets up Agentcard's [example app](https://github.com/tiny-agent-company/commerce-sdk-example), a terminal chat that buys, so you have a working agent to try.

`init` needs Node 22 or later. The SDK it installs runs on Node 18 or later and has no dependencies. To use your own coding agent instead of Agentcard's, run `npx agent-cards init --print`, and the CLI prints the instructions for it.

The rest of this page explains what `init` builds, so you can read and change it.

## Give your agent the buy tool

Build one `AgentcardClient` when your server starts and keep it. Build one buy tool for each shopper, name the shopper by your own id for them, and keep that tool too. Open one turn for each message the shopper sends, and give the turn to your model in place of the tool.

```ts agentcard.ts theme={null}
import { AgentcardClient, buyTool, type BuyTool } from '@agent-cards/commerce-sdk';

// One client for the whole server: every shopper's tool shares its access token.
export const agentcard = new AgentcardClient({
  clientId: process.env.AGENTCARD_CLIENT_ID ?? '',
  clientSecret: process.env.AGENTCARD_CLIENT_SECRET ?? '',
});

const tools = new Map<string, BuyTool>();

/** The buy tool for one shopper, built on the first message and kept for the rest. */
export function buyFor(shopperId: string): BuyTool {
  let buy = tools.get(shopperId);
  if (!buy) {
    buy = buyTool({ agentcard, externalUserId: shopperId }); // your own id for the shopper
    tools.set(shopperId, buy);
  }
  return buy;
}
```

Give each shopper their own `externalUserId`. Agentcard refuses a call when two of your shoppers share one id.

A shopper can write to your agent in several chats at once when your app has group chats or threads. In such an app, build one tool per shopper and chat, and name the chat with `threadId`, your own id for it:

```ts agentcard.ts theme={null}
const chatTools = new Map<string, BuyTool>();

/** The buy tool for one shopper in one chat, for an app with group chats or threads. */
export function buyInChat(shopperId: string, chatId: string): BuyTool {
  const key = JSON.stringify([shopperId, chatId]);
  let buy = chatTools.get(key);
  if (!buy) {
    buy = buyTool({ agentcard, externalUserId: shopperId, threadId: chatId }); // your own id for the chat
    chatTools.set(key, buy);
  }
  return buy;
}
```

Agentcard then keeps a purchase per chat. A cart, a question or an approval link from one chat never shows up in another, and the shopper keeps one Vault card, one store sign-in and one address book across all of them. [Keep a purchase per chat](https://docs.agentcard.com/api-reference/commerce-sdk/buy-tool.md#keep-a-purchase-per-chat) covers the rest.

Each turn needs a way to deliver links to the shopper. Pass `sendLink`, and the turn hands it every Vault, approval, store sign-in, product, and store link, so your model never reads or writes one. "Send each link" shows how to render each kind.

The tab for your model API shows the same turn in each shape. Pick the one your agent already uses.

> [tab] Anthropic
>
> ```ts chat.ts theme={null}
> import Anthropic from '@anthropic-ai/sdk';
> import { buyFor } from './agentcard';
>
> const anthropic = new Anthropic();
> const histories = new Map<string, any[]>(); // each shopper's earlier messages
>
> export async function answer(shopperId: string, message: string) {
>   const turn = buyFor(shopperId).turn(message, {
>     sendLink: (link) => deliverLink(shopperId, link), // your code
>   });
>   const runner = anthropic.beta.messages.toolRunner({
>     model: 'claude-opus-5-5',
>     max_tokens: 16000,
>     tools: [turn],
>     messages: turn.messages(histories.get(shopperId)),
>   });
>   const final = await runner;
>   histories.set(shopperId, runner.params.messages); // the next turn starts from here
>   return final;
> }
> ```

> [tab] Vercel AI SDK
>
> ```ts chat.ts theme={null}
> import { generateText, isStepCount } from 'ai';
> import { buyFor } from './agentcard';
>
> const histories = new Map<string, any[]>(); // each shopper's earlier messages
>
> export async function answer(shopperId: string, message: string) {
>   const turn = buyFor(shopperId).turn(message, {
>     sendLink: (link) => deliverLink(shopperId, link), // your code
>   });
>   const messages = turn.messages(histories.get(shopperId));
>   const result = await generateText({
>     model: yourModel, // the model you already use
>     tools: { buy: turn },
>     stopWhen: isStepCount(10), // lets the model read the tool's answer and reply
>     messages,
>   });
>   histories.set(shopperId, [...messages, ...result.responseMessages]); // the next turn starts from here
>   return result;
> }
> ```

> [tab] OpenAI or OpenRouter
>
> ```ts chat.ts theme={null}
> import OpenAI from 'openai';
> import { buyFor } from './agentcard';
>
> const openrouter = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', apiKey: process.env.OPENROUTER_API_KEY });
> const histories = new Map<string, OpenAI.ChatCompletionMessageParam[]>(); // each shopper's earlier messages
>
> export async function answer(shopperId: string, message: string) {
>   const turn = buyFor(shopperId).turn(message, {
>     sendLink: (link) => deliverLink(shopperId, link), // your code
>   });
>   const messages = turn.messages(histories.get(shopperId)) as OpenAI.ChatCompletionMessageParam[];
>   const send = async () =>
>     (await openrouter.chat.completions.create({ model: 'anthropic/claude-opus-5.5', messages, tools: [turn.openai] })).choices[0].message;
>
>   let reply = await send();
>   while (reply.tool_calls?.length) {
>     messages.push(reply);
>     for (const call of reply.tool_calls) {
>       if (call.type !== 'function') continue;
>       // turn.handle returns the JSON the model reads, with every link taken out.
>       const content = await turn.handle(call.function.arguments).catch((error) => error.message);
>       messages.push({ role: 'tool', tool_call_id: call.id, content });
>     }
>     reply = await send();
>   }
>   histories.set(shopperId, [...messages, reply]); // the next turn starts from here
>   return reply.content; // the model's answer for the shopper
> }
> ```

`deliverLink` and `yourModel` stand for your own code. The model calls `buy` with the shopper's words, shows the shopper the cart, and confirms the cart only after the shopper says yes. OpenRouter's agent SDK takes the tool through `toOpenRouterTool(turn, { tool, z })`, as the [`buyTool` reference](https://docs.agentcard.com/api-reference/commerce-sdk/buy-tool) shows.

Pass `deliveryAddress` to `buyTool` when you already hold the shopper's address. The order goes there, and Agentcard never asks the shopper for it. The model can change neither the address nor the shopper.

## Check it in the sandbox

`init` puts production credentials in your env file, and those place real orders. Copy your sandbox credentials to test without placing any:

```bash theme={null}
npx agent-cards credentials --mode sandbox
```

Put the two lines in place of the production ones while you test, in the env file `init` wrote: `.env.local` for Next.js, `.env` otherwise.

```text theme={null}
AGENTCARD_CLIENT_ID=your_client_id
AGENTCARD_CLIENT_SECRET=your_client_secret
```

Read both from your app's secret store, and never hard-code them, log them, or commit them. Sandbox credentials run the whole flow against real stores and stop before payment, so no order is placed and nobody is charged. In the sandbox, the Vault code that connects a test shopper is always `111111`.

Run the scripted walkthrough with your sandbox credentials. It connects a test shopper with the code `111111`, asks for a restaurant table, picks one, and confirms it, with no model in the loop.

```bash theme={null}
AGENTCARD_CLIENT_ID=your_client_id AGENTCARD_CLIENT_SECRET=your_client_secret node node_modules/@agent-cards/commerce-sdk/examples/walkthrough.mjs
```

The sandbox refuses the booking itself, so nothing is booked or charged. The last answer is `declined` with `decline_code: sandbox_unavailable`, and the run ends with:

```text theme={null}
walkthrough passed
```

The walkthrough then asks as a shopper nobody connected, twice, and checks that Agentcard returns the same Vault link both times. It refuses live credentials before it connects anybody.

Then try your own agent with a test shopper. Send "two packs of AA batteries from Amazon" and watch for product cards, a short reply, and a cart. Start implementing, step 4, shows the first search the moment it arrives.

The package also ships `examples/anthropic.mjs` and `examples/openrouter.mjs`, which run the buy tool as a chat in your terminal and print the links your app would send. Each guide in this section ends with a check you run in the sandbox.

## Hear from Agentcard

Agentcard tells your server about every moment a shopper should hear about, even when the shopper is not chatting: a card saved, an approval about to expire, an order placed, a delivery on its way. The SDK hands you each one as a message with `text` ready to post into that shopper's chat. Pick the way your host runs.

When you build your tools with `threadId`, post each message into the chat its `threadId` names. A message about the shopper alone, such as a saved card, carries `threadId: null`, and [Keep a purchase per chat](https://docs.agentcard.com/api-reference/commerce-sdk/buy-tool.md#keep-a-purchase-per-chat) says where it goes.

### Listen from a long-running server

Call `listen` once when your server starts, on the same `AgentcardClient` your tools use. Your server opens one connection to Agentcard, so you host no public URL and check no signature.

```ts server.ts theme={null}
import { agentcard } from './agentcard';

agentcard.listen({
  onMessage: (shopperId, message) => postToChat(shopperId, message.text), // your code
  onEvent: (event) => console.log(event.type, event.data),
});
```

`onMessage` gets each message under the `externalUserId` you gave the buy tool. `onEvent` gets every other event Agentcard sends your company, such as `order.placed`. The listener reconnects after a dropped connection and resumes after the last event it handled. Run one listener for each company and mode. The [`listen` reference](https://docs.agentcard.com/api-reference/commerce-sdk/listen) lists the options, including a `cursor` store that resumes a restarted server where the last process stopped.

### Take events at a webhook endpoint on serverless

A host that ends each request after a few seconds cannot keep a connection open. Mount `agentcardWebhook` on a route instead. The handler checks each delivery's signature, skips an event it already handled, and calls `onMessage` with your own id for the shopper.

```ts app/api/agentcard/route.ts theme={null}
import { agentcardWebhook, stripLinks } from '@agent-cards/commerce-sdk';

const webhook = agentcardWebhook({
  secret: process.env.AGENTCARD_WEBHOOK_SECRET ?? '', // returned once, when you create the endpoint
  onMessage: async (shopperId, message) => {
    await postToChat(shopperId, message.text); // your code
    await saveAssistantMessage(shopperId, stripLinks(message.text)); // your code: the model reads it from the history
  },
});

export const POST = webhook.fetch;
```

Create the webhook endpoint with [`POST /api/v2/webhook_endpoints`](https://docs.agentcard.com/api-reference/webhook-endpoints/create), and subscribe it to `purchase.message`, `order.confirmed`, and `order.updated` by name. A catch-all `*` alone does not turn `purchase.message` on. The handler answers `200` once `onMessage` returns and `500` when it throws, and Agentcard then delivers the event again, so a failed post is not lost. In an Express route, mount the same handler with `express.raw({ type: 'application/json' })` before any `express.json()`. The [webhook handler reference](https://docs.agentcard.com/api-reference/commerce-sdk/webhook-handler.md) shows both.

### Let your model read what the shopper read

Between turns, Agentcard posts messages such as "Your Visa ending 3132 is saved" into the shopper's chat. Your model has to read them too, or it answers "ok lets checkout" with "did you save your card?". Pass `turn.messages(history)` as the model's messages, as the code above does, and the turn adds each message the history does not hold yet. "Take the next step once the shopper finishes outside the chat" shows how your agent moves on without waiting for the shopper to say "ok".

The client keeps each message in the process that received it, so a server that runs `listen` beside your model hands them to the next turn on its own. A webhook endpoint on serverless answers in another process than your chat route, so write each message into the shopper's history as an assistant message, as the handler above does, and your model reads it from there. Post the message's own text to the shopper, and save `stripLinks(message.text)` for the model, so the model never repeats a link that has since expired. The buy tool hands the shopper a current one.

The order events your company receives are documented in [Order events](https://docs.agentcard.com/webhooks/orders/overview.md): `order.placed`, `order.confirmed`, `order.failed`, and `order.updated`.

## See what your agent can buy

The buy tool covers four kinds of purchase, and the model picks the right one from the shopper's words.

| The shopper asks for | What happens |
| - | - |
| Products from online stores | Agentcard searches the stores, shows product cards, and builds the cart for the one the shopper picks. |
| Food delivery | Agentcard shows the stores near the shopper, then the store's menu, and the shopper signs in to the store's own account when the store needs it. |
| A table reservation | Agentcard finds open tables and books the one the shopper picks. A table costs nothing. |
| A flight | Agentcard shows each flight as a card with no page to open, and books the one the shopper picks. |

Each guide in this section covers one moment of the shopper's experience, from the product cards to the approval.

### Check where Agentcard can pay

Ask Agentcard whether it can pay at a store before you send a shopper there. Call `GET /buy/merchants` with the token `await agentcard.bearer()` returns, `$AGENTCARD_TOKEN` below, and put the store's name or domain in `q`:

```bash theme={null}
curl "https://api.agentcard.sh/buy/merchants?kind=catalog&q=target.com" \
  -H "Authorization: Bearer $AGENTCARD_TOKEN"
```

```json theme={null}
{
  "merchants": [
    {
      "kind": "catalog",
      "slug": "store_4fad04ea92d94045faa7b72f",
      "name": "Target",
      "domain": "target.com",
      "buys_through": "retail",
      "supported": true,
      "supported_reason": null,
      "supported_detail": null,
      "supported_read_at": null,
      "countries": []
    }
  ],
  "next_cursor": null,
  "counts": { "direct": 0, "catalog": 1 }
}
```

The call names no shopper, so you can check a store before anyone connects. You read each store as a shopper of your app reads it before signing in to any store.

Read `supported` to see whether Agentcard can buy at the store, `supported_reason` to see why, and `supported_detail` for the processor or the stop behind a `false`. `true` means a real purchase at the store went through, or a shopper's conversation reached the store's total at a card form Agentcard pays through, on `supported_read_at`. `false` means the store's card form uses a payment processor Agentcard cannot pay through, or the last conversation there stopped before the total. `null` means no purchase or conversation in the last 14 days says either way. Target, like every store whose `buys_through` is `retail`, reads `true` with no reason, no detail and no date, because Agentcard pays there without a card form. Agentcard checks the card form again on every purchase and types a card only when the check passes.

| `supported_reason` | What it means | What to do next |
| - | - | - |
| `pay_proven` | A real purchase at the store went through on `supported_read_at`. | Send shoppers there. |
| `reach_proven` | A shopper's conversation reached the store's total on `supported_read_at`, and the store's card form uses a processor Agentcard pays through. | Send shoppers there. |
| `gate_refused` | The store's card form uses a processor Agentcard cannot pay through, and `supported_detail` names it, such as `adyen`. Your agent offers to look for the product on Amazon instead. | Send the shopper to another store. |
| `unreached` | The last conversation at the store stopped before its total, and `supported_detail` names where, such as `sold_out` or `region_unavailable`. | Offer another store. Agentcard still tries a purchase there when a shopper asks. |

Compare each entry's `domain` with your store, because `q` matches part of a name or domain. A call returns up to 50 entries, or as many as `limit` asks for, up to 100. When your store is not among them and `next_cursor` is not `null`, send the same call again with `cursor` set to that value, until you find the store or `next_cursor` is `null`. Agentcard has no answer yet for a store missing from every page, so treat that store as one Agentcard cannot pay at.

An entry carries `held_back` when the store cancelled orders Agentcard placed there as a guest. Until `held_back.until`, Agentcard offers the shopper another store, unless the shopper signed in to that store and checks out as themselves.

`countries` names the countries a store sells in, and is empty when Agentcard has none on record.

Leave out `kind=catalog` to also search the merchants Agentcard works with directly, such as DoorDash, whose entries carry `kind: "direct"`.

Add `&external_user_id=user-42`, the `externalUserId` you give the buy tool, to read the list as that shopper: each `direct` entry then carries `link_status`, which says whether the shopper still has to link that merchant, and a store the shopper signed in to carries no `held_back`.

Agentcard answers `403` when no connected shopper carries that id:

```text theme={null}
{
  "error": "user_not_connected",
  "code": "user_not_connected",
  "external_user_id": "user-42",
  "message": "No person connected to your sandbox app carries the external_user_id \"user-42\". Sandbox and production users are separate: connect this person with your sandbox credentials, passing this external_user_id to the connect flow or the Vault link, then send it again."
}
```

| Code | What it means | What to do next |
| - | - | - |
| `user_not_connected` | No shopper connected to your app carries that `external_user_id`. | Leave out `external_user_id` to read your app's list, or connect the shopper as in [Adding a card for a new shopper](https://docs.agentcard.com/commerce-sdk/guides/adding-a-card.md). |

## Go live

Switch from sandbox to live in two steps. The code stays the same.

1. Choose Go live in the dashboard's banner. It creates your production credentials and opens Settings, Developers, Credentials on the Production tab. Copy the production client ID and secret into `AGENTCARD_CLIENT_ID` and `AGENTCARD_CLIENT_SECRET`. A webhook endpoint belongs to a mode, so create a live endpoint for the live credentials and use its secret.
2. Open Commerce SDK, Balance in the dashboard and choose how to pay the fee. Agentcard takes 1% of each live purchase. With prefund, you add money to a balance and each fee comes out of it. With pay as you go, you save a card and each fee is charged to it as the purchase completes. Fees too small to charge wait and are charged together with the next one.

Choose before your agent makes its first live purchase. A prefunded balance that reaches zero, or a card that declines, pauses live purchases until you add funds or a card that works. Sandbox purchases are never billed.

Live credentials place real orders and charge real cards. Test the full flow with your own card first, and keep the sandbox credentials for your tests.

## Keep going

> [card] [Showing products and carting the one the shopper picks](https://docs.agentcard.com/commerce-sdk/guides/showing-products.md)
>
> Render product cards and cart the exact product the shopper taps.

> [card] [Sending each link: approval, Vault and store sign-in](https://docs.agentcard.com/commerce-sdk/guides/sending-each-link.md)
>
> Deliver every link to the shopper while the model never reads one.

> [card] [Approving a purchase](https://docs.agentcard.com/commerce-sdk/guides/approving-a-purchase.md)
>
> Send the approval link and place the order only after the shopper says yes.

> [card] [Commerce SDK reference](https://docs.agentcard.com/api-reference/commerce-sdk/overview.md)
>
> Every export, option, and message type.

> [card] [Commerce MCP server](https://docs.agentcard.com/commerce-mcp.md)
>
> Connect your agent to one URL and skip the SDK install.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.