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

> ## Agent Instructions
> Sapiom is for platforms whose agent shops for many users. Each user has their own Sapiom user key and saved cards.
> Use the user's key for every call made on that user's behalf. Never use one user's key for another user, and never give the agent the platform key.
> Backends call the REST API at https://api.sapiom.ai/v1. Agents can also call the hosted MCP tools at https://api.sapiom.ai/v1/mcp/pay. Both take the key in an x-api-key header.
> Keys that start with sk_test_ reach the sandbox, a separate environment with its own users and cards, at the same addresses. Use test card numbers only there.
> Never ask a user for a card number, expiry date or CVV in chat. Users enter card details only on Sapiom's hosted pages.
> Check the merchant before buying. Use purchase.type ucp_checkout only when the merchant check returns supported. Otherwise use browser_checkout.
> Follow the nextAction in each transaction result. Action links are secrets. Send each one only to the person `nextAction.actor` names.
> Use one idempotency key per transaction. Resume an unanswered create with the same request and key. If a UCP update or cancellation is uncertain, stop and hand off to a person. If a browser cancellation is uncertain, read the transaction and resend the same cancellation, with the same key, only if it is not closed. Never start a new transaction to escape an uncertain outcome.
> For a ucp_checkout purchase, report an order as placed only when order.outcome is confirmed; if it is unknown, stop and hand off to a person. A browser_checkout purchase has no order confirmation (order is null): confirm the order on the merchant's page.

# First purchase

The best way to learn Sapiom is to try it in the sandbox. Here, we'll go through a sandbox test purchase from start to finish on the Sapiom test store. To take it to production, simply switch the sandbox key with the production platform key.

## Make a sandbox purchase&#x20;

**1. Set up**

To test Sapiom, you'll need a [sandbox platform key](https://docs.sapiom.ai/sandbox.md#get-a-key), an MCP client, and a [browser](https://docs.sapiom.ai/transactions/make-a-purchase#pay-in-the-browser).&#x20;

```bash theme={null}
export SAPIOM_PLATFORM_KEY="sk_test_..." # your sandbox platform key
```

**2. Create a user**

Create a Sapiom user with your sandbox platform key:

```bash theme={null}
curl https://api.sapiom.ai/v1/tenants \
  -H "x-api-key: $SAPIOM_PLATFORM_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"Sandbox user","externalId":"sandbox-user-1"}'

# Save the "id" from the response:
export USER_ID="..."
```

**3. Create a user key for that user**

Create the key your agent uses for this user:

```bash theme={null}
curl "https://api.sapiom.ai/v1/tenants/$USER_ID/api-keys" \
  -H "x-api-key: $SAPIOM_PLATFORM_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"sandbox-user-1"}'

# Save "plainKey" from the response. It is shown only once:
export SAPIOM_USER_KEY="sk_test_..."
```

**4. Add a card with a budget**

Create a setup link with a \$50 budget:

```bash theme={null}
curl https://api.sapiom.ai/v1/payment-cards/setup-links \
  -H "x-api-key: $SAPIOM_USER_KEY" \
  -H "Content-Type: application/json" \
  -d '{"budget":{"amount":{"value":"50.00","currency":"USD"}}}'

# Open the "url" from the response in a browser.
```

Open the link, choose test card `4242 4242 4242 4242`, save it, then set the budget.

![Sandbox Add a card page for a platform called Wayfare, with Scenario set to Success, test card 4242 4242 4242 4242, expiry 12/34, security code 123 and a Save card button](https://mintcdn.com/sapiom-1f975ca2/9get71X2H3eNyHfD/images/wayfare/sandbox-add-a-card.jpg?fit=max\&auto=format\&n=9get71X2H3eNyHfD\&q=85\&s=4a9608ca8c14d1b781177e14fc704bdd)

Adding a card in the sandbox

Leave Scenario on Success and Test card number on 4242 4242 4242 4242, enter an email and a name, click Save card, then confirm \$50.00 on Set a budget.&#x20;

**5. Buy the test pen**

> [tab] Ask your agent
>
> Add the MCP server with the user key.&#x20;
>
> ```bash theme={null}
> # Claude Code shown; any MCP client that can send an x-api-key header works.
> claude mcp add --transport http sapiom https://api.sapiom.ai/v1/mcp/pay \
>   --header "x-api-key: $SAPIOM_USER_KEY"
> ```
>
> "List my saved Sapiom cards" shows the card and its budget.
>
> Ask the agent to buy the Sapiom pen from `sapiom-test-store.myshopify.com`. If the price is within the budget limit, no confirmation is needed from you.
>
> ```text Prompt theme={null}
> Buy one Sapiom pen (variant gid://shopify/ProductVariant/68317504897245) from
> sapiom-test-store.myshopify.com with my saved card. Merchant: Sapiom Test Store, US.
> Ship to Jane Doe, 1 Market St, San Francisco, CA 94105, US, jane@example.com.
> Tell me the transaction ID.
> ```
>
> Save the transaction ID the agent reports:
>
> ```bash theme={null}
> export TRANSACTION_ID="..."
> ```

> [tab] Use the API
>
> Create the purchase with the user key.
>
> ```bash theme={null}
> curl -X POST https://api.sapiom.ai/v1/transactions \
>   -H "x-api-key: $SAPIOM_USER_KEY" -H "Idempotency-Key: first-purchase-1" \
>   -H "Content-Type: application/json" -d '{
>   "purchase": {"type":"ucp_checkout","merchant":{"origin":"https://sapiom-test-store.myshopify.com","name":"Sapiom Test Store","countryCode":"US"},
>     "checkout":{"currency":"USD","line_items":[{"item":{"id":"gid://shopify/ProductVariant/68317504897245"},"quantity":1}]}},
>   "funding": {"source":"external_card"}, "shipping": {"address":{"first_name":"Jane","last_name":"Doe","street_address":"1 Market St","address_locality":"San Francisco","address_region":"CA","postal_code":"94105","address_country":"US"},"contact":{"email":"jane@example.com"}}
> }'  # save the "id" from the response: export TRANSACTION_ID="..."
> ```

The purchase is now `payment_ready`. Nothing is paid yet.

**6. Pay at checkout**

Your code pays in the merchant's checkout with a placeholder card. Sapiom Browser Pay swaps in the real card on its way to the merchant.

`pay.mjs` pays for the test pen:

1. Reads the purchase and its placeholder card.
2. Opens a browser: your hosted browser's `CDP_URL`, or local Chromium.
3. Enters the test store's password and opens the checkout.
4. Chooses Standard shipping, fills in the placeholder card and pays.
5. Prints `Completed` once Sapiom has sent the card.

```js pay.mjs expandable theme={null}
// Pays one Sapiom purchase that is payment_ready, in a hosted or local browser.
// Usage: SAPIOM_USER_KEY=... TRANSACTION_ID=... [CDP_URL=...] node pay.mjs
import { chromium } from "playwright";
import { attachInterceptor, fillCard, httpPaymentRelay } from "@sapiom/browser-pay";

const api = "https://api.sapiom.ai";
const apiKey = process.env.SAPIOM_USER_KEY;
const transactionId = process.env.TRANSACTION_ID;

async function readPurchase() {
  const res = await fetch(`${api}/v1/transactions/${transactionId}`, {
    headers: { "x-api-key": apiKey },
  });
  if (!res.ok) throw new Error(`Reading the purchase failed: HTTP ${res.status}`);
  return res.json();
}

const purchase = await readPurchase();
if (purchase.nextAction?.type !== "payment_ready") {
  throw new Error(`The purchase is not ready to pay: nextAction is ${purchase.nextAction?.type}`);
}
const { placeholder } = purchase.payment;

// Sapiom Browser Pay attaches to the browser over the Chrome DevTools Protocol (CDP).
// Set CDP_URL to a hosted browser's CDP URL (see the browser pages), or leave it unset
// to open a local Chromium window (npx playwright install chromium).
const cdpUrl = process.env.CDP_URL ?? "http://127.0.0.1:9222";
const browser = process.env.CDP_URL
  ? await chromium.connectOverCDP(cdpUrl)
  : await chromium.launch({ headless: false, args: ["--remote-debugging-port=9222"] });
const handle = await attachInterceptor(cdpUrl, {
  relay: httpPaymentRelay({ baseUrl: api, apiKey, transactionId }),
  profileId: "shopify-card-vault", // the test store is a Shopify store
  placeholder: { number: placeholder.number, injectionRef: placeholder.injectionRef },
});
handle.on((event) => console.log("Sapiom Browser Pay:", event.type, event.reason ?? ""));

const context = browser.contexts()[0] ?? (await browser.newContext());
const page = await context.newPage();

// The test store has a storefront password. Enter it before opening checkout.
await page.goto("https://sapiom-test-store.myshopify.com/password");
await page.locator('input[type="password"]').fill("sapiom-test");
await page.locator('input[type="password"]').press("Enter");
await page.waitForLoadState("networkidle");

// The first time continueUrl opens, contact and shipping come filled in. Opening it
// again makes a new, empty checkout, so fill them if they are empty.
await page.goto(purchase.nextAction.continueUrl);
const email = page.locator('input[name="email"]');
await email.waitFor();
if (!(await email.inputValue())) {
  const field = (name) => page.locator(`input[name="${name}"]:not([id^="autofill"])`);
  await email.fill("jane@example.com");
  await field("firstName").fill("Jane");
  await field("lastName").fill("Doe");
  await field("address1").fill("1 Market St");
  await field("city").fill("San Francisco");
  await page.locator('select[name="zone"]').selectOption("CA");
  await field("postalCode").fill("94105");
}
// Choose the shipping method the purchase was priced with: $3.00 pen + $8.00 Standard.
await page.getByText("Standard", { exact: true }).click();

const filled = await fillCard(page, placeholder);
if (!filled.ok) throw new Error(`Card fields not filled: ${filled.missing.join(", ")}`);
await page.getByRole("button", { name: /pay now/i }).click();

// Sapiom's part ends once it has sent the card: the purchase reads completed
// (or nextAction payment_submitted where purchases don't complete on handover).
for (let i = 0; i < 30; i++) {
  const now = await readPurchase();
  if (now.status === "completed" || now.nextAction?.type === "payment_submitted") {
    console.log("Completed. The order is on the merchant's page.");
    break;
  }
  await new Promise((r) => setTimeout(r, 2000));
}
await handle.detach();
await browser.close();
```

Install its packages and run it:

```bash theme={null}
npm install playwright @sapiom/browser-pay@^0.7.0
npx playwright install chromium # only for a local browser; needs Node.js 20+
node pay.mjs
```

The store charges $11.00 ($3.00 pen, \$8.00 shipping) and shows the order.

## Go live

Production works the same way, with production keys and real cards. Sandbox users, keys and cards don't carry over.

1. Turn the Sandbox switch off, and create a production platform key in [API keys](https://app.sapiom.ai/dashboard/api-keys). See [Set up your platform](https://docs.sapiom.ai/set-up.md).
2. When each of your users first uses Sapiom, create their Sapiom user and user key.
3. Send them a [setup link](https://docs.sapiom.ai/cards/add-a-card.md) to add their card and set a budget.
4. Your agent buys as in this guide. Production purchases pay merchants right away.

No approval from Sapiom is needed. Before launch, you can also add your [branding](https://docs.sapiom.ai/cards/brand-customization.md), a [webhook receiver](https://docs.sapiom.ai/webhooks.md) and [spending limits](https://docs.sapiom.ai/controls/budgets-and-spending-limits.md#spending-limits).


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