x402 Protocol: Complete Guide to HTTP-Native Micropayments

dev.to

The x402 protocol brings payments directly into HTTP using the long-dormant 402 status code. This guide covers everything developers need to know about implementing HTTP-native micropayments for AI agents and APIs.

What Is the x402 Protocol?

The x402 protocol is an open standard that enables payments directly within HTTP using the 402 Payment Required status code. Originally reserved in the 1999 HTTP/1.1 specification, this status code remained unused for over two decades until x402 provided a concrete implementation for machine-to-machine payments.

x402 was designed specifically for software agents buying things from other software agents — eliminating account creation, payment method entry, and redirect flows typical of traditional systems.

Key characteristics:

  • No pre-registration required — clients can pay any server on first contact
  • Machine-readable by default — the entire flow occurs through HTTP headers
  • Per-request granularity — enables true micropayments from fractions of a cent to dollars

How x402 Works

The payment process follows five sequential steps:

  1. Client Requests Resource — sends a standard HTTP request
  2. Server Responds 402 — returns payment requirements via headers (amount, token, network, recipient, expiry)
  3. Client Signs and Submits Payment — constructs a blockchain transaction and resubmits the request with payment proof
  4. Server Verifies On-Chain — validates transaction settlement
  5. Server Delivers Resource — returns HTTP 200 with requested content

Response headers include:

  • X-Payment-Amount
  • X-Payment-Token
  • X-Payment-Network
  • X-Payment-Recipient
  • X-Payment-Expiry

x402 vs Traditional Payment APIs

Dimension Traditional APIs x402
Authentication API keys, OAuth, session cookies Payment proof in HTTP header
Payment Flow Multi-step with manual setup Two HTTP requests
Settlement Days to weeks Seconds via blockchain
Fees 2.9% + $0.30 per transaction Fraction of a cent in gas
Machine-Readable Partially, requires SDK Fully, standardized headers
Setup Complexity High, requires KYC, PCI compliance Low, wallet address plus headers
Micropayments Impractical, ~$0.50 minimum Native, viable at $0.001+

Code Examples

cURL Implementation

# Step 1: Initial request
curl -i https://api.example.com/v1/premium-data

# Response includes:
# X-Payment-Amount: 1000
# X-Payment-Token: 0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359
# X-Payment-Network: polygon
# X-Payment-Recipient: 0x8f2e...c9E2
# X-Payment-Expiry: 1713312000

# Step 2: Retry with proof after on-chain payment
curl -i https://api.example.com/v1/premium-data \
  -H "X-Payment-Proof: 0xabc123..."
Enter fullscreen mode Exit fullscreen mode

JavaScript/Node.js

async function x402Fetch(url, options = {}) {
  const initialResponse = await fetch(url, options);

  if (initialResponse.status !== 402) {
    return initialResponse;
  }

  const paymentAmount = initialResponse.headers.get("X-Payment-Amount");
  const paymentToken = initialResponse.headers.get("X-Payment-Token");
  const paymentNetwork = initialResponse.headers.get("X-Payment-Network");
  const paymentRecipient = initialResponse.headers.get("X-Payment-Recipient");
  const paymentExpiry = initialResponse.headers.get("X-Payment-Expiry");

  if (Date.now() / 1000 > parseInt(paymentExpiry)) {
    throw new Error("Payment window expired, retry to get new terms");
  }

  const txHash = await submitPayment({
    to: paymentRecipient,
    amount: paymentAmount,
    token: paymentToken,
    network: paymentNetwork,
  });

  const paidResponse = await fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      "X-Payment-Proof": txHash,
    },
  });

  return paidResponse;
}

const response = await x402Fetch("https://api.example.com/v1/premium-data");
const data = await response.json();
Enter fullscreen mode Exit fullscreen mode

Python

import time
import requests

def x402_request(url, method="GET", **kwargs):
    response = requests.request(method, url, **kwargs)

    if response.status_code != 402:
        return response

    payment_requirements = {
        "amount": response.headers.get("X-Payment-Amount"),
        "token": response.headers.get("X-Payment-Token"),
        "network": response.headers.get("X-Payment-Network"),
        "recipient": response.headers.get("X-Payment-Recipient"),
        "expiry": response.headers.get("X-Payment-Expiry"),
    }

    if time.time() > int(payment_requirements["expiry"]):
        raise ValueError("Payment window expired")

    tx_hash = submit_payment(
        to=payment_requirements["recipient"],
        amount=payment_requirements["amount"],
        token=payment_requirements["token"],
        network=payment_requirements["network"],
    )

    headers = kwargs.pop("headers", {})
    headers["X-Payment-Proof"] = tx_hash

    paid_response = requests.request(
        method, url, headers=headers, **kwargs
    )
    return paid_response

response = x402_request("https://api.example.com/v1/premium-data")
data = response.json()
Enter fullscreen mode Exit fullscreen mode

Integrating x402 with MoltPe

MoltPe supports x402 natively with automatic payment handling:

  1. Automatic 402 detection and header extraction
  2. Policy-checked signing before payment
  3. Gasless settlement (sponsored gas on Polygon PoS, Base, Tempo)
  4. Automatic retry with payment proof

MCP Tool Call

{"tool":"call_x402_endpoint","arguments":{"url":"https://api.example.com/v1/premium-data","method":"GET","max_payment":"0.01"}}
Enter fullscreen mode Exit fullscreen mode

REST API

POST https://api.moltpe.com/v1/x402/proxy
Authorization: Bearer YOUR_AGENT_TOKEN
Content-Type: application/json

{
  "target_url": "https://api.example.com/v1/premium-data",
  "method": "GET",
  "max_payment_usd": "0.01"
}
Enter fullscreen mode Exit fullscreen mode

MoltPe agents can also collect payments by configuring as sellers, with automatic 402 header generation and on-chain verification.

Use Cases

API Monetization

Servers can charge for access without managing API keys or billing infrastructure, using x402 as the sole access control mechanism.

Data Marketplace

Agents pay exactly for what they use, and providers earn exactly for what they serve — enabling economically viable niche data sales.

Agent-to-Agent Services

Specialized agents can charge other agents for services — translation, code review, market analysis — without invoicing overhead.

Content Paywalls

Publishers can charge per-article instead of requiring subscriptions, appealing to both humans and agents accessing content across multiple providers.

FAQ

What does x402 stand for?
The protocol references HTTP status code 402 (Payment Required), with "x" indicating experimental status.

Is x402 a blockchain protocol?
x402 is an HTTP-layer protocol that uses blockchain for payment settlement. It remains network-agnostic and compatible with EVM-compatible chains.

Who created x402?
Coinbase pioneered the specification and reference implementation, which has since gained adoption across multiple platforms.

Can x402 handle large payments?
Yes — there are no protocol-level limits. Payment amounts are server-specified via headers.

How does x402 compare to Lightning Network?
Lightning operates as a Layer 2 payment channel network on Bitcoin, while x402 operates at the HTTP layer on EVM chains using stablecoins like USDC.


Originally published at moltpe.com/blog/x402-protocol-complete-guide

Source: dev.to

arrow_back Back to News