A Software Engineer's Guide to the x402 Micropayments Standard
x402 is an open payments protocol for the internet, built on HTTP.
Its core concept is simple yet powerful
it re-activates the dormant HTTP 402 "Payment Required" status code to standardize a seamless, machine-readable way for a server to ask for payment and a client (which could be a user's app, a script, or an AI agent) to pay for a resource.
It primarily uses blockchain-based payments, like stablecoins (e.g., USDC), to enable instant, low-cost, and fractional transactions.
x402 offers a game-changing solution to several persistent monetization and access problems on the internet
Traditional payment systems (like credit cards) have high fixed fees, making transactions below a dollar or even a few cents impractical. x402, by leveraging low-cost, fast blockchain networks (like Base), makes micropayments economically viable.
API Monetization
Instead of fixed subscription tiers, you can charge $0.001 per API call. This is perfect for high-volume, low-cost data access or utility services.
Content Access
Implement paywalls that charge per-article, per-video view, or per-dataset access, moving beyond rigid monthly subscriptions.
This is the biggest immediate win. The rise of sophisticated AI agents requires a way for them to pay for services they need autonomously.
Autonomous Agents
Your AI agent can seamlessly pay for access to a premium data API, a specialized computation service, or a context-aware model without human intervention. The agent receives the 402 response, processes the payment, and retries the request—all programmatically.
Model Context Protocol (MCP)
x402 is a key enabler for protocols like MCP, allowing agents to pay for the context and resources they consume in real-time.
The payment itself acts as a form of authorization, simplifying the user experience and developer workflow.
"Payment is Authentication"
For many use cases, you can eliminate the need for complex user sign-ups, password management, and API key generation. If the client can pay the required amount, they get access—simple as that.
HTTP-Native
Since it's built right into the HTTP request/response flow, it integrates naturally with existing web infrastructure like reverse proxies, load balancers, and web servers.
The protocol follows a straightforward request-response handshake
Client Request
A client (buyer) makes a standard HTTP request for a resource
GET /api/premium-data
Server Response (Offer)
The server (seller) requires payment and returns the 402 Payment Required status code. The response body contains a machine-readable JSON object with the payment details
maxAmountRequired
The price (e.g., "$0.01")
payTo
The receiving wallet address.
asset
The required stablecoin/token (e.g., USDC).
network
The blockchain network (e.g., "base-mainnet").
Client Payment
The client uses this information to generate and sign a payment payload with their crypto wallet. This payload proves they authorized the transfer of funds.
Client Retry (Proof)
The client retries the original request, but this time includes the signed payment payload in a special header, typically X-PAYMENT
GET /api/premium-data
X-PAYMENT: <signed_payment_payload>
Server Verification and Settlement
The server (often delegating this to a Facilitator service like one offered by Coinbase) verifies the payment payload's signature and then settles the transaction on the blockchain.
Server Final Response
Once payment is confirmed, the server returns the requested resource (e.g., 200 OK with the data) and may include a confirmation header (X-PAYMENT-RESPONSE).
Implementing x402 typically involves using a middleware library on your server to handle the 402 response and payment verification, and a client library for agents/apps to construct the payment payload.
As a server owner, you'll install an x402-compatible middleware in your web framework. This middleware does the heavy lifting of intercepting requests, sending the 402 response, and calling the facilitator service to verify payment on subsequent requests.
Here's a conceptual Node.js/Express-style example using a hypothetical x402-middleware package
// Example: Server-side (Node.js/Express)
const express = require('express');
const { paymentMiddleware } = require('@coinbase/x402-express');
// Note: Package name is hypothetical but based on typical library patterns
const app = express();
const RECEIVING_WALLET_ADDRESS = "0xYourWalletAddressHere";
const CHARGE_AMOUNT = "$0.005"; // Pay-per-request microcharge
// 1. Apply the middleware to the protected route(s).
// This single line ensures that any request to '/paid-api' will first trigger the x402 flow.
app.get('/paid-api',
paymentMiddleware(RECEIVING_WALLET_ADDRESS, {
price: CHARGE_AMOUNT,
network: "base-mainnet",
asset: "USDC"
}),
(req, res) => {
// This block only executes IF the payment has been successfully verified!
res.json({ data: "Congratulations, you paid and got the premium content!" });
}
);
app.listen(4020, () => console.log('Server running on port 4020'));
/*
What the middleware does:
- On initial GET /paid-api, it returns the 402 response with the payment details.
- On subsequent request with the X-PAYMENT header, it verifies the payload with the Facilitator.
- If verified, it calls next() to let your handler execute.
*/
As a client or an AI agent, you need a process to handle the 402 response, generate the payment, and retry.
// Example: Client-side (Typescript/Javascript for an AI Agent)
import axios from 'axios';
import { getPaymentPayload, signPayload } from '@coinbase/x402-client';
// Hypothetical client library for generating/signing the payment
const AGENT_WALLET_PRIVATE_KEY = process.env.AGENT_SECRET_KEY;
async function accessProtectedAPI(url: string) {
try {
// First attempt - will likely receive 402
const response = await axios.get(url);
return response.data;
} catch (error) {
// Check if the response is a 402 Payment Required
if (error.response && error.response.status === 402) {
console.log("Payment required. Starting x402 flow...");
const paymentDetails = error.response.data; // The JSON from the 402 body
// 1. Generate the payment payload using the server's requirements
const unsignedPayload = getPaymentPayload(paymentDetails);
// 2. Sign the payload using the agent's wallet
const signedPaymentPayload = signPayload(unsignedPayload, AGENT_WALLET_PRIVATE_KEY);
// 3. Retry the request with the X-PAYMENT header
const paidResponse = await axios.get(url, {
headers: {
'X-PAYMENT': signedPaymentPayload
}
});
console.log("Payment successful! Access granted.");
return paidResponse.data;
} else {
console.error("An unexpected error occurred:", error.message);
throw error;
}
}
}
accessProtectedAPI('http://localhost:4020/paid-api')
.then(data => console.log("Received data:", data));
This pattern—receiving a 402, processing the instructions, and retrying with an X-PAYMENT header—is what makes x402 a clean, open, and powerful standard for the future of internet-native commerce. It essentially brings the efficiency of blockchain microtransactions right into your existing HTTP-based architecture.