How to Monetize Your AI Agent with x402 Micropayments
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 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:
- Agent sends a request to an API endpoint
- Server responds with 402 and a
X-PAYMENTheader containing the price, payment address, and network - Agent signs a USDC authorization using its wallet
- Agent retries the request with a
X-PAYMENT-RESPONSEheader containing the signed payment - Server verifies the payment signature and returns the API response
- 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
- Node.js 18+ (or Bun)
- An Ethereum wallet with USDC on Base Sepolia (testnet)
- That's it — no API keys, no accounts, no signup
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
| Service | What It Does | Price |
|---|---|---|
| IP Geolocation | IP to country, city, ISP, coords | $0.001 |
| DNS Lookup | Query any DNS record type | $0.001 |
| Crypto Prices | Live prices for 500+ tokens | $0.001 |
| On-Chain Analytics | Wallet balances, token holders | $0.001 |
| Web Search | Search the web programmatically | $0.001 |
| Agent Memory | Persistent key-value storage | $0.003 |
| File Storage | Upload and retrieve files | $0.003 |
| Task Queue | Async job processing | $0.003 |
| URL Shortener | Create short links | $0.003 |
| Web Scraper | Extract content from any URL | $0.005 |
| Screenshots | Render page screenshots | $0.005 |
| PDF Generator | HTML/URL to PDF | $0.005 |
| LLM Router | Multi-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);
How x402 Compares to Traditional API Billing
| Feature | x402 Auto-Pay | API Keys | Subscriptions |
|---|---|---|---|
| Setup required | Install @x402/fetch | Register, get key | Sign up, pick plan |
| Authentication | Crypto wallet | Bearer token | Account login |
| Billing model | Pay per request | Prepaid credits | Monthly flat rate |
| Minimum cost | $0.001 | $0 (free credits) | $9–$99/mo |
| Overpayment risk | None | Low | High |
| Agent-native | Yes | Partial | No |
| Multi-service | One wallet, all APIs | One key per service | One plan per service |
| Settlement | On-chain (USDC) | Off-chain | Credit 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
- Private key safety: Store your agent's private key in environment variables, never in code. Use a dedicated wallet for your agent with limited funds.
- Spending limits: The x402 protocol settles payments per-request. Your agent only spends what it uses. Fund the wallet with small amounts to limit exposure.
- Testnet first: x402 currently uses Base Sepolia (testnet). No real money is spent during development.
- On-chain verification: All payments are verified on-chain by the facilitator. No trust required between agent and API provider.
What's Next for x402?
- Mainnet support: Base mainnet (real USDC) is coming soon, currently in beta on Sepolia.
- Multi-chain: Support for other EVM chains (Ethereum, Arbitrum, Optimism) is planned.
- Agent-to-agent: x402 enables a future where agents pay each other for services — no human intermediary needed.
- MCP integration: Combining x402 with Model Context Protocol for seamless tool use with built-in billing.
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 PlaygroundResources
- x402.org — Official x402 protocol specification
- Clawdia API Catalog — 39+ x402-enabled services
- Pricing page — Full pricing across all services and payment methods
- Referral program — Earn 10% on referred agent purchases
- @x402/fetch on npm — Client library for x402 payments