# Connected-card checkout

> Request a checkout credential, acknowledge delivery, report the outcome, and handle retries.

- Human URL: https://conto.finance/docs/sdk/connected-cards
- Raw Markdown: https://conto.finance/docs/sdk/connected-cards.md
- Terminal view: https://conto.finance/ai/docs/sdk/connected-cards

Documentation group: Agentic commerce

Connected cards are available on the Builder and Enterprise plans. [Connect a card and verify its authorization](https://conto.finance/docs/guides/connected-cards) first. Install `@conto_finance/sdk` 0.4.0 or later. A standard agent SDK key has the `transactions:read` and `payments:approve` scopes these calls need. See [authentication](https://conto.finance/docs/sdk/authentication).

## Request and use a credential

Call `conto.connectedCards.list()` for card IDs and active mandates. Pass the card and mandate IDs to `draw()` with a saved 8–128 character idempotency key. A **draw** requests a credential. Amounts are USD cents: `2500` means **$25.00**.

```typescript

const conto = new Conto({ apiKey: process.env.CONTO_API_KEY! });

const draw = await conto.connectedCards.draw({
  cardId: process.env.CONTO_CARD_ID!,
  mandateId: process.env.CONTO_MANDATE_ID!,
  idempotencyKey: 'office-supplies-order-1042',
  amountMinor: 2500,
  currency: 'USD',
  merchant: {
    merchantName: 'Office Supply Store',
    merchantCountry: 'US',
  },
});

if (draw.reconciliationRequired) {
  throw new Error('Review the existing card request before checkout');
}
if (draw.decision !== 'APPROVED' || !draw.credential) {
  throw new Error('No fresh checkout credential is available');
}
if (!draw.credentialExpiresAt || Date.parse(draw.credentialExpiresAt) <= Date.now()) {
  throw new Error('Checkout credential has expired');
}

await conto.connectedCards.acknowledgeDelivery(draw.requestId);

// Your checkout integration; keep the credential in memory only.
const receipt = await completeAuthorizedCheckout({
  requestId: draw.requestId,
  credential: draw.credential,
  amountMinor: 2500,
  currency: 'USD',
});

await conto.connectedCards.reportOutcome(draw.requestId, { outcome: 'USED' });
```

`completeAuthorizedCheckout` is your application’s function. It must use the authorized merchant and checkout origin, enforce the purchase amount, and prevent duplicate checkout. Never persist credentials or expose them in prompts, tool results, logs, traces, or screenshots.

## Check a purchase first

Before you ask the cardholder to authorize a purchase, you can check it against the agent's card limits and policies. The check reserves nothing, creates no authorization, and returns no credential.

```typescript
const response = await fetch('https://conto.finance/api/sdk/connected-cards/preview', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.CONTO_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    cardId: process.env.CONTO_CARD_ID,
    amountMinor: 2500,
    merchant: {
      name: 'Office Supply Store',
      countryCode: 'US',
      checkoutOrigin: 'https://shop.example.com',
    },
  }),
});
if (!response.ok) throw new Error(`Preview failed: HTTP ${response.status}`);
const { decision, reasons } = await response.json();
```

`decision` is `APPROVED`, `DENIED`, or `REQUIRES_APPROVAL`, and `reasons` explains a denial. Send the store details the authorization will record. All `merchant` fields are optional: `name`, `providerMerchantId`, `categoryCode` (four-digit MCC), `countryCode` (two-letter code), and `checkoutOrigin` (HTTPS).

The draw rechecks current limits and policies against the verified authorization; a successful preview does not authorize checkout.

## Decisions and retries

| Result                                                   | What to do                                                                                                                                                 |
| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `APPROVED` with a fresh credential                       | Check expiry, acknowledge delivery, then complete checkout.                                                                                                |
| `DENIED`                                                 | Stop and inspect `reasons`.                                                                                                                                |
| `REQUIRES_APPROVAL`                                      | Wait for approval under **Needs attention** on the agent’s **Funding** tab, then retry the original input and key. Conto checks the request again. |
| Replay without a credential, or `reconciliationRequired` | Investigate the existing request before another issuance or checkout attempt.                                                                              |

Credentials are returned only once. The SDK does not automatically retry `draw()`, and reusing a key cannot retrieve a lost credential. Do not generate a new key to recover an uncertain result. A failed checkout does not return the amount to the verified authorization, even after the hold on the agent's limits is released.

If the card provider refuses to issue a credential, the draw returns `DENIED` with the reason. Nothing was charged, the hold is released, and a single-purchase authorization stays usable, so you can retry with a new idempotency key.

`acknowledgeDelivery()` is safe to retry for the same request. It records receipt of the credential, **not payment settlement**. Keep the request ID and non-sensitive order references, and confirm the purchase against the merchant receipt and card activity. Contact support if the outcome remains unclear.

## Purpose and task

A draw takes two optional fields, in `draw()` and in the request body:

- `purpose`: why the agent wants this purchase, up to 500 characters. People reviewing the draw see it, and it stays on the purchase record. Text that looks like a card number or a labeled secret is refused with 400.
- `taskRequestId`: an approved task, for a [shared budget](https://conto.finance/docs/sdk/shared-budgets) that requires one.

A retry with the same idempotency key must send the same values, or it returns 409.

Naming a task grants nothing. When a shared budget refuses a draw, the draw returns `DENIED` with no credential, the reason in `reasons`, and a code in `reasonCodes`. A test card draw returns `reasonCodes` too. Common codes:

| Code                          | Meaning                                                                |
| ----------------------------- | ---------------------------------------------------------------------- |
| `SHARED_BUDGET_EXCEEDED`      | The budget cannot cover the draw.                                      |
| `TASK_REQUIRED`               | A budget requires an approved task and the draw did not name one.      |
| `TASK_AUTHORITY_UNAVAILABLE`  | The task is unapproved, expired, closed, or unavailable to this agent. |
| `BUDGET_PAUSED`               | A budget that covers the draw is paused.                               |
| `BUDGET_EXPIRED`              | The draw is after a budget's end date.                                 |
| `BUDGET_CURRENCY_UNSUPPORTED` | A level has budgets for the agent and none covers the currency.        |
| `LINKED_BUDGET_REQUIRED`      | A linked buyer has no budget in the owner workspace.                   |

See [budget errors](https://conto.finance/docs/sdk/shared-budgets#errors) for more.

Get the task approved before you draw. A draw a budget refuses keeps its single-purchase authorization, unless another purchase takes the last of the budget at that same moment. Then the next try needs a new one.

## Report the outcome

The draw's amount stays held against the agent's limits until Conto knows what happened. After checkout, call `reportOutcome()`:

```typescript
// Charged the full amount. This closes the draw.
await conto.connectedCards.reportOutcome(draw.requestId, { outcome: 'USED' });

// Charged less than the approved amount, in cents.
await conto.connectedCards.reportOutcome(draw.requestId, { outcome: 'USED', amountMinor: 1850 });

// Never used the credential.
await conto.connectedCards.reportOutcome(draw.requestId, { outcome: 'NOT_USED' });
```

A report never releases held spend by itself. `USED` at the full amount closes the draw. `NOT_USED`, or a smaller amount, goes under **Needs attention** on the agent's **Funding** tab with your report shown. A person checks the card's activity and confirms, and only then is the rest of the hold released. An unused credential is shown there once it expires. The result has `closed` and `reviewRequired` so your agent knows which happened.

`reportOutcome()` is safe to retry with the same report. A different second report returns 409. If the agent reports nothing, the draw also goes under **Needs attention** an hour after its credential expires.

## Test cards

A [test card](https://conto.finance/docs/guides/connected-cards#try-it-with-a-test-card) works on every plan and uses the same agent key and scopes. Draws go through the agent's limits, your policies, and human review like a live card, and the same retry rules apply. The differences:

- Test cards have their own endpoints. A live card or authorization ID is not found there, and a test ID is not found on the live endpoints.
- An approved draw returns `testCredential`, an opaque token that starts with `ctc_test_`, instead of card fields. It is returned once. Handle it like a live credential: keep it out of prompts, tool results, and logs.
- The purchase completes at Conto's test checkout, the only place the token works. Checkout returns a receipt with `environment: "test"`, `simulated: true`, and `settlementMode: "test"`. Retrying checkout with the same draw and token returns the same receipt with `replayed: true`.
- Test purchases are simulated. No card is charged and no funds move.

```typescript
const base = 'https://conto.finance';
const headers = {
  Authorization: `Bearer ${process.env.CONTO_API_KEY}`,
  'Content-Type': 'application/json',
};

const { cards, merchants } = await (
  await fetch(`${base}/api/sdk/connected-cards/test`, { headers })
).json();
const card = cards[0];
const mandate = card.mandates[0];

const draw = await (
  await fetch(`${base}/api/sdk/connected-cards/test/draws`, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      cardId: card.cardId,
      mandateId: mandate.id,
      idempotencyKey: 'test-order-1042',
      amountMinor: 1200,
      currency: 'USD',
      merchant: { merchantName: mandate.merchant.name },
    }),
  })
).json();

if (draw.decision === 'APPROVED' && draw.testCredential) {
  const receipt = await (
    await fetch(`${base}/api/sdk/connected-cards/test/checkout`, {
      method: 'POST',
      headers,
      body: JSON.stringify({
        requestId: draw.requestId,
        credential: draw.testCredential.token,
        items: [{ sku: 'notebook-pack', quantity: 1 }],
      }),
    })
  ).json();
  console.log(receipt.orderNumber, receipt.settlementMode);
}
```

`merchants` lists each test merchant's catalog. Leave out `items` to buy one line for the authorized amount. An order above the authorized amount, or an item the merchant does not sell, is declined with 409 and leaves the credential usable until it expires. A credential expires 15 minutes after it is issued.

## HTTP endpoints

| Method | Endpoint                                                 | Agent scope         |
| ------ | -------------------------------------------------------- | ------------------- |
| `GET`  | `/api/sdk/connected-cards`                               | `transactions:read` |
| `POST` | `/api/sdk/connected-cards/preview`                       | `payments:approve`  |
| `POST` | `/api/sdk/connected-cards/draws`                         | `payments:approve`  |
| `POST` | `/api/sdk/connected-cards/draws/{requestId}/acknowledge` | `payments:approve`  |
| `POST` | `/api/sdk/connected-cards/draws/{requestId}/outcome`     | `payments:approve`  |

Test cards:

| Method | Endpoint                                                      | Agent scope         |
| ------ | ------------------------------------------------------------- | ------------------- |
| `GET`  | `/api/sdk/connected-cards/test`                               | `transactions:read` |
| `POST` | `/api/sdk/connected-cards/test/preview`                       | `payments:approve`  |
| `POST` | `/api/sdk/connected-cards/test/draws`                         | `payments:approve`  |
| `POST` | `/api/sdk/connected-cards/test/draws/{requestId}/acknowledge` | `payments:approve`  |
| `POST` | `/api/sdk/connected-cards/test/checkout`                      | `payments:approve`  |
| `GET`  | `/api/sdk/connected-cards/test/orders/{orderId}`              | `transactions:read` |

Use bearer authentication. On a draw, all `merchant` fields are optional: `merchantName`, `merchantId`, `merchantCategory` (four-digit MCC), and `merchantCountry` (two- or three-letter code). Any field you send must match the verified mandate exactly, or the request fails with 400. `amountMinor` cannot exceed the mandate amount.
