Client Libraries

Integrate x402 payments into your applications using our client libraries. Automatic payment handling for HTTP requests.

How Client Libraries Work

x402 client libraries automatically handle the HTTP 402 payment flow. When you make a request to a protected endpoint, the library detects the 402 response, creates a payment transaction, and retries the request with payment proof.

JavaScript / TypeScript

Install the x402 client for Node.js or browser environments:

npm install x402-client

Basic Usage

import { X402Client } from 'x402-client';
import { ethers } from 'ethers';

// Initialize with your wallet
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();

const client = new X402Client({
  signer,
  network: 'base'
});

// Make paid requests automatically
const response = await client.get('https://api.example.com/data');
const data = await response.json();

console.log(data);

POST Requests

// POST with automatic payment
const response = await client.post(
  'https://api.example.com/generate',
  {
    body: JSON.stringify({ prompt: 'Generate image' }),
    headers: { 'Content-Type': 'application/json' }
  }
);

const result = await response.json();

React Integration

import { X402Provider, useX402 } from 'x402-react';
import { useWallet } from '@solana/wallet-adapter-react';

function App() {
  const { signer } = useWallet();
  
  return (
    <X402Provider signer={signer} network="solana">
      <YourApp />
    </X402Provider>
  );
}

function YourComponent() {
  const { client } = useX402();
  
  const fetchData = async () => {
    const response = await client.get('https://api.example.com/data');
    const data = await response.json();
    return data;
  };
  
  // Use in your component
}

Python

Install the Python client library:

pip install x402-python-client

Basic Usage

from x402 import X402Client
from web3 import Web3

# Initialize client
w3 = Web3(Web3.HTTPProvider('https://mainnet.base.org'))
account = w3.eth.account.from_key('your-private-key')

client = X402Client(
    signer=account,
    network='base'
)

# Make paid request
response = client.get('https://api.example.com/data')
data = response.json()

print(data)

Async Support

from x402 import AsyncX402Client

async def fetch_data():
    client = AsyncX402Client(signer=account, network='base')
    
    response = await client.get('https://api.example.com/data')
    data = await response.json()
    
    return data

# Use with asyncio
import asyncio
data = asyncio.run(fetch_data())

Configuration Options

Network Selection

const client = new X402Client({
  signer,
  network: 'base', // or 'solana', 'polygon', 'bsc'
  rpcUrl: 'https://mainnet.base.org' // optional custom RPC
});

Payment Limits

const client = new X402Client({
  signer,
  network: 'base',
  maxPayment: '0.1', // Maximum payment per request (in ETH)
  autoApprove: false // Require manual approval for each payment
});

Custom Headers

const response = await client.get(
  'https://api.example.com/data',
  {
    headers: {
      'Authorization': 'Bearer token',
      'Custom-Header': 'value'
    }
  }
);

Error Handling

try {
  const response = await client.get('https://api.example.com/data');
  const data = await response.json();
} catch (error) {
  if (error.code === 'INSUFFICIENT_FUNDS') {
    console.error('Not enough balance for payment');
  } else if (error.code === 'PAYMENT_REJECTED') {
    console.error('User rejected payment');
  } else if (error.code === 'NETWORK_ERROR') {
    console.error('Network error:', error.message);
  } else {
    console.error('Unknown error:', error);
  }
}

Advanced Features

Payment Caching

Automatically cache payment proofs to avoid redundant payments for the same resource

Retry Logic

Built-in retry mechanism for failed payments and network issues

Multi-Network

Support for multiple blockchain networks with automatic network detection

TypeScript Types

Full TypeScript support with comprehensive type definitions

Learn More

Check out code examples and understand the payment flow in detail.

Nova402