x402-fetch
A utility package that extends the nativefetch
API to automatically handle 402 Payment Required responses using the x402 payment protocol. This package enables seamless integration of payment functionality into your applications when making HTTP requests.
Installation
Quick Start
API
wrapFetchWithPayment(fetch, walletClient, maxValue?, paymentRequirementsSelector?)
Wraps the native fetch API to handle 402 Payment Required responses automatically.
Parameters
fetch
: The fetch function to wrap (typicallyglobalThis.fetch
)walletClient
: The wallet client used to sign payment messages (must implement the x402 wallet interface)maxValue
: Optional maximum allowed payment amount in base units (defaults to 0.1 USDC)paymentRequirementsSelector
: Optional function to select payment requirements from the response (defaults toselectPaymentRequirements
)
Returns
A wrapped fetch function that automatically handles 402 responses by:- Making the initial request
- If a 402 response is received, parsing the payment requirements
- Verifying the payment amount is within the allowed maximum
- Creating a payment header using the provided wallet client
- Retrying the request with the payment header