T402 API Reference - v2.8.0
    Preparing search index...

    Function wrapFetchWithPayment

    • Enables the payment of APIs using the t402 payment protocol v2.

      This function wraps the native fetch API to automatically handle 402 Payment Required responses by creating and sending payment headers. It will:

      1. Make the initial request
      2. If a 402 response is received, parse the payment requirements
      3. Create a payment header using the configured t402HTTPClient
      4. Retry the request with the payment header

      Parameters

      • fetch: {
            (input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
            (input: string | Request | URL, init?: RequestInit): Promise<Response>;
        }

        The fetch function to wrap (typically globalThis.fetch)

          • (input: RequestInfo | URL, init?: RequestInit): Promise<Response>
          • Parameters

            • input: RequestInfo | URL
            • Optionalinit: RequestInit

            Returns Promise<Response>

          • (input: string | Request | URL, init?: RequestInit): Promise<Response>
          • Parameters

            • input: string | Request | URL
            • Optionalinit: RequestInit

            Returns Promise<Response>

      • client: any

        Configured t402Client or t402HTTPClient instance for handling payments

      Returns (input: RequestInfo, init?: RequestInit) => Promise<Response>

      A wrapped fetch function that handles 402 responses automatically

      import { wrapFetchWithPayment, t402Client } from '@t402/fetch';
      import { ExactEvmScheme } from '@t402/evm';
      import { ExactSvmScheme } from '@t402/svm';

      const client = new t402Client()
      .register('eip155:8453', new ExactEvmScheme(evmSigner))
      .register('solana:mainnet', new ExactSvmScheme(svmSigner))
      .register('eip155:1', new ExactEvmScheme(evmSigner), 1); // v1 protocol

      const fetchWithPay = wrapFetchWithPayment(fetch, client);

      // Make a request that may require payment
      const response = await fetchWithPay('https://api.example.com/paid-endpoint');

      If no schemes are provided

      If the request configuration is missing

      If a payment has already been attempted for this request

      If there's an error creating the payment header