Quickstart for Buyers
This guide walks you through how to use x402 to interact with services that require payment. By the end of this guide, you will be able to programmatically discover payment requirements, complete a payment, and access a paid resource.
The x402-axios and x402-fetch helper packages greatly simplify your integration with x402. You’ll be able to automatically detect payment challenges, authorize payments onchain, and retry requests — all with minimal code. The packages will automatically trigger the following flow:
- Makes the initial request (if using Fetch) or intercepts the initial request (if using Axios)
- If a 402 response is received, parses the payment requirements
- Verifies the payment amount is within the allowed maximum
- Creates a payment header using the provided wallet client
- Retries the request with the payment header
Prerequisites
Before you begin, ensure you have:
- A crypto wallet with USDC (any EVM-compatible wallet, e.g., CDP Wallet, AgentKit)
- Node.js and npm installed
- A service that requires payment via x402
We have pre-configured examples available in our repo, including examples for fetch, Axios, and MCP.
1. Install Dependencies
Install x402-axios or x402-fetch:
2. Create a Wallet Client
Create a wallet client using CDP’s Wallet API (recommended) or viem.
3. Make Paid Requests Automatically
You can use either x402-fetch
or x402-axios
to automatically handle 402 Payment Required responses and complete payment flows.
x402-fetch extends the native fetch
API to handle 402 responses and payment headers for you.
Features:
- Automatically handles 402 Payment Required responses
- Verifies payment and generates payment headers
- Retries the request with proof of payment
- Supports all standard fetch options
x402-fetch extends the native fetch
API to handle 402 responses and payment headers for you.
Features:
- Automatically handles 402 Payment Required responses
- Verifies payment and generates payment headers
- Retries the request with proof of payment
- Supports all standard fetch options
x402-axios adds a payment interceptor to Axios, so your requests are retried with payment headers automatically.
Features:
- Automatically handles 402 Payment Required responses
- Retries requests with payment headers
- Exposes payment response headers
4. Error Handling
Both x402-fetch
and x402-axios
will throw errors if:
- The request configuration is missing
- A payment has already been attempted for the request
- There is an error creating the payment header
Summary
- Install either
x402-fetch
orx402-axios
- Create a wallet client (using viem or CDP Wallet API)
- Use the provided wrapper/interceptor to make paid API requests
- Payment flows are handled automatically for you
References:
For questions or support, join our Discord.