# x402 Explained: HTTP-Native Micropayments for AI Agents (With Real Code)

> Source: <https://dev.to/nikhilranka23/x402-explained-http-native-micropayments-for-ai-agents-with-real-code-28d6>
> Published: 2026-09-07 08:17:28+00:00

When autonomous AI agents need to call external services—LLM inference, data feeds, compute functions—they often encounter two practical problems:

The x402 specification addresses both by embedding a lightweight payment handshake directly into HTTP status codes. Agents can discover a price, pay it with a stablecoin, and receive the requested resource—all without leaving the HTTP request/response flow.

x402 is an extension of the HTTP status code space. It repurposes the **402 Payment Required** code (originally reserved for future use) to signal that a resource is behind a paywall. The response includes a `WWW-Authenticate` header that conveys:

`x402`).
Upon receiving a 402, the client can:

`Authorization` header.
Because the flow stays within HTTP, existing libraries, proxies, and caching layers continue to work unchanged—only the client needs to understand the 402 flow.

| Component | Role | 
|---|---|
| **Resource Server** | Exposes endpoints that may return 402. Holds a price list and validates payments. | 
| **Payment Processor** | Usually a smart contract on a low‑cost L2 (e.g., Base) that escrowed USDC and emits an event on successful transfer. | 
| **Client (Agent)** | Implements the 402 handshake: reads the challenge, signs/pays, retries with proof. | 
| **Metadata** | The `WWW-Authenticate` header contains a JSON object (`x402` scheme) with fields:`amount` ,`asset` ,`network` ,`paymentPointer` ,`maxTimeout` . | 

```
WWW-Authenticate: x402 amount="0.05", asset="USDC", network="base:8453", paymentPointer="pay:0xA1b2.../invoice"
```

`Cache-Control: no-store` for paid resources to avoid stale content.
These trade‑offs mean x402 is best suited for services where the per‑call cost is low enough to absorb the blockchain overhead, and where agents can tolerate a few seconds of latency for guaranteed payment.

Below is a self‑contained example that demonstrates:

`/summarize` endpoint with x402.
**Note**: For brevity, the payment processor is a mock contract that simply records the payer and amount. In production you would deploy a real ERC‑20 escrow contract (e.g., OpenZeppelin’s `ERC20Votes` with a `receive()` fallback) and verify the transaction via an RPC call or a subgraph.

`server.js`)

``` js
// server.js
const express = require('express');
const app = express();
const PORT = 3000;

// Mock price: $0.05 USDC per call
const PRICE_USDC = BigInt('5000000'); // 6 decimals => 0.05 * 1e6
const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; // Base USDC

app.use(express.json());

function x402Challenge() {
  return `x402 amount="${Number(PRICE_USDC/1e6)}", asset="USDC", network="base:8453", paymentPointer="pay:${USDC_ADDRESS}/invoice"`;
}

// Protect endpoint
app.get('/summarize', (req, res) => {
  const auth = req.headers.authorization || '';
  // Expect proof: "x402 <txHash>"
  if (!auth.startsWith('x402 ')) {
    return res.status(402)
              .set('WWW-Authenticate', x402Challenge())
              .json({error: 'Payment required'});
  }
  const txHash = auth.slice(5);
  // In real code: verify txHash on-chain, confirm amount >= PRICE_USDC, and that sender is allowed.
  // Here we just accept any hash for demo.
  res.json({summary: 'This is a dummy summary of the requested content.'});
});

app.listen(PORT, () => console.log(`Server listening on :${PORT}`));
```

`agent.js`)

``` js
javascript
// agent.js
const fetch = require('node-fetch');
const { ethers } = require('ethers');

// Configure provider (Base Sepolia testnet for demo)
const provider = new ethers.JsonRpcProvider('https://sepolia.base.org');
const USDC_ABI = [
  "function balanceOf(address) view returns (uint256)",
  "function transfer(address to, uint256 amount) returns (bool)"
];
const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const USDC = new ethers.Contract(USDC_ADDRESS, USDC_ABI, provider);

// Wallet funded with USDC on Base Sepolia (replace with your own)
const PRIVATE_KEY = '0xYOUR_PRIVATE_KEY';
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);
const usdcWithSigner = USDC.connect(wallet);

async function callSummarize(text) {
  const url = 'http://localhost:3000/summarize';
  let attempts = 0;
  while (true) {
    attempts++;
    const resp = await fetch(url, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    });
    if (resp.ok) {
      const data = await resp.json();
      return data.summary;
    }
    if (resp.status !== 402) {
      throw new Error(`Unexpected status ${resp.status}`);
    }
    // Parse challenge
    const wwwAuth = resp.headers.get('www-authenticate') || '';
    const match = wwwAuth.match(/amount="([^"]+)"/);
    if (!match) throw new Error('Malformed 402 challenge');
    const amountUSDC = parseFloat(match[1]); // e.g., 0.05
    const amountWei = ethers.parseUnits(amountUSDC.toString(), 6); // USDC has 6 decimals

    // Ensure we have enough balance
    const bal = await USDC.balanceOf(wallet.address);
    if (bal < amountWei) {
      throw new Error(`Insufficient USDC balance: ${ethers.formatUnits(bal,6)} < ${amountUSDC}`);
    }

    // Send payment (mock: just transfer to a fixed payee)
    const payee = '0xPayeeAddressHere'; // In real scenario, this is the escrow contract
    const tx = await usdcWithSigner.transfer(payee, amountWei);
    await tx.wait(); // wait for inclusion on Base (~2s)

    // Retry with proof
    const authHeader = `x402 ${tx.hash}`;
    console.log(`Paid ${amountUSDC} USDC (tx ${tx.hash}), retrying…`);
    const secondResp = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': authHeader
      }
    });
    if (secondResp.ok) {
      return (await secondResp.json()).summary;
    }
    // If still 402, something went wrong; break to avoid loop
    throw new Error('Payment not recognized by server');
  }
}

// Example usage
(async () => {
  try {
    const summary = await callSummarize('Explain quantum entanglement in two sentences.');
    console.log('Result:', summary);
  } catch (e) {
    console.error('Failed:', e.message);
  }
```


