Implement x402

Add agentic payments to your stack with just a few lines of code.

Integration Steps

1. Define Pricing Logic

Determine which endpoints require payment and specify the price (e.g., 0.01 USDC). x402 supports dynamic pricing.

2. Add Middleware

Intercept requests on your server. If payment is missing, return `402 Payment Required` with the `WWW-Authenticate` header.

3. Handle Client Response

On the client (or agent), detect 402, parse the header, sign the payment, and retry the request with the proof.

Live Test Endpoint

You can test your agent or script against our live endpoint. It will always return 402 Payment Required with valid payment details for the Base network.

GET /api/x402CORS Enabled
curl -i https://402payment-test.com/api/x402
Returns headers: WWW-Authenticate: x402 address="..." amount="0.01" token="..."

Code Examples

Node.js Client

viem / ethers
async function fetchWith402(url) {
  let res = await fetch(url);

  if (res.status === 402) {
    console.log("Payment Required");
    
    // 1. Parse Payment Details
    const auth = res.headers.get('WWW-Authenticate');
    // Example header: x402 address="0x...", amount="0.01", token="USDC"
    const { address, amount, token } = parseAuth(auth);

    // 2. Make Payment
    // Using viem or ethers to send transaction
    const txHash = await wallet.sendTransaction({
      to: address,
      value: parseEther(amount) // if native
      // or writeContract for USDC transfer
    });

    console.log("Paid:", txHash);

    // 3. Retry with Proof
    res = await fetch(url, {
      headers: {
        'Authorization': `x402-proof ${txHash}`
      }
    });
  }

  return res.json();
}

function parseAuth(header) {
  // Simple regex parser
  const address = header.match(/address="([^"]+)"/)[1];
  const amount = header.match(/amount="([^"]+)"/)[1];
  return { address, amount };
}

Python Client

requests / web3.py
import requests
from web3 import Web3

def fetch_with_402(url):
    res = requests.get(url)

    if res.status_code == 402:
        print("Payment Required")

        # 1. Parse Header
        auth = res.headers['WWW-Authenticate']
        details = parse_auth_header(auth)

        # 2. Pay
        # Using web3.py
        tx_hash = w3.eth.send_transaction({
            'to': details['address'],
            'value': w3.to_wei(details['amount'], 'ether')
        })
        
        print(f"Paid: {tx_hash.hex()}")

        # 3. Retry with Proof
        headers = {
            'Authorization': f'x402-proof {tx_hash.hex()}'
        }
        res = requests.get(url, headers=headers)

    return res.json()

def parse_auth_header(header):
    # Implementation of parsing logic
    # Returns dict with address, amount, etc.
    pass
Read Official Documentation