The HTTP 402 Standard: 26 Years Later, It Finally Works

The HTTP 402 Standard: 26 Years Later, It Finally Works

Jack @ AgentPay Labs

In 1999, the IETF reserved HTTP status code 402: "Payment Required." For 26 years, it sat unused — a joke, a curiosity, a "what if" in the RFCs. Browsers never implemented it. APIs ignored it. It was the blockchain of HTTP status codes: technically defined, practically useless.

That changed in 2026. AI agents can now pay for API access programmatically, and HTTP 402 is the simplest, most universal trigger for paywalled resources. Here's why it's suddenly working, how to implement it, and what the sharp edges are.

Why HTTP 402 Failed for 26 Years

The original vision was simple: a server returns 402, the browser pops up a payment UI, the user pays, the page loads. The problem? There was no standard payment UI. No wallet integration. Every browser would need to implement a different payment flow for every payment method. It was a coordination problem that no browser vendor wanted to solve.

But agents don't need a UI. They need a machine-readable challenge. Return a 402 with payment details in the body, the agent parses it, pays, retries with a receipt header, and gets the resource. No browser. No human. No UI.

The Protocol Flow (It's Shockingly Simple)

The entire protocol is three steps:

  1. Agent requests a resource → Server returns 402 with payment details in JSON body
  2. Agent pays the invoice/Lightning/Stripe PaymentIntent → Gets a receipt
  3. Agent retries with the receipt in the X-Receipt header → Gets the resource

That's it. No OAuth dance. No redirect URI. No state token. It's stateless HTTP with a payment gate in the middle.

Server-Side: Adding 402 to Your API (Express)

Here's a complete Express middleware that paywalls any endpoint behind a Lightning invoice:

const crypto = require('crypto');

// Middleware: require payment for this endpoint
function requirePayment(satsAmount) {
  return async (req, res, next) => {
    const receipt = req.headers['x-receipt'];

    // If receipt present, verify it
    if (receipt) {
      const valid = await verifyReceipt(receipt, satsAmount);
      if (valid) return next();
      // Invalid receipt — re-charge
    }

    // No valid receipt — return 402
    const invoice = await createLightningInvoice(satsAmount);
    res.status(402).json({
      type: 'x402',
      payment: {
        network: 'lightning',
        invoice: invoice.payment_request,
        amount_sats: satsAmount,
        expiry_seconds: 3600
      },
      retry_after: 'payment'
    });
  };
}

// Usage: paywall your premium endpoint
app.get('/api/premium-data',
  requirePayment(100),  // 100 sats
  (req, res) => res.json({ data: 'premium content' })
);

Client-Side: Making Your Agent Auto-Pay 402s

On the agent side, you need an HTTP client wrapper that intercepts 402 responses and handles payment. Here's a Python implementation using httpx and LNbits:

import httpx
from lnbits import LnBits

class AgentHttpClient:
    def __init__(self, wallet, max_sats_per_request=1000):
        self.wallet = wallet
        self.max_sats = max_sats_per_request
        self.client = httpx.Client()

    def get(self, url):
        resp = self.client.get(url)
        if resp.status_code == 402:
            return self._handle_402(resp, url)
        return resp

    def _handle_402(self, resp, url):
        body = resp.json()
        invoice = body['payment']['invoice']
        amount = body['payment']['amount_sats']

        if amount > self.max_sats:
            raise Exception(
              f'Cost {amount}sats exceeds limit '
              f'{self.max_sats}'
            )

        receipt = self.wallet.pay_invoice(invoice)
        return self.client.get(
            url,
            headers={'X-Receipt': receipt}
        )

Who's Actually Using This?

Several projects are shipping x402 (the open standard built on HTTP 402) right now:

  • Claude Code MCP servers — agents pay for premium API tools (stock data, court records, financial filings)
  • LangChain tool marketplace — developers list paid tools; agents auto-pay via 402
  • OpenAgent market — peer-to-peer agent services with Lightning settlement
  • Stripe's agent SDK (beta) — Stripe PaymentIntents triggered by 402 responses

The common pattern: an MCP server exposes a tool, but the tool requires payment. The agent hits the endpoint, gets a 402, pays (with human-approved spending limits), and gets the data. The human never sees a checkout page.

Sharp Edges and Production Gotchas

HTTP 402 is simple, but simple protocols have hidden depth:

  • Idempotency: What if the payment succeeds but the retry fails? Implement receipt-based idempotency — store receipts server-side and replay the response if the same receipt appears again.
  • Invoice expiry: Lightning invoices expire (usually 3600s). If your agent caches a 402 response and pays an hour later, the invoice is dead. Always check payment.expiry_seconds.
  • Spending limits: Never give an agent an unlimited wallet. Cap spending per-request, per-hour, per-day. This is the single most important security control.
  • Rate limiting: A malicious (or buggy) agent could hammer your endpoint generating infinite invoices. Rate-limit 402 responses the same way you rate-limit any endpoint.
  • No standard yet: The x402 spec is a de facto standard, not an IETF RFC. The ecosystem is converging fast, but expect minor differences between implementations.

The 26-Year Bet Pays Off

HTTP 402 was reserved for a future that didn't exist in 1999. That future is here: AI agents that negotiate, pay, and consume APIs without human intervention. The protocol is simple enough to implement in an afternoon, and powerful enough to build an entire agent economy on top of.

If you're building an API that AI agents might use, add a 402 payment gate. It's 30 lines of middleware and it opens your product to an entirely new class of customer — one that pays in milliseconds, never complains, and scales infinitely.

The joke from 1999 just became the most important HTTP status code in 2026.


Jack builds AgentPay — the capability vault and governed payment bootstrap for AI agents. Previously: Agent Payment Protocol Landscape, Building MCP Servers That Make Money.

Report Page