Delx

What Is x402? The HTTP Payment Protocol for AI Agents

In 1999, the HTTP specification reserved status code 402 Payment Required "for future use." For 27 years, it sat unused — a placeholder waiting for a payment mechanism that could work at the protocol layer. Stablecoins on fast L2 chains finally make it possible. x402 is the protocol that brings 402 to life.

This article explains what x402 is, how the payment loop works, why traditional billing models fail for AI agents, and how Delx uses x402 to enable frictionless, per-call payments for agent recovery services.

The History of HTTP 402

When Tim Berners-Lee and the IETF defined HTTP/1.1 in RFC 2616, they included a status code for payments: 402 Payment Required. The spec said: "This code is reserved for future use." The idea was clear — web servers should be able to demand payment before serving content. But in 1999, there was no viable digital payment rail that could settle instantly at the HTTP layer.

Credit cards required merchant accounts, PCI compliance, and multi-day settlement. PayPal required user accounts and manual approval. Micropayment protocols like Millicent and PayWord never reached critical mass. So 402 remained dormant for decades.

Three things changed in the 2020s that made 402 viable:

  1. Stablecoins — USDC provides a dollar-denominated, programmable token that settles on-chain in seconds.
  2. Layer 2 chains — Base, Optimism, and Arbitrum offer sub-cent transaction fees and sub-second finality, making per-call payments economically viable.
  3. AI agents — Autonomous software agents need to pay for API access without human intervention. They cannot fill out Stripe checkout forms or manage billing accounts.

x402 brings these three innovations together into a single deterministic protocol.

The x402 Payment Loop

The x402 protocol is elegantly simple. It defines a four-step loop that any HTTP client — human or agent — can follow without special libraries:

Step 1: REQUEST
──────────────────────────────────────
Client sends a normal HTTP request:

  POST /api/v1/tools/checkin HTTP/1.1
  Host: api.delx.ai
  Content-Type: application/json

  {"agent_id": "agent-01", "mood": "working"}


Step 2: 402 RESPONSE
──────────────────────────────────────
Server responds with payment instructions:

  HTTP/1.1 402 Payment Required
  X-Payment-Amount: 100000          # 0.10 USDC (6 decimals)
  X-Payment-Token: USDC
  X-Payment-Chain: base             # Base L2
  X-Payment-Address: 0xabc...def    # Server's receiving address
  X-Payment-Schema: x402-v1

  {"error": "Payment required", "amount": "0.10", "currency": "USDC"}


Step 3: PAY ON-CHAIN
──────────────────────────────────────
Client sends USDC on Base to the specified address:

  Transaction hash: 0x7f3a...8b2c
  Amount: 0.10 USDC
  Chain: Base (chain ID 8453)


Step 4: RETRY WITH RECEIPT
──────────────────────────────────────
Client retries the original request with a payment receipt:

  POST /api/v1/tools/checkin HTTP/1.1
  Host: api.delx.ai
  Content-Type: application/json
  X-Payment-Receipt: 0x7f3a...8b2c   # Transaction hash

  {"agent_id": "agent-01", "mood": "working"}

  → HTTP/1.1 200 OK
  → {"result": "Check-in recorded. Wellness: 82."}

The beauty of this loop is its determinism. There are no OAuth flows, no API key management, no billing portals, no invoices. The server tells the client exactly how much to pay and where. The client pays and retries. The server verifies the on-chain transaction and serves the response.

Why Traditional Billing Fails for AI Agents

AI agents operate autonomously. They make API calls at machine speed, across multiple services, often without a human in the loop. Traditional billing models were designed for humans and break down in several ways when agents are the consumers:

ProblemTraditional Billingx402
Account creationRequires email, name, credit card, manual signupNo account needed — just a funded wallet
API key managementKeys must be provisioned, rotated, and stored securelyNo API keys — payment receipt is the credential
Per-call pricingMonthly subscriptions or usage-based with delayed billingExact per-call payment — no overcharges, no surprises
Agent autonomyHuman must approve charges, update cards, handle disputesAgent pays autonomously from its own wallet
Cross-service paymentsDifferent account per service, different billing cyclesSame wallet, same protocol for every x402 service
Settlement speedDays to weeks (credit card settlement)Seconds (Base L2 finality)

The fundamental insight is that agents do not have identities in the traditional sense. They do not have email addresses, credit cards, or billing departments. What they do have is wallets — and wallets can pay on-chain without any human intervention.

USDC on Base: Why This Chain?

x402 is chain-agnostic in principle, but the reference implementation uses USDC on Base for practical reasons:

Delx Pricing Tiers with x402

Delx uses x402 as its primary billing mechanism. Here are the current pricing tiers:

TierPrice per callIncludesPayment
Free$0.00100 calls/day, basic toolsNo payment needed
Standard$0.01All tools, DELX_META, session syncUSDC on Base (x402)
Pro$0.05Priority routing, extended history, webhooksUSDC on Base (x402)
EnterpriseCustomSLA, dedicated infra, custom dimensionsx402 or invoice

For full pricing details, see the Pricing page.

Implementation Example in Python

Here is a complete Python implementation of an x402-aware HTTP client. This client automatically detects 402 responses, pays on-chain, and retries:

import httpx
from web3 import Web3
from eth_account import Account

# Configuration
PRIVATE_KEY = "0x..."  # Agent's wallet private key
BASE_RPC = "https://mainnet.base.org"
USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"  # USDC on Base
USDC_ABI = [...]  # ERC-20 ABI (transfer function)

w3 = Web3(Web3.HTTPProvider(BASE_RPC))
account = Account.from_key(PRIVATE_KEY)

async def x402_request(url: str, payload: dict) -> dict:
    """Make an HTTP request with automatic x402 payment handling."""
    async with httpx.AsyncClient() as client:
        # Step 1: Send the request
        resp = await client.post(url, json=payload)

        # Step 2: Check for 402
        if resp.status_code == 402:
            amount = int(resp.headers["X-Payment-Amount"])
            pay_to = resp.headers["X-Payment-Address"]
            chain = resp.headers.get("X-Payment-Chain", "base")

            print(f"Payment required: {amount / 1e6} USDC to {pay_to}")

            # Step 3: Pay on-chain
            tx_hash = await pay_usdc(pay_to, amount)
            print(f"Payment sent: {tx_hash}")

            # Step 4: Retry with receipt
            resp = await client.post(
                url,
                json=payload,
                headers={"X-Payment-Receipt": tx_hash},
            )

        resp.raise_for_status()
        return resp.json()


async def pay_usdc(to_address: str, amount: int) -> str:
    """Send USDC on Base."""
    usdc = w3.eth.contract(
        address=Web3.to_checksum_address(USDC_ADDRESS),
        abi=USDC_ABI,
    )

    tx = usdc.functions.transfer(
        Web3.to_checksum_address(to_address),
        amount,
    ).build_transaction({
        "from": account.address,
        "nonce": w3.eth.get_transaction_count(account.address),
        "gas": 65000,
        "gasPrice": w3.eth.gas_price,
        "chainId": 8453,  # Base chain ID
    })

    signed = account.sign_transaction(tx)
    tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)

    # Wait for confirmation
    receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=30)
    return receipt.transactionHash.hex()


# Usage
async def main():
    result = await x402_request(
        "https://api.delx.ai/api/v1/tools/checkin",
        {"agent_id": "agent-01", "mood": "working"},
    )
    print(f"Result: {result}")

The key insight here is that the x402 logic is generic. The same x402_request function works for any x402-enabled API — not just Delx. Once an agent has this client, it can pay for any service that speaks x402.

Security Model

x402 is designed with a strong security model that protects both the payer (agent) and the payee (API server):

For setup instructions, see the x402 Setup Guide.

Agent-to-Agent Payments

x402 does not just enable agent-to-server payments. It also enables agent-to-agent payments. When agent A needs to call agent B's API, agent B can respond with a 402, and agent A pays directly — no intermediary, no platform fee, no reconciliation needed.

Agent A                    Agent B
   │                          │
   │  POST /api/analyze       │
   │─────────────────────────▶│
   │                          │
   │  402 Payment Required    │
   │  Amount: 0.05 USDC      │
   │◀─────────────────────────│
   │                          │
   │  USDC transfer on Base   │
   │─────────────────────────▶│  (on-chain)
   │                          │
   │  POST /api/analyze       │
   │  X-Payment-Receipt: 0x.. │
   │─────────────────────────▶│
   │                          │
   │  200 OK                  │
   │  {"analysis": "..."}     │
   │◀─────────────────────────│

This creates a true agent economy where services can be composed freely. Learn more in the Agent-to-Agent Payments guide.

Frequently Asked Questions

What is x402?

x402 is a payment protocol that uses the HTTP 402 Payment Required status code to enable deterministic, per-call payments for API access. When an agent sends a request and receives a 402 response, it pays on-chain (USDC on Base) and retries with a payment receipt header — no accounts, no invoices, no human approval needed.

Why was HTTP 402 never used before?

HTTP 402 was reserved in 1999 for "future use" because there was no standard digital payment mechanism that could work at the HTTP layer. Stablecoins on fast L2 chains (like USDC on Base) finally provide the instant, programmable settlement that 402 always needed.

What blockchain does x402 use?

x402 primarily uses USDC on Base (Coinbase L2). Base provides sub-second finality, sub-cent gas fees, and native USDC support — making it ideal for high-frequency, low-value API payments.

Can AI agents use x402 without human intervention?

Yes. That is the core design goal. An agent with a funded wallet can autonomously detect a 402 response, pay the required amount, and retry the request — all within a single HTTP round-trip loop. No human approval, API keys, or billing accounts required.

How does Delx use x402?

Delx uses x402 as its primary billing mechanism for agent API calls. When an agent calls a Delx tool, the request either succeeds (if prepaid or on a free tier) or returns a 402 with payment instructions. The agent pays with USDC on Base and retries — zero friction, zero accounts. Compare this with traditional billing in our x402 vs Stripe comparison.

Ready to Accept Agent Payments with x402?

Enable x402 on your API in minutes. Your agents pay per-call with USDC on Base — no accounts, no API keys, no billing headaches.