Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.x402.org/llms.txt

Use this file to discover all available pages before exploring further.

Note: This quickstart begins with testnet configuration for safe testing. When you’re ready for production, see Running on Mainnet for the simple changes needed to accept real payments on Base (EVM) and Solana networks.

Prerequisites

Before you begin, ensure you have:
  • A crypto wallet to receive funds (any EVM or SVM compatible wallet)
  • Node.js and npm, Go, or Python and pip installed
  • An existing API or server
Note
There are pre-configured examples available in the x402 repo for both Node.js and Go. There is also an advanced example that shows how to use the x402 SDKs to build a more complex payment flow.

1. Install Dependencies

Install the x402 Express middleware package.
npm install @x402/express @x402/core @x402/evm @x402/svm @x402/avm

2. Add Payment Middleware

Integrate the payment middleware into your application. You will need to provide:
  • The Facilitator URL or facilitator client. For testing, use https://x402.org/facilitator which works on Base Sepolia and Solana devnet.
  • The routes you want to protect.
  • Your receiving wallet address.
Full example in the repo here.
import express from "express";
import { paymentMiddleware, x402ResourceServer } from "@x402/express";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { ExactSvmScheme } from "@x402/svm/exact/server";
import { ExactAvmScheme } from "@x402/avm/exact/server";
import { HTTPFacilitatorClient } from "@x402/core/server";

const app = express();

// Your receiving wallet addresses
const evmAddress = "0xYourEvmAddress";
const svmAddress = "YourSolanaAddress";
const avmAddress = "YourAlgorandAddress";

// Create facilitator client (testnet)
const facilitatorClient = new HTTPFacilitatorClient({
  url: "https://x402.org/facilitator"
});

app.use(
  paymentMiddleware(
    {
      "GET /weather": {
        accepts: [
          {
            scheme: "exact",
            price: "$0.001",
            network: "eip155:84532", // Base Sepolia
            payTo: evmAddress,
          },
          {
            scheme: "exact",
            price: "$0.001",
            network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", // Solana Devnet
            payTo: svmAddress,
          },
          {
            scheme: "exact",
            price: "$0.001",
            network: "algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=", // Algorand Testnet
            payTo: avmAddress,
          },
        ],
        description: "Weather data",
        mimeType: "application/json",
      },
    },
    new x402ResourceServer(facilitatorClient)
      .register("eip155:84532", new ExactEvmScheme())
      .register("solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", new ExactSvmScheme())
      .register("algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=", new ExactAvmScheme()),
  ),
);

app.get("/weather", (req, res) => {
  res.send({
    report: {
      weather: "sunny",
      temperature: 70,
    },
  });
});

app.listen(4021, () => {
  console.log(`Server listening at http://localhost:4021`);
});
Route Configuration Interface:
interface RouteConfig {
  accepts: Array<{
    scheme: string;           // Payment scheme: "exact" or "upto"
    price: string;            // For "exact": the fixed price. For "upto": the maximum authorized amount.
    network: string;          // Network in CAIP-2 format (e.g., "eip155:84532" or "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1")
    payTo: string;            // Your wallet address
  }>;
  description?: string;       // Description of the resource
  mimeType?: string;          // MIME type of the response
  extensions?: object;        // Optional extensions (e.g., Bazaar)
}
When a request is made to these routes without payment, your server will respond with the HTTP 402 Payment Required code and payment instructions.

Payment Schemes: Exact vs Upto

x402 supports two payment schemes that control how charges are calculated: exact (default) — The client pays the exact advertised price. This is the simplest scheme and works across all networks (EVM, SVM, Stellar, Aptos) and all SDKs (TypeScript, Go, Python). Best for fixed-price endpoints where the cost is known upfront. upto — The client authorizes a maximum amount, but the server settles only what was actually used. This enables usage-based billing where the final charge depends on work performed (LLM token count, compute time, bytes served, etc.). Currently available on EVM networks only (Permit2), in TypeScript, Go, and Python SDKs. The examples in step 2 above all use the exact scheme. To use upto instead, there are two key differences:
  1. Set scheme: "upto" in your route config, where price becomes the maximum the client authorizes
  2. Call setSettlementOverrides in your handler to specify the actual amount to charge
Full example in the repo here.
import express from "express";
import { paymentMiddleware, setSettlementOverrides, x402ResourceServer } from "@x402/express";
import { UptoEvmScheme } from "@x402/evm/upto/server";
import { HTTPFacilitatorClient } from "@x402/core/server";

const app = express();
const evmAddress = "0xYourEvmAddress";

const facilitatorClient = new HTTPFacilitatorClient({
  url: "https://x402.org/facilitator"
});

const maxPrice = "$0.10"; // Maximum the client authorizes (10 cents)

app.use(
  paymentMiddleware(
    {
      "GET /api/generate": {
        accepts: {
          scheme: "upto",
          price: maxPrice,
          network: "eip155:84532", // Base Sepolia
          payTo: evmAddress,
        },
        description: "AI text generation — billed by token usage",
        mimeType: "application/json",
      },
    },
    new x402ResourceServer(facilitatorClient)
      .register("eip155:84532", new UptoEvmScheme()),
  ),
);

app.get("/api/generate", (req, res) => {
  // Simulate variable-cost work (LLM tokens, compute time, etc.)
  const maxAmountAtomic = 100000; // 10 cents in 6-decimal USDC atomic units
  const actualUsage = Math.floor(Math.random() * (maxAmountAtomic + 1));

  // Settle only the actual usage — the client is never charged more than this
  setSettlementOverrides(res, { amount: String(actualUsage) });

  res.json({
    result: "Here is your generated text...",
    usage: {
      authorizedMaxAtomic: String(maxAmountAtomic),
      actualChargedAtomic: String(actualUsage),
    },
  });
});

app.listen(4021, () => {
  console.log("Server listening at http://localhost:4021");
});
The setSettlementOverrides amount supports three formats:
  • Raw atomic units — e.g., "1000" settles exactly 1,000 atomic units of the token (for USDC with 6 decimals, "1000" = $0.001)
  • Percentage of authorized maximum — e.g., "50%" settles 50% of PaymentRequirements.amount. Supports up to two decimal places (e.g., "33.33%"). The result is floored to the nearest atomic unit.
  • Dollar price — e.g., "$0.05" converts a USD-denominated price to atomic units. This format works when you configured your route with $-prefixed pricing (e.g., price: "$0.10"). Token decimals are determined from the registered scheme. The result is rounded to the nearest atomic unit.
The resolved amount must always be <= the authorized maximum. If the amount is "0", no on-chain transaction occurs and the client is not charged.

3. Test Your Integration

To verify:
  1. Make a request to your endpoint (e.g., curl http://localhost:4021/weather).
  2. The server responds with a 402 Payment Required, including payment instructions in the PAYMENT-REQUIRED header.
  3. Complete the payment using a compatible client, wallet, or automated agent. This typically involves signing a payment payload, which is handled by the client SDK detailed in the Quickstart for Buyers.
  4. Retry the request, this time including the PAYMENT-SIGNATURE header containing the cryptographic proof of payment.
  5. The server verifies the payment via the facilitator and, if valid, returns your actual API response (e.g., { "data": "Your paid API response." }).
When using a facilitator that supports the Bazaar extension, your endpoints can be listed in the x402 Bazaar, the discovery layer that helps buyers and AI agents find services. For HTTP endpoints, add the discovery extension to your route config:
import { declareDiscoveryExtension } from "@x402/extensions/bazaar";

{
  "GET /weather": {
    accepts: [{ scheme: "exact", price: "$0.001", network: "eip155:8453", payTo: "0xYourAddress" }],
    description: "Get real-time weather data including temperature, conditions, and humidity",
    mimeType: "application/json",
    extensions: {
      ...declareDiscoveryExtension({
        input: { city: "San Francisco" },
        inputSchema: {
          properties: { city: { type: "string", description: "City name" } },
          required: ["city"],
        },
      }),
    },
  },
}
For MCP tools, pass the discovery extension in your payment wrapper config:
import { createPaymentWrapper } from "@x402/mcp";
import { declareDiscoveryExtension } from "@x402/extensions/bazaar";

const paid = createPaymentWrapper(resourceServer, {
  accepts,
  resource: { url: "mcp://tool/get_weather", description: "Get current weather for a city" },
  extensions: declareDiscoveryExtension({
    toolName: "get_weather",
    description: "Get current weather for a city",
    transport: "sse",
    inputSchema: {
      properties: { city: { type: "string", description: "City name" } },
      required: ["city"],
    },
  }),
});
Learn more about the discovery layer in the Bazaar documentation.

5. Error Handling

  • If you run into trouble, check out the examples in the repo for more context and full code.
  • Run npm install or go mod tidy to install dependencies

Running on Mainnet

Once you’ve tested your integration on testnet, you’re ready to accept real payments on mainnet.

1. Update the Facilitator URL

For mainnet, use a production facilitator. See the x402 Ecosystem for available options. Example using one facilitator:
const facilitatorClient = new HTTPFacilitatorClient({
  url: "https://api.cdp.coinbase.com/platform/v2/x402"
  // url: "https://facilitator.payai.network"  // PayAI Facilitator
});

2. Update Your Network Identifier

Change from testnet to mainnet network identifiers:
// Testnet → Mainnet
network: "eip155:8453", // Base mainnet (was eip155:84532)

3. Register Multiple Schemes (Multi-Network)

For multi-network support, register both EVM and SVM schemes:
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { ExactSvmScheme } from "@x402/svm/exact/server";

const server = new x402ResourceServer(facilitatorClient);
server.register("eip155:*", new ExactEvmScheme());
server.register("solana:*", new ExactSvmScheme());

4. Update Your Wallet

Make sure your receiving wallet address is a real mainnet address where you want to receive USDC payments.

5. Test with Real Payments

Before going live:
  1. Test with small amounts first
  2. Verify payments are arriving in your wallet
  3. Monitor the facilitator for any issues
Warning: Mainnet transactions involve real money. Always test thoroughly on testnet first and start with small amounts on mainnet.

Network Identifiers (CAIP-2)

x402 v2 uses CAIP-2 format for network identifiers:
NetworkCAIP-2 Identifier
Base Mainneteip155:8453
Base Sepoliaeip155:84532
Solana Mainnetsolana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp
Solana Devnetsolana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1
See Network Support for the full list.

Next Steps

  • Check out the Advanced Example for a more complex payment flow
  • Explore Advanced Concepts like lifecycle hooks for custom logic before/after verification/settlement
  • Explore Extensions like Bazaar for service discovery
  • Get started as a buyer
For questions or support, join our Discord.

Summary

This quickstart covered:
  • Installing the x402 SDK and relevant middleware
  • Adding payment middleware to your API and configuring it
  • Choosing between exact (fixed-price) and upto (usage-based) payment schemes
  • Testing your integration
  • Deploying to mainnet with CAIP-2 network identifiers
Your API is now ready to accept crypto payments through x402.