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.
Prerequisites
Before you begin, ensure you have:
A crypto wallet with USDC (any EVM-compatible wallet, e.g., )
and npm installed
A service that requires payment via x402
Note
We have pre-configured , including examples for fetch, Axios, and MCP.
1. Install Dependencies
Install or :
npm install x402-axios
# or
npm install x402-fetch
2. Create a Wallet Client
Create a wallet client using CDP's Wallet API or :
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { baseSepolia } from "viem/chains";
// Create a wallet client (using your private key)
const account = privateKeyToAccount("0xYourPrivateKey"); // we recommend using an environment variable for this
import { CdpClient } from "@coinbase/cdp-sdk";
import { createWalletClient, http } from "viem";
import { baseSepolia } from "viem/chains";
const cdp = new CdpClient();
const account = await cdp.evm.createAccount();
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.
import { wrapFetchWithPayment, decodeXPaymentResponse } from "x402-fetch";
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
fetchWithPayment(url, { //url should be something like https://api.example.com/paid-endpoint
method: "GET",
})
.then(async response => {
const body = await response.json();
console.log(body);
const paymentResponse = decodeXPaymentResponse(response.headers.get("x-payment-response")!);
console.log(paymentResponse);
})
.catch(error => {
console.error(error.response?.data?.error);
});