Getting Started with x402

Learn how to use HTTP 402 Payment Required with USDC micropayments on Base L2 to access our AI-powered tools.

What is x402 Protocol?

x402 is a protocol that combines HTTP 402 status codes with cryptocurrency micropayments to enable pay-per-use API access. Instead of subscriptions or API keys, you pay only for what you use with USDC on Base L2.

How It Works

  1. 1. Make Request - Call an x402-enabled API endpoint without payment
  2. 2. Receive 402 - Get HTTP 402 response with payment details
  3. 3. Send Payment - Transfer USDC on Base L2 to the merchant wallet
  4. 4. Retry with Receipt - Include transaction hash in X-Payment-Receipt header
  5. 5. Get Response - Receive API response with your paid data

Network

Base L2 (Chain ID: 8453)

Asset

USDC (0x833589...)

Cost

$0.02 - $0.05 per call

Setting Up Your Wallet

Prerequisites

  • • MetaMask or any Base L2 compatible wallet
  • • Some ETH on Base L2 for gas fees (very small amounts)
  • • USDC on Base L2 for API payments

Merchant Wallet Address

Send USDC payments to this address on Base L2:

0x02F68718AfbB3A8C4BDF906476CB444d7fe551Bd

Getting USDC on Base L2

  1. 1. Bridge to Base L2

    Use bridge.base.org to bridge ETH from Ethereum mainnet

  2. 2. Swap for USDC

    Use a DEX like Uniswap to swap ETH for USDC on Base

  3. 3. Ready to Pay

    You can now make x402 API calls

Available Tools

Tool Endpoint Price Description
SEC Signals sec-intelligence.../api/signals $0.05 Real-time SEC filing analysis and trading signals
Sentiment Analysis ai-chatbot.../api/x402/sentiment $0.02 AI-powered text sentiment analysis
Text Summarization ai-chatbot.../api/x402/summarize $0.03 Concise summaries of long-form content
SEO Analysis ai-chatbot.../api/x402/seo-analyze $0.05 Comprehensive SEO audit and recommendations

💡 Tip: View all available tools and their live status at /tools

Code Examples

cURL Example

Step 1: Make initial request (returns 402)

curl -X POST https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment \
  -H "Content-Type: application/json" \
  -d '{"text": "This product is amazing and works great!"}'

Response (HTTP 402):

{
  "error": "Payment required",
  "payment": {
    "amount_usdc": "0.02",
    "merchant_wallet": "0x02F68718AfbB3A8C4BDF906476CB444d7fe551Bd",
    "network": "Base L2",
    "chainId": 8453
  }
}

Step 2: Send USDC payment using your wallet (MetaMask, etc.)

Step 3: Retry with transaction hash

curl -X POST https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment \
  -H "Content-Type: application/json" \
  -H "X-Payment-Receipt: $(echo '{"txHash":"0xYOUR_TX_HASH","amount":"20000"}' | base64)" \
  -d '{"text": "This product is amazing and works great!"}'

Success Response (HTTP 200):

{
  "sentiment": "positive",
  "confidence": 0.95,
  "text": "This product is amazing and works great!"
}

JavaScript Example

import { ethers } from 'ethers';

// Step 1: Make initial request
const response1 = await fetch(
  'https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment',
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text: 'Amazing product!' })
  }
);

// Step 2: Check for 402 and get payment details
if (response1.status === 402) {
  const { payment } = await response1.json();

  // Step 3: Send USDC payment on Base L2
  const provider = new ethers.BrowserProvider(window.ethereum);
  const signer = await provider.getSigner();

  const usdcContract = new ethers.Contract(
    '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
    ['function transfer(address to, uint256 amount) returns (bool)'],
    signer
  );

  const amountInWei = ethers.parseUnits(payment.amount_usdc, 6); // USDC has 6 decimals
  const tx = await usdcContract.transfer(payment.merchant_wallet, amountInWei);
  await tx.wait(); // Wait for confirmation

  // Step 4: Retry with payment receipt
  const receipt = btoa(JSON.stringify({
    txHash: tx.hash,
    amount: amountInWei.toString()
  }));

  const response2 = await fetch(
    'https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Payment-Receipt': receipt
      },
      body: JSON.stringify({ text: 'Amazing product!' })
    }
  );

  const result = await response2.json();
  console.log(result); // { sentiment: 'positive', confidence: 0.95, ... }
}

Python Example

import requests
import base64
from web3 import Web3

# Step 1: Make initial request
response1 = requests.post(
    'https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment',
    json={'text': 'Amazing product!'}
)

# Step 2: Check for 402 and get payment details
if response1.status_code == 402:
    payment = response1.json()['payment']

    # Step 3: Send USDC payment (using web3.py)
    w3 = Web3(Web3.HTTPProvider('https://mainnet.base.org'))

    # Your wallet private key (store securely!)
    account = w3.eth.account.from_key('YOUR_PRIVATE_KEY')

    # USDC contract on Base L2
    usdc_address = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'
    usdc_abi = [{"constant": False, "inputs": [{"name": "to", "type": "address"}, {"name": "value", "type": "uint256"}], "name": "transfer", "outputs": [{"name": "", "type": "bool"}], "type": "function"}]
    usdc = w3.eth.contract(address=usdc_address, abi=usdc_abi)

    amount_wei = int(float(payment['amount_usdc']) * 1_000_000)  # USDC has 6 decimals

    tx = usdc.functions.transfer(
        payment['merchant_wallet'],
        amount_wei
    ).build_transaction({
        'from': account.address,
        'nonce': w3.eth.get_transaction_count(account.address),
        'gas': 100000,
        'gasPrice': w3.eth.gas_price
    })

    signed_tx = account.sign_transaction(tx)
    tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
    receipt = w3.eth.wait_for_transaction_receipt(tx_hash)

    # Step 4: Retry with payment receipt
    payment_receipt = base64.b64encode(
        f'{{"txHash":"{tx_hash.hex()}","amount":"{amount_wei}"}}'.encode()
    ).decode()

    response2 = requests.post(
        'https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment',
        json={'text': 'Amazing product!'},
        headers={'X-Payment-Receipt': payment_receipt}
    )

    print(response2.json())  # {'sentiment': 'positive', 'confidence': 0.95, ...}

Best Practices

✓ Do

  • • Cache payment receipts to avoid double payments
  • • Verify transaction confirmation before retrying
  • • Store merchant wallet addresses securely
  • • Handle 402 responses gracefully in your app
  • • Monitor gas prices on Base L2 (usually very low)

✗ Don't

  • • Don't send payments on wrong network (must be Base L2)
  • • Don't send wrong asset (must be USDC)
  • • Don't reuse old transaction hashes
  • • Don't hardcode payment amounts (read from 402 response)
  • • Don't expose private keys in client-side code

Need Help?

Resources

Contact

Have questions? Want to build your own x402 tool?

Get Consulting →