# Set up Intents Checkout in this project

You are a coding agent adding **Intents Checkout** to this project so it can get paid in crypto.
The merchant prices in USD, the customer pays in whatever token they hold on whatever chain, and
the merchant receives one settlement asset (a USD stablecoin, or native Bitcoin) at their own
address. Intents is non-custodial: it never holds the money. Invoices are always priced in USD:
match orders on the invoice's `amount` and `currency`, never on `settlement.*`, which is in the
settlement asset's base units (sats for BTC).

This prompt is only about Intents Checkout. Do not call `/v0/quotes` or `/v0/orders` and do not read the
Intents Route pages: Intents Checkout finds the route for every payment itself. (If the human actually
wants their users to swap or bridge their own funds, stop and follow
`https://intents.fi/docs/agent-setup/route.md` instead.)

If the project is a WooCommerce, WHMCS, Magento, PrestaShop or OpenCart store, there is nothing to
code: tell the human to install the plugin from `https://intents.fi/docs/checkout/index.md` and stop.

Follow the steps in order. Stop and ask the human only where a step says **ASK**.

## Rules for the whole session

- **Test keys only.** Use an `ik_test_` secret key. If the human gives you an `ik_live_` key, do not
  use it: say so and ask for the test key instead. Test mode routes in process, so no money moves.
- The secret key lives in `.env.local` (check it is in `.gitignore`) and in server code only. It is
  never imported by a client component, printed, logged or committed.
- Do not invent API fields. When unsure, read the docs: the `docs_search` and `docs_get_page` MCP
  tools, or `https://intents.fi/docs/checkout/llms.txt` (the Intents Checkout pages; every page is
  markdown at its URL plus `.md`).
- Amounts on the wire are integer strings in base units; prices are decimal strings like `"25.00"`.
  Do maths in `BigInt`, never floats.
- Only the webhook marks an order paid. A browser returning from checkout, or the widget's
  `onPaid`, is not proof of payment.

## Step 1: install the MCP server and the skills

Install the intents.fi MCP server (`@intents-fi/mcp`, run with `npx -y @intents-fi/mcp`) with
`INTENTS_API_KEY` set to the test key and `INTENTS_TOOLSETS=docs,checkout`, and the three Intents Checkout
skills from `https://github.com/intents-fi/skills` (`integrate-checkout`, `verify-webhooks`,
`go-live-checklist`). How depends on the agent you are:

- **Claude Code:** `claude mcp add intents-fi -e INTENTS_API_KEY=ik_test_… -e INTENTS_TOOLSETS=docs,checkout -- npx -y @intents-fi/mcp`,
  then clone `https://github.com/intents-fi/skills` to a temporary directory and copy those three
  skill folders into `.claude/skills/` (each skill must sit directly under it, as
  `.claude/skills/<skill>/SKILL.md`).
- **Cursor:** add the server to `.cursor/mcp.json`; see `https://intents.fi/docs/agent-setup/cursor.md`.
- **Codex:** add the server to `~/.codex/config.toml`; see `https://intents.fi/docs/agent-setup/codex.md`.

**ASK** the human for their `ik_test_` secret key (dashboard.intents.fi → Developers → API keys)
if it is not already in the environment. If the agent cannot load MCP servers, carry on without
them: everything below also works from the docs alone.

## Step 2: install the SDK

Install `@intents-fi/sdk` (the API client and webhook verification) and `@intents-fi/react` (the
`PayButton` widget) with the project's package manager:

```bash
npm install @intents-fi/sdk @intents-fi/react
```

## Step 3: a test-mode checkout

These files assume a Next.js App Router project. For another framework, keep the same three
pieces — an invoice route, a verified webhook handler, a pay button — and adapt the wiring.
Write them **as they are**; they use relative imports so no path alias is needed.

`.env.local` (append; never commit it):

```bash
# Test keys only while you build. dashboard.intents.fi → Developers → API keys.
INTENTS_SECRET_KEY=ik_test_replace_me
# Returned once, when you register the webhook endpoint (POST /v0/webhooks).
INTENTS_WEBHOOK_SECRET=whsec_replace_me
# Optional: only if the embedded widget should offer WalletConnect (Reown) wallets.
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=
```

`lib/intents.ts`, the server-side client:

```ts
import { createClient } from "@intents-fi/sdk";

/**
 * The intents.fi client, server-side only. INTENTS_SECRET_KEY is an `ik_test_` key while you
 * build; it must never reach the browser, so this file is only imported from route handlers.
 */
export function intents() {
  const apiKey = process.env.INTENTS_SECRET_KEY;
  if (!apiKey) throw new Error("Set INTENTS_SECRET_KEY (an ik_test_ key) in .env.local");
  return createClient({
    apiKey,
    ...(process.env.INTENTS_API_URL && { baseUrl: process.env.INTENTS_API_URL }),
  });
}
```

`lib/orders.ts`, a stand-in order store (tell the human to swap it for their database):

```ts
/**
 * Your order store. Replace this Map with your database: the webhook handler marks an order paid
 * here, keyed by the `reference` you created the invoice with.
 *
 * `markPaid` is idempotent on purpose. Webhooks are retried and may arrive twice or out of order,
 * so a second `invoice.paid` for the same invoice must change nothing.
 */
export type OrderState = { invoiceId: string; status: "pending" | "paid"; late: boolean };

export const orders = new Map<string, OrderState>();

export function markPaid(reference: string, invoiceId: string, late: boolean): boolean {
  const existing = orders.get(reference);
  if (existing?.status === "paid") return false;
  orders.set(reference, { invoiceId, status: "paid", late });
  return true;
}
```

`app/api/checkout/route.ts`, which creates the invoice server-side:

```ts
import { intents } from "../../../lib/intents";

/**
 * POST /api/checkout — create an invoice for a cart, server-side.
 *
 * The price comes from your own catalogue, never from the request body: a customer can send any
 * body they like. `reference` is your order ID and the API's idempotency key, so a retried request
 * returns the same invoice instead of a second one.
 */
const CATALOGUE: Record<string, { name: string; price: string }> = {
  "starter-plan": { name: "Starter plan", price: "25.00" },
};

export async function POST(request: Request) {
  const { sku, orderId } = (await request.json()) as { sku?: string; orderId?: string };
  const item = sku ? CATALOGUE[sku] : undefined;
  if (!item) return Response.json({ error: "unknown sku" }, { status: 400 });

  const invoice = await intents().checkout.invoices.create({
    amount: item.price,
    currency: "USD",
    reference: orderId ?? `order_${crypto.randomUUID()}`,
    description: item.name,
  });

  // `clientSecret` is for this one invoice and is meant for the browser; the secret key is not.
  return Response.json({
    invoiceId: invoice.id,
    clientSecret: invoice.clientSecret,
    url: invoice.url,
    amount: invoice.amount,
  });
}
```

`app/api/webhooks/intents/route.ts`, which verifies the signature and marks the order paid:

```ts
import { verifyAndParse } from "@intents-fi/sdk";
import { markPaid } from "../../../../lib/orders";

/**
 * POST /api/webhooks/intents — the only thing that marks an order paid.
 *
 * Read the body as text: the signature covers the raw bytes, and parsed-then-reserialised JSON is
 * not the same bytes. `verifyAndParse` returns null for a bad or stale signature, and the body is
 * never trusted before that check.
 */
export async function POST(request: Request) {
  const secret = process.env.INTENTS_WEBHOOK_SECRET;
  if (!secret) return new Response("INTENTS_WEBHOOK_SECRET is not set", { status: 500 });

  const body = await request.text();
  const event = await verifyAndParse(body, request.headers.get("x-intents-signature"), secret);
  if (!event) return new Response("bad signature", { status: 400 });

  // `data.status` is the truth; `type` is only why you were woken. Duplicates are normal.
  if (event.type === "invoice.paid" && event.data.status === "paid" && event.data.reference) {
    markPaid(event.data.reference, event.data.id, event.late === true);
  }
  return new Response(null, { status: 204 });
}
```

`app/checkout/page.tsx`, the page with the `PayButton`:

```tsx
"use client";

import { PayButton } from "@intents-fi/react";
import { useState } from "react";

/**
 * /checkout — one product, one button. The invoice is created server-side by /api/checkout;
 * the browser only ever sees the invoice's own `clientSecret`.
 *
 * `onPaid` updates the page, and that is all it does. It is not proof of payment: the webhook
 * handler is what marks the order paid.
 */
type Created = { invoiceId: string; clientSecret: string; url: string; amount: string };

export default function CheckoutPage() {
  const [invoice, setInvoice] = useState<Created | null>(null);
  const [paid, setPaid] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function start() {
    setError(null);
    const res = await fetch("/api/checkout", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ sku: "starter-plan" }),
    });
    if (!res.ok) return setError("Could not start the payment. Try again.");
    setInvoice((await res.json()) as Created);
  }

  if (paid) {
    return (
      <main>
        <h1>Thank you</h1>
        <p>Your payment was received.</p>
      </main>
    );
  }

  return (
    <main>
      <h1>Starter plan</h1>
      <p>$25.00</p>
      {invoice ? (
        <>
          <PayButton
            invoiceId={invoice.invoiceId}
            clientSecret={invoice.clientSecret}
            onPaid={() => setPaid(true)}
          />
          <p>
            Or <a href={invoice.url}>pay on the secure payment page</a>.
          </p>
        </>
      ) : (
        <button type="button" onClick={start}>
          Pay $25.00
        </button>
      )}
      {error && <p role="alert">{error}</p>}
    </main>
  );
}
```

### The webhook secret

The API only delivers to public `https` endpoints, so a handler on `localhost` never hears from it
directly. For local development, set `INTENTS_WEBHOOK_SECRET` to the same `whsec_` value in
`.env.local` **and** in the MCP server's environment: `send_test_webhook` signs with it. Once the
app is deployed, register the real endpoint (`POST /v0/webhooks` with the test key, events
`invoice.paid`, `invoice.expired`, `invoice.needs_review`) and use the `secret` it returns, once,
in both places.

## Step 4: check it works

1. Run the dev server and open `/checkout`. The page shows the price and a **Pay $25.00** button.
   Pressing it creates a test invoice and shows a **Pay** button, which opens the payment sheet;
   for a test invoice the sheet says "This is a test payment. No money moves…" and offers
   **Complete the test payment**.
2. Use the MCP tools: `get_invoice` with the invoice ID shows `"mode": "test"` and `"status": "open"`.
3. Call `send_test_webhook` with the invoice ID and `url` set to
   `http://localhost:3000/api/webhooks/intents` (use the real port). It pays the test invoice and
   POSTs the signed `invoice.paid` to the handler. Expect `"status": "paid"` and
   `"direct": { "status": 204 }`, and the order marked paid in `lib/orders.ts`.
4. Send the handler a body with a wrong signature and check it answers `400`.

If a step fails, read the error code's page at `https://intents.fi/docs/errors/<CODE>.md` and fix
the cause rather than working around it.

## Step 5: tell the human

Summarise what you created and that it runs in test mode, and point them at the
`go-live-checklist` skill (or `https://intents.fi/docs/checkout/index.md`, "Going live") for
the switch to live keys: register a live endpoint, check the settlement address in the dashboard,
pay themselves $5 for real.
