Enable AI agents to pay APIs autonomously with Circle Wallets and x402. Learn how USDC unlocks onchain, pay-per-use access in real time.

Introduction
Imagine an AI agent that can not only think and act but also pay for services on its own. Recent advancements in payments technology are making this possible. The HTTP status code 402 Payment Required has sat unused for decades – until now. Coinbase’s new x402 protocol revives HTTP 402 to enable onchain payments within standard web requests.
This means an API or web service can now request a small USDC payment, such as a processing fee, access toll, or data usage charge before fulfilling a request. For example, an AI agent querying a real-time weather API or onchain oracle could automatically approve the microtransaction, complete the payment, and retrieve the response, all in one seamless flow. This unlocks new monetization opportunities for developers and creates a foundation for autonomous agents to interact with paid services natively across the Internet.
Agentic (AI agent-based) commerce also extends to more complex, higher-value transactions like travel. Imagine an AI travel assistant that monitors flight prices and hotel availability based on your calendar, preferences, and loyalty programs. When it finds a flight that fits your schedule and budget, it can autonomously book the ticket and pay the airline directly using USDC via an x402-enabled API. No form-filling, no checkout friction, just a seamless transaction executed by your AI agent. This unlocks a future where AI agents don’t just recommend options, but can act on your behalf to secure real-world goods and services with real-time, onchain payments.
In our sample app, we combined autonomous AI agents with autonomous payments using Circle’s Developer-Controlled Wallets and the x402 protocol. Written in Typescript using the Langchain agent framework and OpenAI’s GPT-4o mini model, our agent fetched a paywalled resource (a blockchain wallet risk profile) by programmatically paying the required fee in USDC.
In this blog post, we’ll walk through the components involved, the overall sequence, a real-world use case, and a guide on how we integrated Circle’s Developer-Controlled Wallets and x402 in our sample app.
Overview of the Components
To achieve autonomous payments, several pieces work together in our solution:
- AI Agent – A Langchain-based AI agent acting on behalf of a user. It can make HTTP requests and decide to purchase data or API access when needed. In our case, the agent uses tools to create its own wallet, funds it and buys a risk profile report for a given wallet address from a 3rd-party API.
- Circle Developer-Controlled Wallets – Circle’s API for creating and managing custodial crypto wallets for users. These wallets use secure MPC technology so private keys are never exposed. The developer controls the wallet via API/SDK, creating addresses, monitoring balances, and initiating transfers. We loaded our agent’s wallet with USDC using Circle’s Testnet faucet API to use for payments. Circle’s Wallets are multichain, supporting USDC across multiple blockchains.
- x402 Protocol – An open HTTP-based payment standard that allows services to monetize APIs via microtransactions. With x402, a web service can respond to a request with 402 Payment Required and include details like the price (in crypto), acceptable tokens (e.g. USDC), and a payment address or invoice. The client (our AI agent) then signs a payment authorization and retries the request including the signed payment payload in the request header, after which the service sends the payload to the x402 facilitator (for signature verification and settlement on the blockchain) and then returns the data after the payment settles.
- Facilitator – Under the hood, x402 relies on a facilitator service to verify payment payloads and settle the transaction onchain. Coinbase’s x402 facilitator ensures that our agent’s signed payment authorization is valid, the payment was confirmed onchain, and the API server can safely unlock the content.
Sequence Diagram
The diagram below illustrates the high-level interaction when our AI agent accesses a paywalled API using x402 and Circle Wallets:

1 - 3: Server Initialization: The web server starts by checking if it has a Circle Wallet. If not, it makes a request to the Circle Wallets service to create one in order to accept payments.
4 - 6: Agent Initialization: The AI agent starts by checking if it has a Circle Wallet. If not, it makes a request to the Circle Wallets service to create one. The agent’s wallet needs USDC to pay for services, so we request USDC from the Circle Testnet faucet API.
7: Agent -> Server: The agent requests a protected resource (e.g. GET /wallet/risk-profile).
8: Server -> Agent: The service responds with HTTP 402, indicating that a payment is required. The 402 response also includes the payment details.
9: Agent -> Circle Wallets API: Upon receiving the 402, the agent uses the Sign Typed Data API to sign a payment authorization to pay for access to the data.
10: Agent -> Server: Agent retries the request with the signed payment authorization as part of the X-PAYMENT header.
11 - 14: Server -> Facilitator -> Blockchain: The server forwards the payment authorization payload to a facilitator service, which validates the payload and broadcasts it to the blockchain.
15 - 17: Server -> Agent: Once the payment is settled, the facilitator notifies the server and then the server returns HTTP 200 with the requested data to the Agent.
This all happens within seconds, without any human intervention. Next, let’s look at a concrete example of why this is powerful.
Real-World Example: Autonomous AI Agent Buys a Wallet Risk Profile
Consider an AI agent that’s evaluating whether to interact with a particular crypto wallet. The agent wants to ensure the wallet has a good reputation (not associated with scams or sanctions). A third-party service offers a “wallet risk profile” via API – basically a report on that wallet’s history and risk score. However, this API isn’t free; it charges a small fee per request. Traditionally, our agent would be stuck, since it has no credit card, API key or login to pay for this API. But with x402 and Circle Wallets, the agent can handle it autonomously.
In our implementation, the agent simply makes an HTTP request to the risk-profile API. The service responds with 402 Payment Required, asking for $0.01 in USDC. The agent automatically parses the payment request, reasons and then uses its tools to fulfil the payment requirement. It creates a wallet, funds it and pays $0.01 USDC onchain to receive the risk profile data for the wallet. All of this happens in one programmatic flow.
This example showcases the power of autonomous payments. The agent didn’t need to pre-register an account or ask a human to complete a purchase. Payment is the authentication: if the agent can pay the fee, it gets access. Such pay-per-use models were impractical with traditional payment rails, but USDC, Circle Developer Service and x402 make it feasible to charge even a few cents for valuable data. This opens up a new world of API monetization and machine-to-machine commerce, where AI agents can pay as they go for the resources they need.
Step-by-Step Integration Guide
Finally, let’s dive into how we integrated Circle’s Developer-Controlled Wallets and x402 in our sample app.
Step 1: Create and Fund Circle Wallets for the AI Agent and the Server
The following functions are to create dedicated Circle Wallets for our AI agent and server upon initialization using Circle’s Wallets SDK. The agent needs a wallet to pay for services and the server needs a wallet to accept payments from clients that need to access its paywalled APIs.
We fund the AI agent’s wallet with a small amount of USDC to enable it to pay to access the server’s paywalled APIs. We used Circle’s USDC faucet to fund the agent’s wallet.
Note: You can only use Externally Owned Accounts (EOA) for signing transactions. This wallet can be used to sign transactions on any EVM chain.
Create an EOA Wallet using the Circle Wallet’s SDK (create-wallet.ts):
const walletResponse = await circleDeveloperSdk.createWallets({
accountType: "EOA",
blockchains: ["EVM-TESTNET"],
count: 1,
walletSetId,
});
Fund a wallet using Circle’s faucet API (fund-wallet.ts):
const response = await axios.post(
"https://api.circle.com/v1/faucet/drips",
{
address: address,
blockchain: "BASE-SEPOLIA",
usdc: true
},
{
headers: {
Authorization: `Bearer ${process.env.CIRCLE_API_KEY}`,
"Content-Type": "application/json",
},
timeout: 30000, // 30 second timeout
}
);
Step 2: Create AI Agent that can pay with Circle Wallets
We created a LangChain AI agent that can use tools to fulfil requests. We gave it access to three tools: a wallet creation tool, a wallet funding tool and a risk profile tool.
The core agent code using LangChain (langchain.ts):
const llm = new ChatOpenAI({
model: "gpt-4o-mini",
temperature: 0,
apiKey: openaiApiKey,
});
const tools = [walletCreationTool, walletFundingTool, riskProfileTool]
const agent = createToolCallingAgent({
llm,
tools,
prompt,
});
const agentExecutor = new AgentExecutor({
agent,
tools,
});
const response = await agentExecutor.invoke({ input: query });
The Wallet Creation Tool (langchain.ts):
const walletCreationTool = tool(
async () => {
const createdWallet = await createWallet();
return `A Circle wallet with the address ${createdWallet.address} was created`
},
{
name: "circle-wallet-creator",
description: "Can create Circle wallets."
}
)
The Wallet Funding Tool (langchain.ts):
const walletFundingTool = tool(
async ({ address }) => {
const faucetResponse = await fundWallet(address);
return `The wallet with address ${address} has been funded successfully: ${faucetResponse}`
},
{
name: "circle-wallet-funding",
description: "Can fund Circle wallets.",
schema: walletFundingSchema
}
)
The Risk Profile Tool (langchain.ts):
const riskProfileTool = tool(
async () => {
const data = await requestRiskProfile();
const {risk_profile, recommendation} = data.report;
return `The risk profile JSON data of the wallet is ${JSON.stringify(risk_profile)}. The recommendation is ${JSON.stringify(recommendation)}`
},
{
name: "risk-profile",
description: "Can return placeholder risk profile data of any crypto wallet."
}
);
The agent also needs to sign a payment to include in the X-PAYMENT header of the follow-up request to the server. We use Circle’s Signing API for this (request-risk-profile.ts).
const response = await circleDeveloperSdk.signTypedData({
walletId: process.env.AGENT_WALLET_ID,
data: JSON.stringify(data)
});
Step 3: Setup server API paywall using x402-express npm package
To add paywall functionality to our server, we used the x402-express npm package, an express middleware integration for the x402 Payment Protocol.
The paymentMiddleware function accepts three parameters:
- payTo: Your receiving address (0x${string})
- routes: Route configurations for protected endpoints
- facilitator: (Optional) Configuration for the x402 facilitator service
- paywall: (Optional) Configuration for the built-in paywall
Middleware Integration (api.ts):
app.use(
paymentMiddleware(
recipientWallet.address as `0x${string}`, //payTo
{
"GET /risk-profile": {
price: "$0.01",
network: "base-sepolia",
},
}, //routes
{
url: "https://x402.org/facilitator",
}, //facilitator
),
);
When the agent calls this API, the x402-express middleware sends a 402 error with payment details.
Server responded with status: 402
Received and parsed payment requirements: {
scheme: 'exact',
network: 'base-sepolia',
maxAmountRequired: '10000',
resource: 'http://localhost:4021/risk-profile',
description: '',
mimeType: '',
payTo: '0x71354f83024159852dc563adc4af0c6b7e342c1c',
maxTimeoutSeconds: 60,
asset: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',
extra: { name: 'USDC', version: '2' }
}
The agent retries with an X-Payment header, the middleware handles the subsequent requests to the Facilitator service to verify and settle the payment onchain.
---> Data to sign: {"types":{"EIP712Domain":[{"name":"name","type":"string"},{"name":"version","type":"string"},{"name":"chainId","type":"uint256"},{"name":"verifyingContract","type":"address"}],"TransferWithAuthorization":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"value","type":"uint256"},{"name":"validAfter","type":"uint256"},{"name":"validBefore","type":"uint256"},{"name":"nonce","type":"bytes32"}]},"domain":{"name":"USDC","version":"2","chainId":84532,"verifyingContract":"0x036CbD53842c5426634e7929541eC2318f3dCF7e"},"primaryType":"TransferWithAuthorization","message":{"from":"0x33776619d123f77934ac04A9Aa6BF64297f2cB10","to":"0x2F6CEBEbD7B033AAab2B2c2074fb7106Cb7FF3bD","value":"10000","validAfter":"1753740125","validBefore":"1753740785","nonce":"0xb57c13878a5e9c86fdeb3be51bd3aae4772065bff8091ffd5ce42658523da6d4"}}
---> Signed typed data: {
signature: '0xbfe64f8f0021f786ed6bac38c5aea4dd849a5ff9e99c5286ce184425348055ef61f8313bdd683f987f551fd5faf309b287101254f534e546b5c192627852b5941c'
}
Once verified, the middleware has completed its job, and then the server responds to the agent with the requested data.
Payment completed, Server responded with: {
report: {
risk_profile: {
wallet_address: '0x5aAeb6053F3E94C9b9a09f33669435E7Ef1BeAed',
chain: 'ethereum',
timestamp: '2025-07-24T18:23:47Z',
risk_score: 87,
risk_level: 'high',
risk_breakdown: [Object],
tags: [Array],
recommendation: 'block_transaction',
provider_signature: '0xf3f9...e1c4'
}
}
}
Conclusion
By combining Circle Wallets with the x402 protocol, we enabled our AI agent to seamlessly pay for API access. This fusion of AI agents and autonomous payments points to a future where machines can transact with each other as easily as they exchange data. Developers can now monetize APIs with fine-grained pricing (down to cents or less) and clients (even non-humans) can pay per use.
In our sample app, a once-manual paywall became an automated step in an agent’s workflow. The agent fetched a blockchain wallet’s risk profile by simply calling an API – x402 and Circle Wallets took care of the rest (finding out the price, transferring USDC, and verifying the payment). The integration was straightforward: we leveraged Circle’s Wallet SDK to manage the wallets and the x402-express npm package to handle the payment flow on the server-side.
This developer experience is surprisingly smooth given the complexity under the hood. As the ecosystem evolves, we expect to see more autonomous agents utilizing protocols like x402 and Circle Wallets to unlock paid resources, and more services adopting pay-by-request models. If you’re building AI agents or any app that needs on-demand data, it’s a great time to explore combining Circle Wallets and x402 payments in your stack. The era of machines with wallets capable of reasoning, acting, and paying has officially begun.
Circle Wallets are provided by Circle Technology Services, LLC (“CTS”). CTS is a software provider and does not provide regulated financial or advisory services. You are solely responsible for services you provide to users, including obtaining any necessary licenses or approvals and otherwise complying with applicable laws. For additional details, please click here to see the Circle Developer terms of service.