@sei-js/x402-axios

A utility package that extends Axios 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 with Axios.

Installation

npm install @sei-js/x402-axios

Quick Start

import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { withPaymentInterceptor } from "@sei-js/x402-axios";
import axios from "axios";
import { seiTestnet } from "viem/chains";

// Create a wallet client
const account = privateKeyToAccount("0xYourPrivateKey");
const client = createWalletClient({
  account,
  transport: http(),
  chain: seiTestnet,
});

// Create an Axios instance with payment handling
const api = withPaymentInterceptor(
  axios.create({
    baseURL: "https://api.example.com",
  }),
  client
);

// Make a request that may require payment
const response = await api.get("/paid-endpoint");
console.log(response.data);

Features

  • Automatic handling of 402 Payment Required responses
  • Automatic retry of requests with payment headers
  • Payment verification and header generation
  • Exposes payment response headers

API

withPaymentInterceptor(axiosClient, walletClient)

Adds payment handling interceptors to an existing Axios instance.

Parameters

  • axiosClient: The Axios instance to add payment handling to
  • walletClient: The wallet client used to sign payment messages (must implement the x402 wallet interface)

Returns

The same Axios instance with payment interceptors added. The interceptors will:
  1. Catch 402 responses
  2. Parse payment requirements from the response
  3. Create payment headers using the wallet client
  4. Retry the original request with payment headers

Example

import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { withPaymentInterceptor } from "@sei-js/x402-axios";
import axios from "axios";
import { seiTestnet } from "viem/chains";

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const client = createWalletClient({
  account,
  transport: http(),
  chain: seiTestnet,
});

const api = withPaymentInterceptor(
  axios.create({
    baseURL: "https://api.example.com",
    timeout: 10000,
  }),
  client
);

// Use the API client normally - payments are handled automatically
try {
  const response = await api.get("/premium-data");
  console.log("Premium data:", response.data);
} catch (error) {
  console.error("Request failed:", error);
}