Code Examples

Learn how to integrate x402 payments into your applications

Client-Side Payment

Making Paid Requests

import { wrapFetchWithPayment } from "x402-fetch";
import { privateKeyToAccount } from "viem/accounts";

// Setup your payment account
const account = privateKeyToAccount(process.env.PRIVATE_KEY);
const fetchWithPay = wrapFetchWithPayment(fetch, account);

// Make a paid request - payment happens automatically
const response = await fetchWithPay("https://api.example.com/premium");
const data = await response.json();

Wrap your fetch calls with wrapFetchWithPayment to automatically handle payments when receiving 402 responses.

Server-Side Protection

Creating Paid Endpoints

import { Hono } from "hono";
import { paymentMiddleware } from "x402-hono";

const app = new Hono();

// Configure payment middleware
app.use(
  paymentMiddleware(
    process.env.SERVER_ADDRESS,
    {
      "/premium-api": {
        price: "$0.50",
        network: "base",
        config: {
          description: "Access to premium API",
        },
      },
    },
    { url: "https://x402.org/facilitator" }
  )
);

// Protected endpoint
app.get("/premium-api", (c) => {
  return c.json({
    message: "Premium content - payment verified!",
  });
});

Use paymentMiddleware to protect your API endpoints and automatically verify payments.

MCP Servers with Paid Tools

Model Context Protocol Integration

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { McpAgent } from "agents/mcp";
import { withX402 } from "agents/x402";

const X402_CONFIG = {
  network: "base",
  recipient: env.MCP_ADDRESS,
  facilitator: { url: "https://x402.org/facilitator" },
};

export class PaidMCP extends McpAgent {
  server = withX402(
    new McpServer({ name: "PaidMCP", version: "1.0.0" }),
    X402_CONFIG
  );

  async init() {
    // Create a paid tool
    this.server.paidTool(
      "analyze",
      "Analyzes data with AI",
      0.10, // $0.10 per call
      { data: z.string() },
      async ({ data }) => {
        return { content: [{ type: "text", text: result }] };
      }
    );
  }
}

Create MCP servers with paid tools using withX402 for AI agents that can monetize their capabilities.