DEV Community

duongynhi000005-oss
duongynhi000005-oss

Posted on

Implementing HTTP 402 (x402) Autonomous AI Agent Micropayments on Cloudflare Edge Workers

Why HTTP 402 Payment Required Finally Has a Real Standard (x402)

For decades, HTTP status code 402 Payment Required was reserved for future use. Today, autonomous AI agents need to call external APIs (Markdown extraction, DNS/MX fraud verification, IBAN/crypto checksum validation, and schema intelligence) without human intervention, credit card forms, or OAuth signups.

With the x402 protocol, an API endpoint can serve both traditional API marketplaces (like RapidAPI) and autonomous on-chain AI agents from a single Cloudflare Edge Worker.


Dual-Mode Authentication Pattern: RapidAPI Header + x402 Payment Gate

Here is the exact pattern we deployed across our 4 production Cloudflare Workers so that:

  1. GET /openapi.json and GET /.well-known/x402 return 200 OK for indexers and registries.
  2. Requests carrying X-RapidAPI-Proxy-Secret or X-RapidAPI-Host are served immediately.
  3. Unauthenticated agent requests receive a standard HTTP 402 Payment Required response with the PAYMENT-REQUIRED header specifying the Base USDC payment requirements:
if (url.pathname === "/openapi.json") {
  return new Response(JSON.stringify(OPENAPI_SPEC, null, 2), {
    status: 200,
    headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }
  });
}

const hasRapidHeader = request.headers.get("X-RapidAPI-Proxy-Secret") || request.headers.get("X-RapidAPI-Host");
const hasX402Payment = request.headers.get("X-PAYMENT") || request.headers.get("Payment");

if (!hasRapidHeader && !hasX402Payment && url.pathname.startsWith("/v1/")) {
  const x402Payload = {
    x402Version: 1,
    accepts: [{
      scheme: "exact",
      network: "base",
      maxAmountRequired: "10000", // $0.01 USDC (6 decimals)
      resource: request.url,
      payTo: "0x10357C508BEEC1AC2353daD50fdD7641A4DC6925",
      asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
    }]
  };
  return new Response(JSON.stringify(x402Payload), {
    status: 402,
    headers: {
      "Content-Type": "application/json",
      "PAYMENT-REQUIRED": btoa(JSON.stringify(x402Payload))
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Live Production Endpoints

You can test the dual-mode /openapi.json and 402 Payment Required handshake live at the edge:

  • https://rapidapi-fintech-iban-vat-crypto-validator-worker.antibot-scraper-worker.workers.dev/openapi.json
  • https://rapidapi-llm-web-extractor-worker.antibot-scraper-worker.workers.dev/openapi.json
  • https://rapidapi-email-fraud-guard-worker.antibot-scraper-worker.workers.dev/openapi.json
  • https://rapidapi-seo-techstack-intel-worker.antibot-scraper-worker.workers.dev/openapi.json

Top comments (0)