Payments

Client Side

Make requests to any x402-compatible backend by automatically handling payment flows when APIs return a 402 Payment Required response.

The client library wraps the native fetch API and handles:

  • Initial request to the API
  • Detection of 402 Payment Required responses
  • Parsing payment requirements from the response
  • Creating and signing payment authorization
  • Retrying the request with payment credentials

Using wrapFetchWithPayment

The wrapFetchWithPayment function wraps the native fetch API to automatically handle 402 Payment Required responses.

import { wrapFetchWithPayment } from "thirdweb/x402";
import { createThirdwebClient } from "thirdweb";
import { createWallet } from "thirdweb/wallets";
const client = createThirdwebClient({ clientId: "your-client-id" });
const wallet = createWallet("io.metamask"); // or any other wallet
await wallet.connect({ client });
// Wrap fetch with payment handling
// maxValue is the maximum payment amount in base units (defaults to 1 USDC = 1_000_000)
const fetchWithPay = wrapFetchWithPayment(
fetch,
client,
wallet,
BigInt(1 * 10 ** 6), // max 1 USDC
);
// Make a request that may require payment
const response = await fetchWithPay(
"https://api.example.com/paid-endpoint",
);
const data = await response.json();

Parameters

  • fetch - The fetch function to wrap (typically globalThis.fetch)
  • client - The thirdweb client used to access RPC infrastructure
  • wallet - The wallet used to sign payment messages
  • maxValue - (Optional) The maximum allowed payment amount in base units (defaults to 1 USDC = 1,000,000)

Reference

For full API documentation, see the TypeScript Reference.