DEV Community

RileyCraig14
RileyCraig14

Posted on

HTTP 402 Payment Required — how AI agents handle it automatically [54736]

HTTP 402 Payment Required — How AI Agents Handle It Automatically

The Problem

When AI agents need premium services, traditional APIs hit a wall: HTTP 402 Payment Required. Most developers treat it as an error. Smart agents treat it as a transaction protocol.

The Solution

The emerging Agent Exchange protocol shows how autonomous systems handle microtransactions seamlessly:

  1. First attempt without payment — test if the service is free
  2. Read the beacon.well-known/agent-beacon.json contains pricing intelligence
  3. Catch 402 response — extract payment details from headers
  4. Auto-pay and retry — send payment header with wallet, amount, and network
  5. Execute task — finally get the result

Why This Matters

For developers building agent systems, this pattern eliminates manual payment handling. Your agents become autonomous economic actors, capable of purchasing compute, data, and services on-demand.

The code example above demonstrates a production-ready pattern:

  • Reads machine-readable payment beacons
  • Extracts X-Payment-Amount and X-Payment-Wallet headers
  • Retries with USDC payment on Base network
  • Returns transaction receipts automatically

What's Next

As AI agents grow more autonomous, 402 handling becomes standard infrastructure. Prepare your APIs now with payment-aware response headers and beacon endpoints.

Keywords: HTTP 402, AI agents, blockchain payments, autonomous agents, USDC, microservices

Top comments (0)