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

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Confirm payments from your backend

> Ship an order only after your server has looked the payment up on the network and checked the amount, the recipient, and the order reference.

<div className="sol-stepper not-prose" data-path="checkout">
<div className="sol-stepper-nav" role="navigation" aria-label="Build a checkout · ~30 min">
<ol>
<li data-state="done"><a href="/developers/docs/payments/checkout/try-it"><span className="sol-stepper-n">Step 1<span className="sol-vh">, </span><span className="sol-stepper-done">Done</span><span className="sol-vh">: </span></span><span className="sol-stepper-t">Pay as a customer</span></a></li>
<li data-state="done"><a href="/developers/docs/payments/checkout/browser"><span className="sol-stepper-n">Step 2<span className="sol-vh">, </span><span className="sol-stepper-done">Done</span><span className="sol-vh">: </span></span><span className="sol-stepper-t">Show a payment QR code</span></a></li>
<li data-state="current"><a href="/developers/docs/payments/checkout/backend" aria-current="step"><span className="sol-stepper-n">Step 3<span className="sol-vh">: </span></span><span className="sol-stepper-t">Confirm from your backend</span></a></li>
<li data-state="todo"><a href="/developers/docs/payments/checkout/go-live"><span className="sol-stepper-n">Step 4<span className="sol-vh">: </span></span><span className="sol-stepper-t">Go live</span></a></li>
</ol>
</div>
</div>

The checkout in the browser gives you a signature. Your server fetches that
transaction and checks that it paid you the right amount of USDC for this order
before marking the order paid. This step builds that server and runs it
against a local test network or devnet.

## 1. Create the project

You need Node.js 20.18 or later. Create a project folder, `solana-payments`,
with a `checkout` folder inside it. Every file in this tutorial goes in
`checkout/`, and you run every command from `solana-payments`. (The Paywall an
endpoint tutorial adds a `paywall-api/` folder next to it.)

```bash Terminal
mkdir -p solana-payments/checkout && cd solana-payments
npm init -y && npm pkg set type=module
npm install @solana/kit @solana-program/token
npm install --save-dev tsx
```

`"type": "module"` lets the scripts use top-level `await`. `tsx` runs the
TypeScript files directly. The examples are tested with `@solana/kit` 8.4 and
`@solana-program/token` 0.17.

Your server reads the network over RPC:

<div className="sol-concept not-prose">
[<span className="sol-concept-name">RPC</span> <span className="sol-concept-def">RPC is the HTTP/JSON API your code uses to read from and send to the network.</span>](/developers/docs/rpc)
</div>

The code reads its network settings from environment variables and defaults
to devnet. Save this as `checkout/config.ts`:

```ts checkout/config.ts
import {
  address,
  createSolanaRpc,
  createSolanaRpcSubscriptions,
} from "@solana/kit";

// Devnet by default. Point RPC_URL at mainnet (and USDC_MINT at mainnet USDC,
// EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v) when you go live.
export const RPC_URL = process.env.RPC_URL ?? "https://api.devnet.solana.com";
export const RPC_SUBSCRIPTIONS_URL =
  process.env.RPC_SUBSCRIPTIONS_URL ?? "wss://api.devnet.solana.com";
export const USDC_MINT = address(
  process.env.USDC_MINT ?? "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
);
export const USDC_DECIMALS = 6;

export const rpc = createSolanaRpc(RPC_URL);
export const rpcSubscriptions = createSolanaRpcSubscriptions(
  RPC_SUBSCRIPTIONS_URL,
);
```

Save the payment code from the previous step as `checkout/pay.ts`:

```ts checkout/pay.ts
import {
  AccountRole,
  appendTransactionMessageInstructions,
  assertIsTransactionWithBlockhashLifetime,
  createTransactionMessage,
  getSignatureFromTransaction,
  pipe,
  sendAndConfirmTransactionFactory,
  setTransactionMessageFeePayerSigner,
  setTransactionMessageLifetimeUsingBlockhash,
  signTransactionMessageWithSigners,
  type Address,
  type TransactionSigner,
} from "@solana/kit";
import {
  findAssociatedTokenPda,
  getTransferCheckedInstruction,
  TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
import { rpc, rpcSubscriptions, USDC_DECIMALS, USDC_MINT } from "./config";

const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({
  rpc,
  rpcSubscriptions,
});

/**
 * The customer pays `amount` USDC base units (1 USDC = 1_000_000) to the
 * store's USDC token account. `reference` is a fresh address for this order,
 * added as a read-only account so the backend can tell which order a
 * transaction pays for (the Solana Pay convention).
 */
export async function payStore(
  customer: TransactionSigner,
  order: { storeOwner: Address; amount: bigint; reference: Address },
) {
  const [source] = await findAssociatedTokenPda({
    owner: customer.address,
    mint: USDC_MINT,
    tokenProgram: TOKEN_PROGRAM_ADDRESS,
  });
  const [destination] = await findAssociatedTokenPda({
    owner: order.storeOwner,
    mint: USDC_MINT,
    tokenProgram: TOKEN_PROGRAM_ADDRESS,
  });

  const transfer = getTransferCheckedInstruction({
    source,
    mint: USDC_MINT,
    destination,
    authority: customer,
    amount: order.amount,
    decimals: USDC_DECIMALS,
  });
  const transferWithReference = {
    ...transfer,
    accounts: [
      ...transfer.accounts,
      { address: order.reference, role: AccountRole.READONLY },
    ],
  };

  const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
  const message = pipe(
    createTransactionMessage({ version: 0 }),
    (m) => setTransactionMessageFeePayerSigner(customer, m),
    (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
    (m) => appendTransactionMessageInstructions([transferWithReference], m),
  );
  const transaction = await signTransactionMessageWithSigners(message);
  assertIsTransactionWithBlockhashLifetime(transaction);
  await sendAndConfirmTransaction(transaction, { commitment: "confirmed" });
  return getSignatureFromTransaction(transaction);
}
```

<div className="sol-term not-prose" data-term="paths/payments/checkout/pay" data-tab="checkout/pay.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">What Node prints for the order and the signature payStore() returns, on a local test network (Surfpool)</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="What Node prints for the order and the signature payStore() returns, on a local test network (Surfpool): Output">
<div className="sol-term-step" data-step="1" data-pending="tx">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> order</div>
<div className="sol-term-row sol-term-ln">\{</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">id\:</span> `'order-1001',`</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">storeOwner\:</span> `'`<span className="sol-h" title="DVxMtF9M6EAQ8CjqH9omYUTXdJU7hu4M8G94udRyr1m6"><span className="sol-h-f">DVxMtF9M6EAQ8CjqH9omYUTXdJU7hu4M8G94udRyr1m6</span><span className="sol-h-s" aria-hidden="true">DVxM…r1m6</span></span>`',`</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">amount\:</span> 1000000n,</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">reference\:</span> `'`<span className="sol-h" title="47venn787GZLWUcgUU3QM1CpT11JHQMs8hyYQMPXKN2W"><span className="sol-h-f">47venn787GZLWUcgUU3QM1CpT11JHQMs8hyYQMPXKN2W</span><span className="sol-h-s" aria-hidden="true">47ve…KN2W</span></span>`'`</div>
<div className="sol-term-row sol-term-ln">\}</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> const signature = await payStore(customer, order)</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> signature</div>
<div className="sol-term-row sol-term-ln">`'`<span className="sol-h" title="paxK3zbseZEZpGrmGrzm3p3VYF5XN6aTAGKS1sVt2CmkcJ2afLCTB5C84rFT8VFX6LboNFty2pzcTCiVJw5DAtJ"><span className="sol-h-f">paxK3zbseZEZpGrmGrzm3p3VYF5XN6aTAGKS1sVt2CmkcJ2afLCTB5C84rFT8VFX6LboNFty2pzcTCiVJw5DAtJ</span><span className="sol-h-s" aria-hidden="true">paxK…DAtJ</span></span>`'`</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="info">Payment sent · not verified yet</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

## 2. Verify a payment

Given the signature and the order, fetch the transaction and check three
things: it succeeded, it carries the order's reference, and the store's USDC
balance went up by exactly the order amount. The balance is read for the USDC
mint only, so a payment in any other token doesn't count. Save this as
`checkout/verify-payment.ts`:

```ts checkout/verify-payment.ts
import type { Address, Signature } from "@solana/kit";
import { rpc } from "./config";

export type PaymentCheck = { paid: true } | { paid: false; reason: string };

/**
 * Confirm on your server that `signature` paid this order: the transaction
 * succeeded, it carries the order's reference, and the store's token account
 * for `mint` received exactly `amount` base units. Never trust the browser's
 * word for it.
 */
export async function verifyPayment(order: {
  signature: Signature;
  storeOwner: Address;
  mint: Address;
  amount: bigint;
  reference?: Address;
}): Promise<PaymentCheck> {
  const tx = await rpc
    .getTransaction(order.signature, {
      commitment: "confirmed",
      encoding: "jsonParsed",
      maxSupportedTransactionVersion: 0,
    })
    .send();
  if (!tx) return { paid: false, reason: "transaction not found" };
  if (tx.meta?.err) return { paid: false, reason: "transaction failed" };

  const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey);
  if (order.reference && !keys.includes(order.reference)) {
    return { paid: false, reason: "reference not found" };
  }

  // What the store's token account for this mint held before and after.
  type TokenBalances = NonNullable<typeof tx.meta>["preTokenBalances"];
  const balance = (list: TokenBalances) =>
    BigInt(
      list?.find((b) => b.owner === order.storeOwner && b.mint === order.mint)
        ?.uiTokenAmount.amount ?? "0",
    );
  const received =
    balance(tx.meta?.postTokenBalances) - balance(tx.meta?.preTokenBalances);
  if (received !== order.amount) {
    return {
      paid: false,
      reason: `amount mismatch: expected ${order.amount}, received ${received}`,
    };
  }
  return { paid: true };
}
```

<div className="sol-term not-prose" data-term="paths/payments/checkout/verify" data-tab="checkout/verify-payment.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Output of verifyPayment() with the right and a wrong amount</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Output of verifyPayment() with the right and a wrong amount: Output">
<div className="sol-term-step" data-step="1" data-pending="call">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> `await verifyPayment({ ...order, signature, mint: USDC_MINT })`</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">\{ paid\: true \}</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> `await verifyPayment({ ...order, amount: 2_000_000n, signature, mint: USDC_MINT })`</div>
<div className="sol-term-row sol-term-ln">\{</div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">paid\:</span> false,</div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">reason\:</span> `'amount mismatch: expected 2000000, received 1000000'`</div>
<div className="sol-term-row sol-term-ln">\}</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="ok">Right amount\: paid</span><span className="sol-term-badge" data-tone="error">Wrong amount\: refused</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

The check asks for the transaction at `confirmed` commitment:

<div className="sol-concept not-prose">
[<span className="sol-concept-name">Confirmation & finality</span> <span className="sol-concept-def">A transaction goes from processed to finalized in well under a second, and once finalized it can't be reversed.</span>](/developers/docs/core/transactions/confirmation)
</div>

## 3. Add a confirm endpoint

The endpoint looks the order up, so it needs somewhere to keep orders. This
in-memory store stands in for your database. Save it as `checkout/orders.ts`:

```ts checkout/orders.ts
// An in-memory order store standing in for your database. A real store
// persists orders and paid signatures.
import type { Address, Signature } from "@solana/kit";

export interface Order {
  id: string;
  storeOwner: Address;
  amount: bigint;
  reference: Address;
}

const orders = new Map<string, Order>();
const paidSignatures = new Set<string>();
const paidOrders = new Map<string, Signature>();

export async function createOrder(order: Order): Promise<Order> {
  orders.set(order.id, order);
  return order;
}

export async function getOrder(id: string): Promise<Order | undefined> {
  return orders.get(id);
}

/**
 * Marks the order paid by this signature. Returns false (and records
 * nothing) if the signature was already used for any order, or if the order
 * is unknown or already paid by another signature. In a database, do this in
 * one transaction with unique constraints on the signature and on the order's
 * paid signature, so two concurrent requests cannot both succeed.
 */
export async function markPaidOnce(
  orderId: string,
  signature: Signature,
): Promise<boolean> {
  if (paidSignatures.has(signature)) return false;
  if (!orders.has(orderId) || paidOrders.has(orderId)) return false;
  paidSignatures.add(signature);
  paidOrders.set(orderId, signature);
  return true;
}

export async function isSignatureUsed(signature: Signature): Promise<boolean> {
  return paidSignatures.has(signature);
}
```

In production, make `markPaidOnce` a single database transaction with a unique
constraint on the signature and on each order's paid signature, so two
concurrent requests can't both succeed.

The endpoint receives `{ "signature": "…" }` for an order, runs
`verifyPayment`, and marks the order paid. It refuses a signature that was
already used, so one payment can't pay for two orders. Save the Node.js version
as `checkout/server.ts`. It uses no framework, so the handler ports directly to
Express, Fastify, or Hono. The Next.js tab is the same handler as an App Router
route: save it at `app/api/orders/[orderId]/confirm/route.ts` and point its
imports at your `config`, `orders`, and `verify-payment` files.

<Tabs>
<Tab title="checkout/server.ts (Node.js)">
<div className="sol-tab-label">checkout/server.ts (Node.js)</div>

```ts
// A framework-free Node.js server (node:http). The same handler body works in
// Express, Fastify or Hono: read the signature, verify it, mark it used.
import { createServer, type IncomingMessage } from "node:http";
import { signature as toSignature } from "@solana/kit";
import { USDC_MINT } from "./config";
import { getOrder, isSignatureUsed, markPaidOnce } from "./orders";
import { verifyPayment } from "./verify-payment";

export function createCheckoutServer() {
  return createServer(async (req, res) => {
    const send = (status: number, body: unknown) => {
      res.writeHead(status, { "content-type": "application/json" });
      res.end(JSON.stringify(body));
    };
    try {
      await handle(req, send);
    } catch (err) {
      // A database or RPC failure: answer 500, keep the server running.
      console.error("confirm error", err);
      if (!res.headersSent)
        send(500, { error: "could not confirm payment, try again" });
    }
  });
}

async function handle(
  req: IncomingMessage,
  send: (status: number, body: unknown) => void,
) {
  const match = req.url?.match(/^\/api\/orders\/([^/]+)\/confirm$/);
  if (req.method !== "POST" || !match) return send(404, { error: "not found" });

  let orderId: string;
  try {
    orderId = decodeURIComponent(match[1]!);
  } catch {
    return send(400, { error: "invalid order id" });
  }
  const order = await getOrder(orderId);
  if (!order) return send(404, { error: "unknown order" });

  let raw = "";
  for await (const chunk of req) raw += chunk;
  let signature;
  try {
    signature = toSignature(
      (JSON.parse(raw) as { signature?: string }).signature ?? "",
    );
  } catch {
    return send(400, { error: "invalid signature" });
  }
  if (await isSignatureUsed(signature)) {
    return send(402, { paid: false, reason: "already used" });
  }

  const check = await verifyPayment({
    signature,
    storeOwner: order.storeOwner,
    mint: USDC_MINT,
    amount: order.amount,
    reference: order.reference,
  });
  if (!check.paid) return send(402, check);
  if (!(await markPaidOnce(order.id, signature))) {
    return send(402, { paid: false, reason: "already used" });
  }
  send(200, { paid: true, orderId: order.id, signature });
}
```

</Tab>
<Tab title="Next.js route.ts">
<div className="sol-tab-label">Next.js route.ts</div>

```ts
// app/api/orders/[orderId]/confirm/route.ts (Next.js App Router)
import { signature as toSignature } from "@solana/kit";
import { USDC_MINT } from "./config";
import { getOrder, isSignatureUsed, markPaidOnce } from "./orders";
import { verifyPayment } from "./verify-payment";

export async function POST(
  request: Request,
  { params }: { params: Promise<{ orderId: string }> },
): Promise<Response> {
  const { orderId } = await params;
  const order = await getOrder(orderId);
  if (!order) return Response.json({ error: "unknown order" }, { status: 404 });

  let signature;
  try {
    const body = (await request.json()) as { signature?: string } | null;
    signature = toSignature(body?.signature ?? "");
  } catch {
    return Response.json({ error: "invalid signature" }, { status: 400 });
  }
  if (await isSignatureUsed(signature)) {
    return Response.json(
      { paid: false, reason: "already used" },
      { status: 402 },
    );
  }

  const check = await verifyPayment({
    signature,
    storeOwner: order.storeOwner,
    mint: USDC_MINT,
    amount: order.amount,
    reference: order.reference,
  });
  if (!check.paid) return Response.json(check, { status: 402 });

  if (!(await markPaidOnce(order.id, signature))) {
    return Response.json(
      { paid: false, reason: "already used" },
      { status: 402 },
    );
  }
  return Response.json({ paid: true, orderId: order.id, signature });
}
```

<div className="sol-term not-prose" data-term="paths/payments/checkout/route" data-tab="Next.js route.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">A confirmed order, a reused signature and an underpaid order</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="A confirmed order, a reused signature and an underpaid order: Output">
<div className="sol-term-step" data-step="1" data-pending="http">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> `await fetch("/api/orders/order-1002/confirm", { method: "POST", body: JSON.stringify({ signature }) })`</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">POST /api/orders/order-1002/confirm -\> <span className="sol-term-code" data-code="2xx">200</span> `{"paid":true,"orderId":"order-1002","signature":"`<span className="sol-h" title="uA4RPaYQdWY7km3ayXA1tWY8aMRJf5e5BtZMmF8yo9oGR1xBphtQmkyQUftSGwScHneW6cdb2GQZJgC4xCyu6jF"><span className="sol-h-f">uA4RPaYQdWY7km3ayXA1tWY8aMRJf5e5BtZMmF8yo9oGR1xBphtQmkyQUftSGwScHneW6cdb2GQZJgC4xCyu6jF</span><span className="sol-h-s" aria-hidden="true">uA4R…u6jF</span></span>`"}`</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> `await fetch("/api/orders/order-1002/confirm", { method: "POST", body: JSON.stringify({ signature }) })`</div>
<div className="sol-term-row sol-term-ln" data-tone="error">POST /api/orders/order-1002/confirm -\> <span className="sol-term-code" data-code="4xx">402</span> `{"paid":false,"reason":"already used"}`</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> `await fetch("/api/orders/order-1003/confirm", { method: "POST", body: JSON.stringify({ signature: underpaid }) })`</div>
<div className="sol-term-row sol-term-ln" data-tone="error">POST /api/orders/order-1003/confirm -\> <span className="sol-term-code" data-code="4xx">402</span> `{"paid":false,"reason":"amount mismatch: expected 2000000, received 1000000"}`</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="ok">200 Paid</span><span className="sol-term-badge" data-tone="error">402 Already used</span><span className="sol-term-badge" data-tone="error">402 Amount mismatch</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

</Tab>
</Tabs>

<Note>
  `reference` is optional in `verifyPayment`, but keep it. Transactions are
  public, so without it anyone who sees a payment to your store could submit
  its signature for their own order of the same amount. If your checkout can't
  attach a reference, also check who paid, for example that the signer is the
  customer's wallet.
</Note>

The output shows the three cases your endpoint must handle:

- **200** for a confirmed payment of the right amount.
- **402 `already used`** when the same signature is sent again.
- **402 `amount mismatch`** when a 2 USDC order was paid with 1 USDC.

## 4. Call it from the checkout

Build the customer's payment with `payStore`, which attaches the order's
reference that this endpoint requires.

1. When the customer checks out, create the order on your server with a fresh
   reference (`(await generateKeyPairSigner()).address`) and send the order's
   `storeOwner`, `amount`, and `reference` to the browser.
2. In the browser, call `payStore(customer, order)`, where `customer` is the
   wallet's `TransactionSigner` (for example from
   `useWalletAccountTransactionSigner` in
   [`@solana/react`](/developers/docs/clients/official/javascript)). It resolves to the transaction signature once the payment is
   confirmed.
3. `POST` that signature to `/api/orders/<order-id>/confirm` with a JSON body
   of `{ "signature": "…" }`.

Show the confirmation page only when the response is `200` with
`"paid": true`. Treat any other response as unpaid, and let the customer
retry.

<Warning>
  The QR code component from step 2 makes its own reference in the browser, so
  `verifyPayment` answers `reference not found` for its payments and the
  endpoint returns `402`. To confirm QR code payments, give `encodeURL` and
  `watchReference` the order's `reference` from your server, then post the
  signature that `watchReference` returns.
</Warning>

## 5. Run it on your machine

You now have five files in `checkout/`: `config.ts`, `pay.ts`,
`verify-payment.ts`, `orders.ts`, and `server.ts`. This script plays both
sides: it starts the server on port 3000, creates a store wallet and its USDC
account, creates order `order-1001` for 1 USDC, pays it as the customer with
`payStore`, and posts the signature to the confirm endpoint twice. Save it as
`checkout/run.ts`:

```ts checkout/run.ts
// checkout/run.ts: start the confirm server, pay an order as a customer, and
// confirm the payment through the endpoint, twice.
//   npx tsx checkout/run.ts
// The customer key is read from CUSTOMER_KEYPAIR, or from the Solana CLI
// default ~/.config/solana/id.json. It needs SOL for fees and 1 USDC.
import { readFile } from "node:fs/promises";
import type { AddressInfo } from "node:net";
import { homedir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import {
  appendTransactionMessageInstructions,
  assertIsTransactionWithBlockhashLifetime,
  createKeyPairSignerFromBytes,
  createTransactionMessage,
  generateKeyPairSigner,
  pipe,
  sendAndConfirmTransactionFactory,
  setTransactionMessageFeePayerSigner,
  setTransactionMessageLifetimeUsingBlockhash,
  signTransactionMessageWithSigners,
  type Address,
  type Signature,
  type TransactionSigner,
} from "@solana/kit";
import {
  findAssociatedTokenPda,
  getCreateAssociatedTokenIdempotentInstruction,
  TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
import { rpc, rpcSubscriptions, USDC_MINT } from "./config";
import { createOrder, type Order } from "./orders";
import { payStore } from "./pay";
import { createCheckoutServer } from "./server";

/** Create `owner`'s USDC account if it doesn't exist yet; `payer` pays. */
export async function createUsdcAccount(
  payer: TransactionSigner,
  owner: Address,
) {
  const [ata] = await findAssociatedTokenPda({
    owner,
    mint: USDC_MINT,
    tokenProgram: TOKEN_PROGRAM_ADDRESS,
  });
  const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
  const message = pipe(
    createTransactionMessage({ version: 0 }),
    (m) => setTransactionMessageFeePayerSigner(payer, m),
    (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
    (m) =>
      appendTransactionMessageInstructions(
        [
          getCreateAssociatedTokenIdempotentInstruction({
            payer,
            ata,
            owner,
            mint: USDC_MINT,
          }),
        ],
        m,
      ),
  );
  const transaction = await signTransactionMessageWithSigners(message);
  assertIsTransactionWithBlockhashLifetime(transaction);
  await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(
    transaction,
    { commitment: "confirmed" },
  );
  return ata;
}

export async function run(
  customer: TransactionSigner,
  port = 3000,
): Promise<{
  order: Order;
  signature: Signature;
  store: Address;
  results: number[];
}> {
  const server = createCheckoutServer();
  await new Promise<void>((resolve, reject) =>
    server.once("error", reject).listen(port, resolve),
  );
  const { port: listening } = server.address() as AddressInfo;
  try {
    // The store's wallet. Use your own address in a real store. Its USDC
    // account must exist before it can receive USDC.
    const store = await generateKeyPairSigner();
    const storeUsdc = await createUsdcAccount(customer, store.address);
    console.log("Store wallet:", store.address, "USDC account:", storeUsdc);

    // Your server creates the order with a fresh reference...
    const order = await createOrder({
      id: "order-1001",
      storeOwner: store.address,
      amount: 1_000_000n, // 1 USDC
      reference: (await generateKeyPairSigner()).address,
    });
    // ...the customer pays it...
    const signature = await payStore(customer, order);
    const tx = await rpc
      .getTransaction(signature, {
        commitment: "confirmed",
        encoding: "json",
        maxSupportedTransactionVersion: 0,
      })
      .send();
    console.log(
      `Paid ${order.id}: ${Number(order.amount) / 1e6} USDC (${order.amount} base units)`,
    );
    console.log("Reference:", order.reference);
    console.log("Signature:", signature);
    console.log("Fee:", String(tx?.meta?.fee), "lamports");

    // ...and the checkout posts the signature to the confirm endpoint. The
    // second post reuses the signature and is refused.
    const results: number[] = [];
    for (let i = 0; i < 2; i++) {
      const res = await fetch(
        `http://localhost:${listening}/api/orders/${order.id}/confirm`,
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ signature }),
        },
      );
      const body = await res.text();
      console.log(`POST /api/orders/${order.id}/confirm ->`, res.status, body);
      results.push(res.status);
    }
    return { order, signature, store: store.address, results };
  } finally {
    server.close();
    server.closeAllConnections();
  }
}

// Run when started directly (not when imported by the tests).
if (
  process.argv[1] &&
  import.meta.url === pathToFileURL(process.argv[1]).href
) {
  const keyPath =
    process.env.CUSTOMER_KEYPAIR ??
    join(homedir(), ".config", "solana", "id.json");
  const bytes = new Uint8Array(JSON.parse(await readFile(keyPath, "utf8")));
  await run(
    await createKeyPairSignerFromBytes(bytes),
    Number(process.env.PORT ?? 3000),
  );
}
```

<div className="sol-term not-prose" data-term="paths/payments/checkout/run" data-tab="checkout/run.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Output of npx tsx checkout/run.ts</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Output of npx tsx checkout/run.ts: Output">
<div className="sol-term-step" data-step="1" data-pending="http">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\$</span> npx tsx checkout/run.ts</div>
<div className="sol-term-row sol-term-ln">Store wallet\: <span className="sol-h" title="DVxMtF9M6EAQ8CjqH9omYUTXdJU7hu4M8G94udRyr1m6"><span className="sol-h-f">DVxMtF9M6EAQ8CjqH9omYUTXdJU7hu4M8G94udRyr1m6</span><span className="sol-h-s" aria-hidden="true">DVxM…r1m6</span></span> USDC account\: <span className="sol-h" title="5iE6nCcXGFAXzQRrBCPbFaNm8hXVBPkndqutjJKyVr9S"><span className="sol-h-f">5iE6nCcXGFAXzQRrBCPbFaNm8hXVBPkndqutjJKyVr9S</span><span className="sol-h-s" aria-hidden="true">5iE6…Vr9S</span></span></div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Paid order-1001\: 1 USDC (1000000 base units)</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Reference\:</span> <span className="sol-h" title="47venn787GZLWUcgUU3QM1CpT11JHQMs8hyYQMPXKN2W"><span className="sol-h-f">47venn787GZLWUcgUU3QM1CpT11JHQMs8hyYQMPXKN2W</span><span className="sol-h-s" aria-hidden="true">47ve…KN2W</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="paxK3zbseZEZpGrmGrzm3p3VYF5XN6aTAGKS1sVt2CmkcJ2afLCTB5C84rFT8VFX6LboNFty2pzcTCiVJw5DAtJ"><span className="sol-h-f">paxK3zbseZEZpGrmGrzm3p3VYF5XN6aTAGKS1sVt2CmkcJ2afLCTB5C84rFT8VFX6LboNFty2pzcTCiVJw5DAtJ</span><span className="sol-h-s" aria-hidden="true">paxK…DAtJ</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Fee\:</span> 5000 lamports</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">POST /api/orders/order-1001/confirm -\> <span className="sol-term-code" data-code="2xx">200</span> `{"paid":true,"orderId":"order-1001","signature":"`<span className="sol-h" title="paxK3zbseZEZpGrmGrzm3p3VYF5XN6aTAGKS1sVt2CmkcJ2afLCTB5C84rFT8VFX6LboNFty2pzcTCiVJw5DAtJ"><span className="sol-h-f">paxK3zbseZEZpGrmGrzm3p3VYF5XN6aTAGKS1sVt2CmkcJ2afLCTB5C84rFT8VFX6LboNFty2pzcTCiVJw5DAtJ</span><span className="sol-h-s" aria-hidden="true">paxK…DAtJ</span></span>`"}`</div>
<div className="sol-term-row sol-term-ln" data-tone="error">POST /api/orders/order-1001/confirm -\> <span className="sol-term-code" data-code="4xx">402</span> `{"paid":false,"reason":"already used"}`</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="ok">Paid · 200</span><span className="sol-term-badge" data-tone="error">Reused signature · 402</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

The script pays as the customer with a key file: the one named in
`CUSTOMER_KEYPAIR`, or the Solana CLI default `~/.config/solana/id.json`. If
you don't have one yet, save this as `keygen.ts` in `solana-payments`. It
writes a new key file in the same format and prints its address:

```ts keygen.ts
import { generateKeyPairSync } from "node:crypto";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { createKeyPairSignerFromBytes } from "@solana/kit";

// Writes a new key file in the Solana CLI format (64 bytes as a JSON array).
const keyPath = join(homedir(), ".config", "solana", "id.json");
if (existsSync(keyPath)) throw new Error(`${keyPath} exists; not overwriting it`);
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
const bytes = new Uint8Array([
  ...privateKey.export({ format: "der", type: "pkcs8" }).subarray(-32),
  ...publicKey.export({ format: "der", type: "spki" }).subarray(-32),
]);
mkdirSync(dirname(keyPath), { recursive: true });
writeFileSync(keyPath, JSON.stringify([...bytes]), { mode: 0o600 });
console.log(`Address: ${(await createKeyPairSignerFromBytes(bytes)).address}`);
```

```bash Terminal
npx tsx keygen.ts
```

The key file is a private key. Keep it out of version control.

The customer needs SOL for fees and at least 1 USDC on the same USDC mint the
code uses. Pick a network:

<Tabs>
<Tab title="Local (Surfpool)">

1. Install the [Surfpool CLI](/developers/docs/tools/surfpool/toolchain/getting-started)
   and start a local network that copies accounts from devnet, so the devnet
   USDC mint the code uses exists locally. It airdrops SOL to
   `~/.config/solana/id.json` when it starts (create the key file first):

   ```bash Terminal
   surfpool start --network devnet
   ```

2. In another terminal, in `solana-payments`, give the customer 10 test USDC
   with Surfpool's
   [`surfnet_setTokenAccount`](/developers/docs/tools/surfpool/rpc/cheatcodes)
   cheatcode. Replace `<customer address>` with the address of your key file:

   ```bash Terminal
   curl http://127.0.0.1:8899 -s -X POST -H "Content-Type: application/json" -d '
     {"jsonrpc": "2.0", "id": 1, "method": "surfnet_setTokenAccount",
      "params": ["<customer address>", "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
                 {"amount": 10000000, "state": "initialized"},
                 "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"]}'
   ```

3. Point the code at Surfpool:

   ```bash Terminal
   export RPC_URL=http://127.0.0.1:8899
   export RPC_SUBSCRIPTIONS_URL=ws://127.0.0.1:8900
   ```

</Tab>
<Tab title="Devnet">

Leave `RPC_URL` and `RPC_SUBSCRIPTIONS_URL` unset. Paste the customer's
address into the [Solana Faucet](https://faucet.solana.com/) for devnet SOL,
and into [Circle's faucet](https://faucet.circle.com/) with **Solana Devnet**
selected for devnet USDC.

</Tab>
</Tabs>

Then run the script:

```bash Terminal
npx tsx checkout/run.ts
```

Expect the output shown under the script, with your own addresses and
signatures: `200` with `"paid": true` for the payment, then `402` with
`already used` for the same signature sent again. Each run creates a new store
wallet, so you can run it as often as the customer has USDC.

<Note>
  Port 3000 in use? Set another one for the run, for example
  `PORT=3001 npx tsx checkout/run.ts`.
</Note>

### Run the tests instead

The code on this page and its tests live in the docs repository under
`packages/docs-examples/paths/payments/checkout`. The test starts its own
Surfpool network and funds a test customer, so you need no Surfpool CLI, keys,
SOL, or USDC. It also checks that `verifyPayment` rejects a wrong amount, mint,
recipient, or reference:

```bash Terminal
git clone https://github.com/solana-foundation/solana-com.git
cd solana-com
corepack enable
pnpm install
pnpm --filter @workspace/docs-examples exec vitest run paths/payments/checkout
```

<Note>
  The full example is in
  [`packages/docs-examples/paths/payments/checkout`](https://github.com/solana-foundation/solana-com/tree/main/packages/docs-examples/paths/payments/checkout).
</Note>
