# Headless checkout

> useCheckout() from @intents-fi/react, or the public checkout API, with the customer-safety elements you must render.

```tsx
"use client";

import { Qr, useCheckout } from "@intents-fi/react";
import { useRef } from "react";

export function Checkout({ invoiceId, clientSecret }: { invoiceId: string; clientSecret: string }) {
  const root = useRef<HTMLDivElement>(null);
  // devCheck: in development, every render checks the safety elements are on screen.
  const c = useCheckout(invoiceId, clientSecret, { devCheck: root });
  const { required } = c;

  if (!c.invoice) return <p>{c.error ?? "Loading…"}</p>;

  return (
    <div ref={root}>
      <h1>${c.invoice.amount}</h1>

      {required.countdown && (
        <p {...required.countdown.props}>
          {required.countdown.label} {required.countdown.text}
        </p>
      )}

      {c.status === "pay" && (
        <button type="button" onClick={() => c.listOptions("transfer")}>
          Choose how to pay
        </button>
      )}

      {c.status === "choose" && (
        <ul>
          {(c.options ?? []).map((option) => (
            <li key={option.asset}>
              <button type="button" onClick={() => c.select(option, "transfer")}>
                {option.symbol} on {option.chain}: ${option.amountInUsd}
                {option.recommended && " (suggested)"}
              </button>
            </li>
          ))}
        </ul>
      )}

      {required.amount && (
        <p {...required.amount.props}>
          Send exactly <code>{required.amount.text}</code>
        </p>
      )}
      {required.chainWarning && (
        <p {...required.chainWarning.props}>
          <strong>{required.chainWarning.text}</strong> {required.chainWarning.detail}
        </p>
      )}
      {required.refundField && (
        <div {...required.refundField.props}>
          {required.refundField.editable ? (
            <label>
              {required.refundField.label}
              <input
                value={required.refundField.value}
                onChange={(e) => required.refundField?.onChange(e.target.value)}
              />
            </label>
          ) : (
            <p>
              {required.refundField.label}: <code>{required.refundField.value}</code>
            </p>
          )}
        </div>
      )}
      {required.address && (
        <p {...required.address.props}>
          To <code>{required.address.address}</code>
        </p>
      )}
      {required.qr && (
        <div {...required.qr.props}>
          <Qr value={required.qr.value} />
        </div>
      )}

      {c.status === "send-transfer" && (
        <button
          type="button"
          disabled={c.busy || (!c.attempt && !required.refundField?.valid)}
          onClick={() => c.pay()}
        >
          Pay
        </button>
      )}
      {c.status === "status" && <p role="status">Payment on its way…</p>}
      {c.status === "paid" && <p role="status">Paid. Thank you.</p>}
    </div>
  );
}
```

You render 100% of the UI; the hook holds the state and the actions. It is the same state machine
the hosted page and `<CheckoutEmbed>` run, calling the same public endpoints, so a headless
checkout walks exactly the same states as the hosted one. The example above is the one in
`packages/react/examples/next/app/headless`, which a test pays end to end.

## `useCheckout(invoiceId, clientSecret, options)`

| Option | What it does |
|---|---|
| `apiBase` | where the hook calls the API. Defaults to `https://api.intents.fi`, which accepts browser calls from any origin; a same-origin proxy that forwards `/v0/checkout/*` unchanged also works |
| `payer` | the customer's address, if you know it: options are ranked by what it holds (below) |
| `onPaid(invoice)` | once, when the invoice is paid. For the page; fulfil from the webhook |
| `onEvent(event)` | `{ type: "status", status, screen }` as the payment moves, and `{ type: "paid", checkout }` once |
| `devCheck` | a ref to the element your checkout renders into. In development, every render runs `assertRequiredRendered` on it and logs any missing safety element by name |

## What the hook returns

| Field | What it is |
|---|---|
| `invoice` | the public view of the invoice: price, merchant, status. `null` until loaded |
| `loading`, `error` | loading the invoice, and the last error message |
| `status` | the screen the default UI would show: `pay`, `choose`, `send-transfer`, `send-wallet`, `status`, `paid`, `underpaid`, `quote-expired`, `refunded`, `failed`, `dead-end-expired`, `dead-end-canceled` |
| `mode` | `"transfer"` (send from an exchange or any wallet) or `"wallet"` (connect and sign) |
| `options`, `optionsLoading` | the ranked "pay with" list, `null` until `listOptions()` has loaded it |
| `selected` | the option the customer chose |
| `attempt` | the active payment attempt, with its exact amount and deposit address |
| `busy`, `walletPhase`, `progress` | an action is running; the wallet's phase (`idle`, `connecting`, `running`, `rejected`, `failed`, `submitted`) and its step progress |
| `priceChange` | the new amount when the price moved between the list and the attempt (`409 QUOTE_DRIFT`), waiting for the customer's answer |
| `required` | the customer-safety elements (below) |
| `listOptions(mode?)` | load the "pay with" list for a way of paying |
| `select(asset \| option, mode?)` | choose what to pay with. In wallet mode this connects the wallet and starts the attempt; in transfer mode it waits for the refund address and `pay()` |
| `setRefundTo(address)` | set the refund address (also `required.refundField.onChange`) |
| `pay()` | take the payment as far as this side can: in transfer mode, issue the deposit address; in wallet mode, run the wallet's steps; in test mode, complete the test payment |
| `confirmPriceChange()`, `rejectPriceChange()` | answer `priceChange`: go ahead at the new amount, or back to the list |
| `requote()` | get a fresh quote after the old one expired (`quote-expired`) |
| `restart()` | start over on the same invoice; a new attempt replaces the old one |

## The safety elements you must render

`required.keys` lists the elements the current state needs on screen, from `REQUIRED_KEYS`:

| Key | What it carries |
|---|---|
| `amount` | `text` ("49.41 USDT", render it exactly), `amount`, `symbol`, `baseUnits` |
| `chainWarning` | `text` ("Send USDT on TRON only."), `detail` (what happens to anything else), `symbol`, `chain` |
| `address` | the deposit `address`, and a `memo` to show beside it when there is one |
| `qr` | `value`, the payment URI to encode. `<Qr value={…} />` from `@intents-fi/react` draws it |
| `countdown` | `text` ("28:14", or "Time is up"), `label`, `expiresAt`, `msLeft`, `expired` |
| `refundField` | `value`, `editable`, `onChange`, `valid`, `error`, `label`, `hint` |

They are what stops a customer sending the wrong amount, on the wrong network, after the quote has
expired, with no way back. Every customisation level shows them; headless is no exception. Each one
is `null` when the current state does not need it, and each carries `props`: spread them on the
element that shows it (`<p {...required.amount.props}>`). The text is already formatted from the
attempt's own `display`, so there is nothing to work out yourself.

`assertRequiredRendered(root, c.required)` checks that every element in `required.keys` is inside
`root`, is not hidden (`hidden`, `aria-hidden`, `display: none`, `visibility: hidden`,
`opacity: 0`) and shows its value: the amount, the network's name, the full address, a drawn QR
(`svg`, `canvas` or `img`), an input for an editable refund field. It throws a
`RequiredElementsError` naming each problem; `checkRequiredRendered` returns the same list without
throwing. Pass `devCheck` to run it on every render in development, and call it in your go-live
test; the `go-live-checklist` [skill](/docs/agents/skills) checks for it too.

## The recommended option

Pass the payer's address (the `payer` option, or the connected wallet) and the list is ranked by
what they hold:



```bash title="curl"
curl https://api.intents.fi/v0/checkout/inv_3QkR7mVt9zLpXdB2hJn6Yw/options \
  -H 'x-client-secret: $CLIENT_SECRET'
```

```ts title="TypeScript"
const response = await fetch("https://api.intents.fi/v0/checkout/inv_3QkR7mVt9zLpXdB2hJn6Yw/options", {
  method: "GET",
  headers: {
    "x-client-secret": clientSecret,
  },
});

if (!response.ok) {
  const { error } = await response.json();
  throw new Error(`${error.code}: ${error.message}`);
}
const data = await response.json();
```

```python title="Python"
import httpx

response = httpx.get(
    "https://api.intents.fi/v0/checkout/inv_3QkR7mVt9zLpXdB2hJn6Yw/options",
    headers={"x-client-secret": client_secret},
)
response.raise_for_status()
data = response.json()
```



With `payer`, each option carries `balance` (base units, when it could be read) and `covers`
(whether that balance pays the all-in amount). `recommended` is the cheapest option the payer is
known to be able to pay with, so a customer holding USDT on Tron gets USDT on Tron preselected, even
if another network is a few cents cheaper, and it is listed first.

Balances are read on the payer's own network family only (an EVM address on the EVM chains, a Tron
address on Tron, a Solana address on Solana), within 800 ms. An option whose balance could not be
read shows without one and with `covers: true`: an unreadable balance never hides a way to pay.

## Test mode

An invoice made with an `ik_test_` key has no deposit address and nothing to sign, so
`required.address` and `required.qr` stay `null`. Tell the customer it is a test (the hosted page
says "This is a test payment. No money moves and there is no address to send to.") and let `pay()`
complete it: the invoice walks to paid and the real `invoice.paid` webhook fires.

## Without React: the raw API

The hook is a thin layer over the public checkout endpoints. A client secret in `x-client-secret`
authorises the writes; reads need only the invoice ID. The API answers browser calls to them from
any origin.



```bash title="curl"
curl https://api.intents.fi/v0/checkout/inv_3QkR7mVt9zLpXdB2hJn6Yw/attempts \
  -X POST \
  -H 'x-client-secret: $CLIENT_SECRET' \
  -H 'content-type: application/json' \
  -d '{
       "asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
       "mode": "wallet",
       "payer": "0xB47c2Ae95D0f1836cA9E7b240F5dC83a61E09b7D",
       "refundTo": "TRdG7wK2aXpL9oYcB5nVzQ4jMhF3sEuT6b"
     }'
```

```ts title="TypeScript"
const response = await fetch("https://api.intents.fi/v0/checkout/inv_3QkR7mVt9zLpXdB2hJn6Yw/attempts", {
  method: "POST",
  headers: {
    "x-client-secret": clientSecret,
    "content-type": "application/json",
  },
  body: JSON.stringify({
    "asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
    "mode": "wallet",
    "payer": "0xB47c2Ae95D0f1836cA9E7b240F5dC83a61E09b7D",
    "refundTo": "TRdG7wK2aXpL9oYcB5nVzQ4jMhF3sEuT6b"
  }),
});

if (!response.ok) {
  const { error } = await response.json();
  throw new Error(`${error.code}: ${error.message}`);
}
const data = await response.json();
```

```python title="Python"
import httpx

response = httpx.post(
    "https://api.intents.fi/v0/checkout/inv_3QkR7mVt9zLpXdB2hJn6Yw/attempts",
    headers={"x-client-secret": client_secret},
    json={
        "asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
        "mode": "wallet",
        "payer": "0xB47c2Ae95D0f1836cA9E7b240F5dC83a61E09b7D",
        "refundTo": "TRdG7wK2aXpL9oYcB5nVzQ4jMhF3sEuT6b"
    },
)
response.raise_for_status()
data = response.json()
```





```bash title="curl"
curl https://api.intents.fi/v0/checkout/inv_3QkR7mVt9zLpXdB2hJn6Yw/attempts/inv_3QkR7mVt9zLpXdB2hJn6Yw \
  -H 'x-client-secret: $CLIENT_SECRET'
```

```ts title="TypeScript"
const response = await fetch("https://api.intents.fi/v0/checkout/inv_3QkR7mVt9zLpXdB2hJn6Yw/attempts/inv_3QkR7mVt9zLpXdB2hJn6Yw", {
  method: "GET",
  headers: {
    "x-client-secret": clientSecret,
  },
});

if (!response.ok) {
  const { error } = await response.json();
  throw new Error(`${error.code}: ${error.message}`);
}
const data = await response.json();
```

```python title="Python"
import httpx

response = httpx.get(
    "https://api.intents.fi/v0/checkout/inv_3QkR7mVt9zLpXdB2hJn6Yw/attempts/inv_3QkR7mVt9zLpXdB2hJn6Yw",
    headers={"x-client-secret": client_secret},
)
response.raise_for_status()
data = response.json()
```



The attempt response carries a `display` object with every customer-safety element already
formatted (the amount as a decimal string and in base units, the symbol, the network, the deposit
address), so a headless client has nothing to format itself. Poll the attempt every two seconds
while the page is visible and back off to ten after five minutes.

## Look

There is no theme to set: it is your UI. Keep the safety elements legible, with text contrast of at
least 4.5:1, and the checkout light. Keep the copy plain: "network fee", never "gas"; "payment",
never "intent".

## Server side

Headless is only the payment UI. Your server still creates the invoice with
[`createInvoice`](/docs/platform/server-sdk) and fulfils on the verified `invoice.paid` webhook
([Verify and test webhooks](/docs/platform/verify-webhooks)), never on a status your page saw. If
you are adding crypto beside existing payment methods, start from
[Add crypto to your existing checkout](/docs/checkout/add-crypto).

---

Source: https://intents.fi/docs/checkout/headless · The whole corpus: https://intents.fi/docs/llms-full.txt
