---
name: x402-paywall
description: Add x402 pay-per-request payments (USDC, settled on-chain) to an existing HTTP API — Express, Hono, Next.js or FastAPI — using the DeepNexus facilitator. Use when the user wants to charge agents or users per API call without accounts or API keys.
---

# x402 paywall

Goal: selected routes answer `402 Payment Required` with payment requirements until the client retries with a valid `X-PAYMENT` header; then the facilitator verifies and settles the payment and the route runs normally.

## 1. Collect

- Which routes, and the price of each (in USD, e.g. `$0.01`).
- The receiving wallet (`payTo`) — an address the user controls. Never generate or store a private key for receiving.
- Network: `base` (recommended, cheap gas) or another network listed by `GET http://localhost:3000/x402/supported`.
- A facilitator key (`fk_…`) from the DeepNexus Facilitator console, stored as `DEEPNEXUS_FACILITATOR_KEY` in the environment.

## 2. Express / Node

```bash
npm install x402-express
```

```js
import { paymentMiddleware } from "x402-express";

const facilitator = {
  url: "http://localhost:3000/x402",
  createAuthHeaders: async () => {
    const h = { Authorization: `Bearer ${process.env.DEEPNEXUS_FACILITATOR_KEY}` };
    return { verify: h, settle: h, supported: {} };
  },
};

app.use(
  paymentMiddleware(
    process.env.PAY_TO,
    {
      "GET /api/forecast": { price: "$0.01", network: "base", config: { description: "7-day forecast" } },
      "POST /api/summarize": { price: "$0.05", network: "base" },
    },
    facilitator,
  ),
);
```

Register the middleware **before** the routes it protects. For Hono use `x402-hono`, for Next.js `x402-next` (middleware.ts) — same arguments.

## 3. Other frameworks (manual)

1. If the request has no `X-PAYMENT` header, return `402` with `{"x402Version":1,"accepts":[requirements],"error":"X-PAYMENT header is required"}`. For USDC on Base: `asset` `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`, `extra` `{"name":"USD Coin","version":"2"}`, `maxAmountRequired` in 6-decimal units (`$0.01` → `"10000"`).
2. Otherwise base64-decode the header to `paymentPayload` and `POST {url}/verify` with `{x402Version:1, paymentPayload, paymentRequirements}`. If `isValid` is false, return `402` with `error: invalidReason`.
3. Run the handler. Only if it succeeds, `POST {url}/settle` with the same body. On success add header `X-PAYMENT-RESPONSE: base64(JSON settle response)`.

## 4. Test

```bash
curl -i https://localhost:3000/api/forecast   # expect 402 and an "accepts" array
```

Then pay with an x402 client (see the `x402-client` skill) using a funded test wallet, and confirm the settlement hash on the block explorer.

## Pitfalls

- Price strings are USD; the middleware converts to token units. In manual mode, mind decimals.
- Settle after the work succeeds, so clients are never charged for errors.
- `maxTimeoutSeconds` must cover your handler's latency plus settlement (60s is a good default).
