How to Monetize Your AI Agent with x402 Micropayments

March 4, 2026 x402 payments tutorial

AI agents need tools — web search, scraping, screenshots, code execution, crypto data. But how does an agent pay for these tools?

Traditional API billing (API keys, monthly subscriptions, rate tiers) was designed for humans. Agents don't have credit cards. They don't want to sign up for accounts. They need to pay per request, instantly, programmatically.

Enter x402 — an open payment protocol from Coinbase that lets AI agents pay for API calls with USDC micropayments. Your agent sends a request, the server responds with a price, your agent signs a payment, and the response arrives. All in one round-trip. No API keys, no accounts, no subscriptions.

What you'll build: An AI agent that uses 39+ API services (geolocation, web scraping, screenshots, crypto data, DNS lookups, and more) with automatic USDC payments at $0.001–$0.01 per request.

What is x402?

x402 uses HTTP 402 (Payment Required) — a status code that's existed since HTTP/1.1 but was never widely used. Here's how it works:

  1. Agent sends a request to an API endpoint
  2. Server responds with 402 and a X-PAYMENT header containing the price, payment address, and network
  3. Agent signs a USDC authorization using its wallet
  4. Agent retries the request with a X-PAYMENT-RESPONSE header containing the signed payment
  5. Server verifies the payment signature and returns the API response
  6. Payment settles on-chain via a facilitator (Coinbase)

The entire flow is handled transparently by the @x402/fetch client library. Your agent code looks almost identical to a normal fetch() call.

Prerequisites

Testnet mode: x402 currently uses Base Sepolia (testnet USDC) while the protocol matures. Get free testnet USDC from the Base Sepolia faucet.

Step 1: Install Dependencies

# Using npm
npm install @x402/fetch viem

# Or using bun
bun add @x402/fetch viem

Step 2: Set Up Your Wallet

// agent-wallet.js
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { baseSepolia } from "viem/chains";

// Your agent's wallet (keep the private key secret!)
const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY);

export const wallet = createWalletClient({
  account,
  chain: baseSepolia,
  transport: http(),
});

console.log(`Agent wallet: ${account.address}`);

Step 3: Make Paid API Calls

// agent.js
import { wrapFetch } from "@x402/fetch";
import { wallet } from "./agent-wallet.js";

const x402fetch = wrapFetch(fetch, wallet);

// GeoIP lookup — $0.001 per request
const geo = await x402fetch(
  "https://agent-gateway-kappa.vercel.app/v1/agent-geo/geo/8.8.8.8"
).then(r => r.json());
console.log(geo);
// { ip: "8.8.8.8", country: "US", city: "Mountain View", ... }

// Web scraping — $0.005 per request
const scraped = await x402fetch(
  "https://agent-gateway-kappa.vercel.app/v1/agent-scraper/scrape",
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ url: "https://example.com" }),
  }
).then(r => r.json());
console.log(scraped.title, scraped.contentLength);

// Screenshot — $0.005 per request
const screenshot = await x402fetch(
  "https://agent-gateway-kappa.vercel.app/v1/agent-screenshot/screenshot",
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ url: "https://example.com" }),
  }
).then(r => r.json());
console.log(screenshot.url); // Direct link to the screenshot image

That's it. No API keys. No signup. Your agent pays $0.001–$0.005 per call, and the payment is settled on-chain automatically.

Available Services & Pricing

ServiceWhat It DoesPrice
IP GeolocationIP to country, city, ISP, coords$0.001
DNS LookupQuery any DNS record type$0.001
Crypto PricesLive prices for 500+ tokens$0.001
On-Chain AnalyticsWallet balances, token holders$0.001
Web SearchSearch the web programmatically$0.001
Agent MemoryPersistent key-value storage$0.003
File StorageUpload and retrieve files$0.003
Task QueueAsync job processing$0.003
URL ShortenerCreate short links$0.003
Web ScraperExtract content from any URL$0.005
ScreenshotsRender page screenshots$0.005
PDF GeneratorHTML/URL to PDF$0.005
LLM RouterMulti-provider AI inference$0.010

Full list of 39+ services at api-catalog-three.vercel.app.

Real-World Example: Research Agent

Here's a complete agent that researches a topic by searching the web, scraping the top results, and summarizing them:

// research-agent.js
import { wrapFetch } from "@x402/fetch";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { baseSepolia } from "viem/chains";

const BASE = "https://agent-gateway-kappa.vercel.app";

const wallet = createWalletClient({
  account: privateKeyToAccount(process.env.AGENT_PRIVATE_KEY),
  chain: baseSepolia,
  transport: http(),
});

const f = wrapFetch(fetch, wallet);

async function research(topic) {
  // 1. Search the web ($0.001)
  const search = await f(`${BASE}/v1/agent-search/search?q=${encodeURIComponent(topic)}`)
    .then(r => r.json());

  // 2. Scrape top 3 results ($0.005 each = $0.015)
  const pages = await Promise.all(
    search.results.slice(0, 3).map(r =>
      f(`${BASE}/v1/agent-scraper/scrape`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url: r.url }),
      }).then(r => r.json())
    )
  );

  // 3. Store results in memory ($0.003)
  await f(`${BASE}/v1/agent-memory/memory`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      key: `research:${topic}`,
      value: pages.map(p => ({ title: p.title, text: p.text?.substring(0, 2000) })),
    }),
  });

  // Total cost: $0.019 for a complete research cycle
  return { topic, sources: pages.length, totalCost: "$0.019" };
}

const result = await research("x402 payment protocol for AI agents");
console.log(result);
Cost breakdown: 1 search ($0.001) + 3 scrapes ($0.015) + 1 memory write ($0.003) = $0.019 total for a full research cycle. That's 52 research cycles per dollar.

How x402 Compares to Traditional API Billing

Featurex402 Auto-PayAPI KeysSubscriptions
Setup requiredInstall @x402/fetchRegister, get keySign up, pick plan
AuthenticationCrypto walletBearer tokenAccount login
Billing modelPay per requestPrepaid creditsMonthly flat rate
Minimum cost$0.001$0 (free credits)$9–$99/mo
Overpayment riskNoneLowHigh
Agent-nativeYesPartialNo
Multi-serviceOne wallet, all APIsOne key per serviceOne plan per service
SettlementOn-chain (USDC)Off-chainCredit card

For API Providers: Accept x402 Payments

If you're building an API and want to accept x402 payments from AI agents, the server-side setup is straightforward:

// Express.js server with x402
import express from "express";
import { paymentMiddleware } from "@x402/express";

const app = express();

app.use(paymentMiddleware({
  facilitatorUrl: "https://x402.org/facilitator",
  payTo: process.env.WALLET_ADDRESS,
  network: "eip155:84532", // Base Sepolia
  routes: [
    { path: "/api/data", price: "$0.001", description: "Data lookup" },
    { path: "/api/scrape", price: "$0.005", description: "Web scraping" },
  ],
}));

app.get("/api/data", (req, res) => {
  res.json({ result: "Your data here" });
});

app.listen(3000);

Every request to /api/data requires a $0.001 USDC payment. The middleware handles the 402 response, payment verification, and settlement automatically.

Security Considerations

What's Next for x402?

Try It Now — Free

Start with 50 free requests/day (no wallet needed). When ready to scale, add x402 auto-pay for unlimited access at $0.001/request.

Try in Playground

View pricing · x402 endpoint details · API docs

Resources