TypeScript SDK
wrapFetchWithPayment
Enables the payment of APIs using the x402 payment protocol.
This function wraps the native fetch API to automatically handle 402 Payment Required responses by creating and sending a payment header. It will:
Make the initial request
If a 402 response is received, parse the payment requirements
Verify the payment amount is within the allowed maximum
Create a payment header using the provided wallet client
Retry the request with the payment header
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");await wallet.connect({ client }); const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet); // Make a request that may require paymentconst response = await fetchWithPay( "https://api.example.com/paid-endpoint",);function wrapFetchWithPayment( fetch: { (input: URL | RequestInfo, init?: RequestInit): Promise<Response>; (input: RequestInfo, init?: RequestInit): Promise<Response>; ( input: string | Request | URL, init?: RequestInit, ): Promise<Response>; }, options?: { maxValue?: bigint; paymentRequirementsSelector?: ( paymentRequirements: Array<{ asset: string; description: string; extra?: Record<string, any>; maxAmountRequired: string; maxTimeoutSeconds: number; mimeType: string; network: string; outputSchema?: Record<string, any>; payTo: string; resource: string; scheme: "exact" | "upto"; }>, ) => | undefined | { asset: string; description: string; extra?: Record<string, any>; maxAmountRequired: string; maxTimeoutSeconds: number; mimeType: string; network: string; outputSchema?: Record<string, any>; payTo: string; resource: string; scheme: "exact" | "upto"; }; },): (input: RequestInfo, init?: RequestInit) => Promise<Response>;The wallet used to sign payment messages
let wallet: { getAuthToken?: () => string | null; id: TWalletId; onConnectRequested?: () => Promise<void>; autoConnect: ( connect: ( disconnect: () => Promise<void>; getChain: () => | undefined switchChain: (chain: Readonly) => Promise<void>;};let options: { maxValue?: bigint; paymentRequirementsSelector?: ( paymentRequirements: Array<{ asset: string; description: string; extra?: Record<string, any>; maxAmountRequired: string; maxTimeoutSeconds: number; mimeType: string; network: string; outputSchema?: Record<string, any>; payTo: string; resource: string; scheme: "exact" | "upto"; }>, ) => | undefined | { asset: string; description: string; extra?: Record<string, any>; maxAmountRequired: string; maxTimeoutSeconds: number; mimeType: string; network: string; outputSchema?: Record<string, any>; payTo: string; resource: string; scheme: "exact" | "upto"; };};