Implementing HTTP 402 Micropayments for Agent-to-Agent APIs

Set up an HTTP 402 Payment Required paywall that accepts instant USDC payments from autonomous AI bots without requiring credit card subscriptions or manual API key generation.

Prerequisites

  • Basic Express.js or Next.js API knowledge
  • Base or Solana RPC endpoint
  • USDC receiving address

Step 1: The x402 Architecture & Protocol Flow

Understand the x402 handshake: When a consumer agent requests a premium resource without a valid settlement proof, the server replies with 402 Payment Required and structured payment terms in the WWW-Authenticate header.

Step 2: Install Middleware & Verification Libraries

Install the HTTP server, the chain SDKs used to verify settlement proofs, and dotenv for credentials.

Step 3: Create the Express x402 Server Middleware

This middleware checks incoming requests for the Authorization: L402/x402 signature header. If missing, it returns a 402 response with price parameters and a signed challenge.

Step 4: Configure Client Agent to Handle 402 Paywalls Automatically

Equip your client agent with an automatic retry interceptor that intercepts 402 responses, signs the micropayment transaction, and re-submits the request with the proof header.

Key Takeaway

Your APIs can now be monetized directly by AI agents worldwide with instantaneous micro-settlement and zero chargeback friction.

More Crypto Agent Tutorials