How to Make Your AI Agent Pay for Things (x402)
Give your agent a wallet and let it buy data, tools, and APIs on its own — safely, in a few lines.
Give your agent a wallet and let it buy data, tools, and APIs on its own — safely, in a few lines.
If you're building an AI agent, you can let it pay for what it uses — a premium API, a dataset, a tool — without you in the loop, using the x402 protocol. The agent hits a paid endpoint, pays in stablecoins, and gets the data. Here's how, and how to do it without setting money on fire.
X-PAYMENT header.No API keys to manage, no subscriptions, no human clicking "approve."
This is the part to get right. Create a brand-new, throwaway wallet for the agent and fund it with a small amount of USDC (Base is the most common chain).
.env file or source code.x402 clients wrap your normal HTTP calls and handle the 402 automatically. Pick your HTTP library:
npm install x402-fetch # for fetch
# or
npm install x402-axios # for axios
import { wrapFetchWithPayment } from "x402-fetch";
import { privateKeyToAccount } from "viem/accounts";
// dedicated, low-balance wallet — see Step 1
const account = privateKeyToAccount(process.env.AGENT_WALLET_KEY);
const fetchWithPay = wrapFetchWithPayment(fetch, account);
// this call auto-pays the 402 and returns the data
const res = await fetchWithPay("https://some-service.com/premium");
const data = await res.json();
That's the whole thing — every call through fetchWithPay handles payment transparently. (APIs evolve; confirm the exact current usage in Coinbase's Quickstart for Buyers.)
Give the agent guardrails so a bug or a bad endpoint can't drain the float:
Most x402 clients and agent wallets support spend policies — use them.
Your agent needs to know what to pay for. The Agent Almanac catalogs the services agents can pay — and you can query it from inside your agent via our MCP server (tools like search_services and get_economy), or browse the live scoreboard to see which providers are actually real (paid by many wallets) versus dead listings.
Settlement only happens on a successful response, but that doesn't protect you from choosing to pay a bad service repeatedly. So: throwaway wallet, small balance, hard spend caps. With those three, letting your agent transact is genuinely low-risk.
Next: the other side — How to accept agent payments on your API (x402). Or see who's actually earning on the leaderboard.
Watch real settlement on the Economy scoreboard, see who's earning on the leaderboard, or query it all from your agent via the MCP server.