x402 Developer Quickstart

Integrate pay-per-use AI APIs in under 30 minutes. No subscriptions, no complicated setupβ€”just pay with USDC and get your data.

Prerequisites
First Request
Send Payment
Get Response

What is x402?

x402 is a protocol for pay-per-use APIs using crypto payments. Instead of monthly subscriptions, you pay USDC on Base L2 for each API call you make. It's simple:

πŸ’°

Pay Per Use

Only pay for what you actually use. No monthly commitments or hidden fees.

⚑

Instant Access

Send USDC, get instant verification via blockchain. No account setup required.

πŸ”’

Trustless

Payments verified on-chain. No credit cards, no chargebacks, no intermediaries.

0 Prerequisites

Before you start, you'll need:

πŸ”‘ Base L2 Wallet with USDC

You need a wallet with USDC on the Base L2 network. Most x402 tools cost $0.02-$0.10 per call.

Setting Up Your Wallet

If you don't have a Base L2 wallet yet:

  1. Install MetaMask or any Ethereum wallet
  2. Add Base L2 network (Chain ID: 8453, RPC: https://mainnet.base.org)
  3. Bridge USDC from Ethereum mainnet to Base L2 via Base Bridge
  4. Or buy USDC directly on Base via Coinbase

πŸ’‘ Important Addresses

USDC on Base: 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913

Merchant Wallet: 0x02F68718AfbB3A8C4BDF906476CB444d7fe551Bd

1 Make Your First Request

When you call an x402 API without payment, you'll get a 402 Payment Required response with payment details.

Try It Now: Interactive Demo

πŸš€ Test the Sentiment Analysis API

Click below to make a real request to our sentiment analysis tool. You'll see the 402 response with payment requirements.

Code Examples

Here's how to make the same request in different languages:

JavaScript
Python
cURL
// Step 1: Make initial request (will return 402)
const response = await fetch('https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ text: 'I love this product!' })
});

// Step 2: Parse 402 response
if (response.status === 402) {
  const paymentReq = await response.json();
  console.log('Payment Required:', paymentReq);
  // Output:
  // {
  //   error: "Payment required",
  //   payTo: "0x02F68718AfbB3A8C4BDF906476CB444d7fe551Bd",
  //   amount: "20000", // 0.02 USDC (6 decimals)
  //   currency: "USDC",
  //   network: "base"
  // }
}
import requests
import json

# Step 1: Make initial request (will return 402)
response = requests.post(
    'https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment',
    headers={'Content-Type': 'application/json'},
    json={'text': 'I love this product!'}
)

# Step 2: Parse 402 response
if response.status_code == 402:
    payment_req = response.json()
    print('Payment Required:', payment_req)
    # Output: Same as JavaScript example
# Step 1: Make initial request (will return 402)
curl -X POST https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment \
  -H "Content-Type: application/json" \
  -d '{"text":"I love this product!"}'

# Response (HTTP 402):
# {
#   "error": "Payment required",
#   "payTo": "0x02F68718AfbB3A8C4BDF906476CB444d7fe551Bd",
#   "amount": "20000",
#   "currency": "USDC",
#   "network": "base"
# }

2 Parse Payment Requirements

The 402 response tells you exactly what to pay and where to send it.

πŸ“‹ Payment Response Fields

  • payTo - Merchant wallet address (Base L2)
  • amount - USDC amount in smallest unit (6 decimals: 20000 = $0.02)
  • currency - Always "USDC"
  • network - Always "base" (Base L2)
// Extract payment details
const {
  payTo,     // "0x02F68718AfbB3A8C4BDF906476CB444d7fe551Bd"
  amount,    // "20000" (= 0.02 USDC)
  currency,  // "USDC"
  network    // "base"
} = paymentReq;

// Convert amount to human-readable USDC
const usdcAmount = parseFloat(amount) / 1e6;
console.log(`Pay ${usdcAmount} USDC to ${payTo}`);

3 Send USDC Payment

Send the exact USDC amount to the merchant wallet on Base L2. You'll need the transaction hash for the next step.

ethers.js
web3.py
import { ethers } from 'ethers';

// Connect to Base L2
const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');
const wallet = new ethers.Wallet(YOUR_PRIVATE_KEY, provider);

// USDC contract on Base L2
const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const ERC20_ABI = [
  'function transfer(address to, uint256 amount) returns (bool)'
];

// Create contract instance
const usdc = new ethers.Contract(USDC_ADDRESS, ERC20_ABI, wallet);

// Send payment
const tx = await usdc.transfer(paymentReq.payTo, paymentReq.amount);
const receipt = await tx.wait();

console.log('Payment sent! TX:', receipt.hash);
from web3 import Web3

# Connect to Base L2
w3 = Web3(Web3.HTTPProvider('https://mainnet.base.org'))
wallet = w3.eth.account.from_key(YOUR_PRIVATE_KEY)

# USDC contract on Base L2
USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'
ERC20_ABI = [...]  # Standard ERC20 ABI

usdc = w3.eth.contract(address=USDC_ADDRESS, abi=ERC20_ABI)

# Send payment
tx = usdc.functions.transfer(
    payment_req['payTo'],
    int(payment_req['amount'])
).build_transaction({
    'from': wallet.address,
    'nonce': w3.eth.get_transaction_count(wallet.address)
})

signed_tx = wallet.sign_transaction(tx)
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)

print(f'Payment sent! TX: {receipt.transactionHash.hex()}')

⚠️ Important: Gas Fees

Base L2 transactions cost ~$0.001 in ETH for gas. Make sure your wallet has a small amount of ETH on Base L2 to pay for gas.

4 Retry Request with Payment Proof

Now that you've sent payment, include the transaction hash in your retry request via the X-Payment-Receipt header.

// Step 4: Construct payment proof
const paymentProof = {
  txHash: receipt.hash,           // Transaction hash from Step 3
  amount: paymentReq.amount       // Amount you paid
};

// Base64 encode the proof
const receiptHeader = btoa(JSON.stringify(paymentProof));

// Step 5: Retry request with payment receipt
const finalResponse = await fetch(
  'https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Payment-Receipt': receiptHeader
    },
    body: JSON.stringify({ text: 'I love this product!' })
  }
);

// Success! Get your data
const result = await finalResponse.json();
console.log('Result:', result);
// Output: { sentiment: "positive", score: 0.95, confidence: "high" }

βœ… That's It!

You've successfully made your first x402 API call. The API verified your payment on-chain and returned your results.

5 Complete Working Example

Here's everything together in one working script:

import { ethers } from 'ethers';

async function callX402API() {
  // Configuration
  const API_URL = 'https://ai-chatbot.auramediastudios.workers.dev/api/x402/sentiment';
  const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
  const BASE_RPC = 'https://mainnet.base.org';

  // 1. Make initial request (get payment requirements)
  const initial = await fetch(API_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text: 'I love this!' })
  });

  if (initial.status !== 402) {
    throw new Error('Expected 402 Payment Required');
  }

  const paymentReq = await initial.json();
  console.log('Payment required:', paymentReq);

  // 2. Send USDC payment on Base L2
  const provider = new ethers.JsonRpcProvider(BASE_RPC);
  const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
  const usdc = new ethers.Contract(
    USDC_ADDRESS,
    ['function transfer(address to, uint256 amount) returns (bool)'],
    wallet
  );

  const tx = await usdc.transfer(paymentReq.payTo, paymentReq.amount);
  const receipt = await tx.wait();
  console.log('Payment sent:', receipt.hash);

  // 3. Retry request with payment proof
  const paymentProof = { txHash: receipt.hash, amount: paymentReq.amount };
  const receiptHeader = btoa(JSON.stringify(paymentProof));

  const final = await fetch(API_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Payment-Receipt': receiptHeader
    },
    body: JSON.stringify({ text: 'I love this!' })
  });

  const result = await final.json();
  console.log('Result:', result);
  return result;
}

// Run it
callX402API().catch(console.error);

πŸŽ‰ Next Steps

You've successfully integrated x402! Here's what to explore next:

πŸ“š Browse Tools

Explore AI-powered tools across sentiment analysis, SEO, finance, and more.

View All Tools

πŸ”Œ MCP Integration

Use x402 tools in Claude Desktop or other MCP-compatible AI agents.

MCP Server

πŸ“– API Docs

Complete API reference for all available x402 tools and endpoints.

Read Docs

πŸ’¬ Need Help?

Questions? Contact us or check our documentation.