- 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 eitherx402-fetch
or x402-axios
to automatically handle 402 Payment Required responses and complete payment flows.
x402-fetch extends the native Features:
fetch
API to handle 402 responses and payment headers for you.- Automatically handles 402 Payment Required responses
- Verifies payment and generates payment headers
- Retries the request with proof of payment
- Supports all standard fetch options
4. Error Handling
Bothx402-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