How to Set Up x402 Payments for Your API

Use the FindUtils x402 Config Generator to generate starter payment middleware code in seconds. Select your server framework or client SDK, configure your payment routes, and copy the generated code directly into your project — no manual boilerplate required.

x402 is an open payment protocol by Coinbase that activates the HTTP 402 Payment Required status code for programmatic, on-chain payments. It lets you charge per API call using stablecoins like USDC, with payment requirements carried through an HTTP request flow.

What You Will Learn

  • How to generate x402 server middleware for any framework
  • How to create x402 client code that pays for API access automatically
  • How to configure payment routes, pricing, and blockchain networks
  • How to test on testnet before going to mainnet

Why Monetize APIs with x402?

Traditional API monetization requires setting up Stripe subscriptions, managing API keys, building billing dashboards, and handling failed payments. x402 eliminates all of that. Here is why developers are switching:

  • Zero protocol fees — No middleman taking a percentage of each transaction
  • No signup required — Clients pay per request without creating accounts
  • Sub-second settlement — Payments confirm on-chain in under one second on Base and Solana
  • AI-agent ready — Autonomous agents can discover and pay for APIs programmatically
  • One-line integration — Server middleware handles the entire payment flow

Support depends on the SDK, payment scheme, asset, network, and facilitator. Check the current x402 documentation before installing packages or configuring a paid route. This guide does not state a transaction-volume or settlement-time guarantee.


Step 1: Open the x402 Config Generator

Navigate to the FindUtils x402 Config Generator. You will see two options: Server (Seller) for accepting payments, and Client (Buyer) for paying for API access. Choose the role that matches your use case.

The tool generates complete, copy-paste ready code including import statements, middleware configuration, route handlers, and install commands for your package manager.

Step 2: Configure Your Server Framework

If you selected Server (Seller), choose your framework from the dropdown. The generator supports seven frameworks across three languages:

FrameworkLanguagePackage
Express.jsTypeScript@x402/express
HonoTypeScript@x402/hono
Next.jsTypeScript@x402/next
FastifyTypeScript@x402/fastify
GinGogithub.com/coinbase/x402/go
FastAPIPythonx402[fastapi]
FlaskPythonx402[flask]

Each framework uses x402's middleware pattern: a single function wraps your routes and automatically handles the 402 Payment Required flow.

Step 3: Add Payment Routes

Click Add Route to define which endpoints require payment. For each route, configure:

  • Method — GET, POST, PUT, PATCH, or DELETE
  • Path — The API endpoint path (e.g., /api/weather)
  • Price — Amount in USD (e.g., $0.001 for micropayments or $1.00 for premium endpoints)
  • Scheme — exact for fixed pricing or upto for variable pricing based on consumption
  • Network — The blockchain to settle on (Base Sepolia for testing, Base or Solana for production)
  • Pay To — Your wallet address that receives payments

You can add multiple routes with different prices and networks. The generator creates a complete route configuration object for your chosen framework.

Step 4: Choose Your Blockchain Network

The x402 protocol uses CAIP-2 identifiers for blockchain networks. The generator lists the following network identifiers. A listed identifier does not prove that the selected facilitator supports it:

NetworkCAIP-2 IDUse For
Base Sepoliaeip155:84532Testing (default)
Baseeip155:8453Production (EVM)
Polygoneip155:137Production (low fees)
Avalancheeip155:43114Production (fast)
Solana Devnetsolana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1Testing (Solana)
Solanasolana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpProduction (Solana)

Start with testnet networks for development. The default testnet facilitator at https://x402.org/facilitator must support the selected test network and payment scheme.

Step 5: Enable Extensions (Optional)

The generator supports two x402 extensions:

  • Bazaar — Makes your endpoints discoverable by AI agents and other clients through a global catalog. Enable this if you want autonomous agents to find and pay for your API.
  • Payment Identifier — Adds unique IDs to each payment for idempotency. Enable this if clients might retry failed requests and you need to prevent duplicate charges.

Step 6: Copy the Install Command and Generated Code

The generator outputs two things:

  1. Install command — The exact npm install, pip install, or go get command with all required packages
  2. Generated code — Complete, starter middleware code with imports, configuration, route handlers, and facilitator setup

Copy both into your project. The install command includes only the packages you actually need based on your chosen networks (EVM, Solana, Aptos, or Stellar).

Step 7: Generate Client Code (For Buyers)

Switch to Client (Buyer) mode to generate code that pays for x402-protected APIs. Choose your SDK:

SDKLanguageHow It Works
FetchTypeScriptWraps native fetch() with automatic payment retry
AxiosTypeScriptAdds payment interceptor to Axios instances
GoGoWraps net/http client with payment logic
httpxPythonAsync context manager with auto-payment
requestsPythonSync context manager with auto-payment

Select the networks your target APIs use, and the generator creates signer setup code for each blockchain. The client automatically detects 402 responses, signs the payment, and retries the request — all transparently.


Real-World Use Cases

Micropayment APIs

Charge $0.001 per weather data request, $0.01 per AI inference call, or $0.10 per premium dataset download. x402 makes sub-cent pricing viable because there are no per-transaction fees from the protocol itself.

AI Agent Payments

Autonomous AI agents can discover x402 APIs through the Bazaar extension, evaluate pricing, and pay programmatically without human intervention. This enables machine-to-machine commerce at scale.

Content Paywalls

Protect premium content behind x402 payments. The @x402/paywall package provides a browser-based payment UI for web content, while the middleware handles server-side verification.

API Aggregation Services

Build services that aggregate multiple x402-protected APIs. A single client SDK instance can pay different APIs on different networks only when the SDK and signer support each advertised payment requirement.


Compare payment models by the required workflow

QuestionWhat to check
Per-request paymentHow the server returns payment requirements
Accepted assetsThe scheme, network, token, and facilitator combination
Client authorizationWho can approve a payment and its maximum amount
SettlementFailure, retry, and duplicate-payment behavior
Application accessWhether payment also needs a separate user identity
CostsNetwork and service costs as well as any protocol charges

Generated middleware is a starting point. Payment transport does not remove the need to check authorization, errors, receipts, and application behavior.

Common Mistakes and How to Avoid Them

Mistake 1: Using V1 Package Names

x402 V2 uses scoped packages under @x402/. The old unscoped packages (x402-express, x402-axios) are deprecated. Always use @x402/express, @x402/core, etc. The FindUtils generator outputs V2 code automatically.

Mistake 2: Wrong Network Identifier Format

V2 requires CAIP-2 identifiers like eip155:84532, not human-readable names like base-sepolia. The generator handles this automatically, but if you modify the code manually, use CAIP-2 format.

Mistake 3: Forgetting to Register Schemes

The V2 architecture requires explicitly registering payment schemes for each network family. If you support both EVM and Solana, you need both server.register("eip155:*", new ExactEvmScheme()) and server.register("solana:*", new ExactSvmScheme()). The generator adds the correct registrations based on your route networks.

Mistake 4: Using Mainnet Facilitator on Testnet

The default testnet facilitator (https://x402.org/facilitator) only works with Base Sepolia and Solana Devnet. For production, use a mainnet facilitator like Coinbase CDP's production endpoint. Never mix testnet networks with production facilitators.

Mistake 5: Exposing Private Keys in Code

Client code requires a private key for signing payments, but never hardcode it. Use environment variables (process.env.EVM_PRIVATE_KEY) or a managed wallet service like Coinbase's CDP Wallet API. The generator uses environment variables by default.


Tools Used in This Guide


Verify the generated integration before accepting money

The output is a template, not an executed payment test. Confirm the installed package exports and documented middleware signature. Check that every configured scheme has a registered handler. The current generated EVM and SVM registrations use exact-payment handlers; selecting another scheme does not add a matching implementation automatically.

Use testnet funds for verification. Check an unpaid request, a valid payment, an invalid payment, a repeated request, and a settlement failure. Confirm the recipient and amount before a production release.

FAQ

Q1: What is x402 and how does it work? A: x402 is an open payment protocol that uses the HTTP 402 Payment Required status code for programmatic API payments. When a client requests a protected endpoint, the server returns a 402 response with payment instructions. The client signs a payment with their crypto wallet, retries the request with a payment header, and the server verifies and settles the payment on-chain. The entire flow is handled automatically by x402 middleware.

Q2: Is the x402 Config Generator free to use? A: Yes. The FindUtils x402 Config Generator is available without signup required. It generates code for all 7 supported server frameworks and 5 client SDKs. Processing happens entirely in your browser — nothing is uploaded to servers.

Q3: What should I check before using x402 Config Generator? A: Express.js is the most popular choice for TypeScript servers, with the most examples and community support. For Go, Gin is the primary option. For Python, FastAPI is recommended for async applications and Flask for simpler synchronous servers. The FindUtils x402 Config Generator supports all of them with identical configuration.

Q4: How much does x402 cost to use? A: Check the facilitator and network costs for the selected configuration. This generator does not quote a fee, guarantee free settlement, or calculate the full cost of serving an API request.

Q5: Can AI agents use x402 to pay for APIs? A: Yes. x402 was designed for machine-to-machine payments. AI agents can discover x402-protected APIs through the Bazaar extension, parse payment requirements from 402 responses, sign payments with their wallet, and access paid resources — all without human intervention. The MCP (Model Context Protocol) integration lets Claude Desktop and other AI tools pay for APIs automatically.

Q6: What blockchains does x402 support? A: Support depends on the SDK, payment scheme, asset, network, and facilitator. Check the current x402 documentation for that combination. A network listed in a generator does not prove that its server template has a working payment handler.

Q7: Is x402 safe for production use? A: Yes. Payments are cryptographically signed by the buyer and settled directly on-chain. The facilitator cannot steal funds because it only verifies and submits pre-signed transactions. The protocol has processed over 119 million transactions on Base with roughly $600 million in annualized volume. The codebase is open-source and audited.


Next Steps

  • Try the tool now: Open the x402 Config Generator and generate your first middleware config
  • Test on testnet: Use Base Sepolia (eip155:84532) with the default facilitator — no real tokens needed
  • Explore the protocol: Read the x402 documentation for advanced features like lifecycle hooks, SIWX authentication, and signed offers
  • Generate API docs: Use the API Docs Generator to document your x402-protected endpoints