Buyer side (x402-client)
A buyer's code (an agent, a CLI, a server) needs to:
- Issue a normal HTTP request.
- Handle a
402 Payment Requiredresponse by signing a Boson escrow payment. - Re-issue the request with an
X-PAYMENTheader.
The x402-client package handles steps 2 and 3 transparently.
Fetch adapter
The simplest integration is x402-client-fetch, which wraps fetch:
import { createX402bClientFetch } from "@bosonprotocol/x402-client-fetch"
import { ethers } from "ethers"
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!)
const fetchWithPayment = createX402bClientFetch({
signer: wallet,
// Optional: pick token-auth + fulfillment preferences
preferredTokenAuth: ["ERC3009", "Permit2", "Permit"],
})
const res = await fetchWithPayment("https://api.example.com/premium-thing")
console.log(await res.json())When the upstream returns 402, the wrapper signs and retries automatically.
Lower-level API
If you're not using fetch, use the core x402-client:
import { createX402bClient } from "@bosonprotocol/x402-client"
const client = createX402bClient({ signer: wallet })
const challenge = parseChallenge(rawResponse) // your HTTP lib's job
const payment = await client.buildPayment(challenge)
// payment is the value for the X-PAYMENT headerPreferences
| Preference | What it controls |
|---|---|
preferredTokenAuth | Order in which to try ERC-3009 / Permit / Permit2 / approve |
preferredFulfillment | Order in which to pick inline / email / XMTP / webhook / IPFS |
maxValue | Reject challenges asking for more than this |
allowAtomicRedeem | Whether to accept atomic commit-and-redeem flows |
Common gotchas
- Token-auth mismatch. If the seller doesn't advertise any of your preferred strategies, the client throws. Have a fallback.
- Network mismatch. The 402 specifies a chain; your wallet must be on it.
- Repeated 402s. If the seller's facilitator is down, you'll get 402 forever. Cap retries.