# Example: Next.js

> Add 'Pay with crypto' to a Next.js (App Router) checkout in three files: create the invoice, open the pop-up, ship the order on the invoice.paid webhook.

Three files and an order store. Create the invoice on your server, open the pop-up on your page,
and **ship the order on the `invoice.paid` webhook**, never on the pop-up's `onPaid`. This is
[`examples/checkout-nextjs`](https://github.com/devluke24/intentsfi/tree/main/examples/checkout-nextjs);
CI runs it against a test key on every change, so what is below works as written.

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

```bash
# .env.local
# A test key while you build: dashboard.intents.fi → API keys → Test mode.
INTENTS_SECRET_KEY=ik_test_...
# The whsec_… shown when you added the webhook endpoint (Webhooks → Add an endpoint).
INTENTS_WEBHOOK_SECRET=whsec_...
```

## 1. Create the invoice

`app/api/checkout/route.ts`

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

// 1. The customer chose "Pay with crypto" and placed the order: create the invoice for it.
export async function POST(request: Request) {
  const { orderId } = (await request.json()) as { orderId: string };
  const order = orders.get(orderId);
  if (!order) return Response.json({ error: "unknown order" }, { status: 404 });
  // The amount comes from your own records, never from the browser. `reference` is your order
  // id: calling this twice for one order returns the same invoice. Reads INTENTS_SECRET_KEY.
  const invoice = await createInvoice({ amount: order.amount, reference: order.id });
  return Response.json({ invoiceId: invoice.id, clientSecret: invoice.clientSecret });
}
```

## 2. The option and the pop-up

`app/page.tsx`

```tsx
"use client";
import { PayButton, PaymentMethodOption } from "@intents-fi/react";
import { useState } from "react";

// 2. Your checkout: "Pay with crypto" beside your other methods; placing the order opens the pop-up.
export default function Checkout() {
  const [method, setMethod] = useState("card");
  const [invoice, setInvoice] = useState<{ invoiceId: string; clientSecret: string } | null>(null);

  async function placeOrder() {
    const res = await fetch("/api/checkout", {
      method: "POST",
      body: JSON.stringify({ orderId: "order_1001" }),
    });
    setInvoice(await res.json());
  }

  return (
    <main style={{ maxWidth: 420, margin: "48px auto", display: "grid", gap: 8 }}>
      <h1>$25.00</h1>
      <label>
        <input
          type="radio"
          name="payment-method"
          checked={method === "card"}
          onChange={() => setMethod("card")}
        />{" "}
        Card
      </label>
      <PaymentMethodOption selected={method === "crypto"} onSelect={() => setMethod("crypto")} />
      {method === "crypto" && !invoice ? (
        <button type="button" onClick={placeOrder}>
          Place order
        </button>
      ) : null}
      {invoice ? (
        // onPaid only updates this page; the order ships from the webhook.
        <PayButton
          invoiceId={invoice.invoiceId}
          clientSecret={invoice.clientSecret}
          onPaid={() => location.assign("/?paid=1")}
        >
          Pay $25.00
        </PayButton>
      ) : null}
    </main>
  );
}
```

## 3. Ship on the webhook

`app/api/webhooks/intents/route.ts`

```ts
import { isTestEvent, verifyWebhook, WebhookSignatureError } from "@intents-fi/sdk";
import { markPaid } from "../../../../lib/orders";

// 3. The only place an order is marked paid: a verified invoice.paid webhook.
export async function POST(request: Request) {
  try {
    // The raw body: request.text(), never request.json(), or the signature cannot match.
    const event = await verifyWebhook(
      await request.text(),
      request.headers,
      process.env.INTENTS_WEBHOOK_SECRET,
    );
    // "Send test event" sends samples that were never paid: acknowledge them, ship nothing.
    if (event.type === "invoice.paid" && !isTestEvent(event) && event.data.reference) {
      markPaid(event.data.reference, event.data.id); // idempotent: the same event can come twice
    }
    return new Response(null, { status: 204 }); // any 2xx; anything else is retried
  } catch (e) {
    if (e instanceof WebhookSignatureError) return new Response("bad signature", { status: 400 });
    throw e;
  }
}
```

`lib/orders.ts` stands in for your database:

```ts
// Your order store. Here: memory. markPaid must be safe to call twice for one order.
type Order = { id: string; amount: string; status: "pending" | "paid"; invoiceId?: string };
export const orders = new Map<string, Order>([
  ["order_1001", { id: "order_1001", amount: "25.00", status: "pending" }],
]);

export function markPaid(orderId: string, invoiceId: string): void {
  const order = orders.get(orderId);
  if (!order || order.status === "paid") return; // unknown, or already shipped: do nothing
  orders.set(orderId, { ...order, status: "paid", invoiceId });
  // …ship it, email the customer, etc.
}
```

## Try it

1. In the dashboard, switch to **Test mode**, create a secret key, and add a webhook endpoint for
   `invoice.paid`. For a local server, register a tunnel's URL (`cloudflared tunnel`, `ngrok`).
2. `npm run dev`, pick **Pay with crypto**, place the order, and pay in the pop-up. Test mode moves
   no money.
3. **Send test event** in the dashboard delivers a sample `invoice.paid`: the handler answers 204
   and ships nothing, because `isTestEvent(event)` is true. **Resend** on the real delivery: the
   order is still paid once.

See [Server helpers](/docs/platform/server-sdk) and [Webhooks](/docs/platform/webhooks).

---

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