What Is the x402 Protocol?

The x402 protocol is an open standard for embedding payments directly into HTTP. It transforms the long-dormant HTTP 402 Payment Required status code into a functional payment negotiation mechanism, allowing any server to charge for access and any client to pay, all within standard HTTP request-response cycles.

HTTP 402 was defined in the original HTTP/1.1 specification in 1999. The spec authors anticipated that the web would eventually need a native payment layer, so they reserved status code 402 for future use. For over two decades, that future never arrived. Payment on the web was handled by external systems: credit card forms, subscription platforms, OAuth-gated API keys. None of these were machine-readable by default, and none supported the kind of frictionless, per-request micropayments that autonomous software agents need.

The x402 protocol, pioneered by Coinbase, finally gives HTTP 402 a concrete implementation. Rather than inventing an entirely new transport layer, x402 works within the HTTP protocol that every web client and server already speaks. A server that wants to charge for a resource simply returns a 402 response with structured headers describing the payment terms. A client that can pay reads those headers, submits payment on a blockchain network, and retries the request with proof of payment attached.

This design has three properties that make it transformative for AI agent payments:

Since its introduction, x402 has processed over 50 million transactions across various implementations. It is rapidly becoming the default payment protocol for the agentic web, where autonomous software agents need to buy and sell services without waiting for human approval.

How x402 Works

An x402 payment follows a five-step flow that mirrors standard HTTP semantics. No new transport protocol is needed. The entire negotiation happens over the same HTTP connection your application already uses.

Step 1: Client Requests Resource

The client sends a standard HTTP request to any endpoint. This could be a GET request for data, a POST request for computation, or any other HTTP method. The client does not need to know in advance that payment is required.

Step 2: Server Responds 402 with Payment Requirements

Instead of returning the resource, the server returns HTTP 402 Payment Required. The response includes structured headers that describe exactly what payment the server expects:

Step 3: Client Signs and Submits Payment

The client reads the 402 headers, constructs a blockchain transaction matching the requirements, and signs it with the agent's private key. The client then submits the original HTTP request again, this time including an X-Payment-Proof header containing the signed transaction hash or payment attestation.

Step 4: Server Verifies Payment On-Chain

The server receives the retry request, reads the payment proof header, and verifies the transaction on-chain. It confirms that the correct amount was sent, in the correct token, to the correct recipient, on the specified network. This verification can happen synchronously (waiting for block confirmation) or asynchronously (accepting the transaction hash and confirming later).

Step 5: Server Delivers Resource

Once payment is confirmed, the server returns HTTP 200 OK with the requested resource. The transaction is complete. There is no session, no cookie, no token to manage. The next request starts the cycle fresh.

HTTP Flow Diagram

CLIENT                                           SERVER
  |                                                |
  |  1. GET /api/premium-data                      |
  |  -------------------------------------->       |
  |                                                |
  |  2. 402 Payment Required                       |
  |     X-Payment-Amount: 1000                     |
  |     X-Payment-Token: 0x3c499...USDC            |
  |     X-Payment-Network: polygon                 |
  |     X-Payment-Recipient: 0x8f2e...             |
  |     X-Payment-Expiry: 1713312000               |
  |  <--------------------------------------       |
  |                                                |
  |  3. [Client signs USDC transfer on Polygon]    |
  |                                                |
  |  4. GET /api/premium-data                      |
  |     X-Payment-Proof: 0xabc123...txhash         |
  |  -------------------------------------->       |
  |                                                |
  |  5. [Server verifies tx on-chain]              |
  |                                                |
  |  6. 200 OK                                     |
  |     { "data": "premium content here" }         |
  |  <--------------------------------------       |
  |                                                |

The entire exchange uses standard HTTP. No WebSocket upgrades, no custom binary protocols, no payment-specific middleware in the network path. Any HTTP client library can be extended to handle x402 with minimal code. See the glossary for definitions of terms used in this guide.

x402 vs Traditional Payment APIs

To understand what x402 changes, it helps to compare it directly with the traditional payment API approach that dominates the web today. Here is a side-by-side comparison across the dimensions that matter most for agent-driven and machine-to-machine scenarios.

Dimension Traditional Payment APIs x402 Protocol
Authentication API keys, OAuth tokens, or session cookies issued after manual signup None required. Payment proof in HTTP header serves as both authentication and authorization
Payment Flow Multi-step: create customer, add payment method, create charge, handle webhooks Two HTTP requests: one 402 response, one paid retry
Settlement Days to weeks (credit card clearing, bank transfers) Seconds (on-chain confirmation on Polygon PoS or Base)
Fee Structure 2.9% + $0.30 per transaction (typical card processing) Fraction of a cent in network gas fees (gasless with MoltPe)
Machine-Readable Partially. Requires SDK integration, API documentation, error handling for each provider Fully. Standardized HTTP headers. Any x402-aware client works with any x402 server
Setup Complexity High. Merchant accounts, KYC, PCI compliance, webhook infrastructure Low. A wallet address and a few HTTP headers on the server side
Micropayment Support Impractical. Minimum viable transaction is ~$0.50 due to fixed fees Native. Payments of $0.001 or less are economically viable
Protocol Layer Application layer (proprietary APIs on top of HTTP) HTTP layer (uses the 402 status code defined in the HTTP specification)

The key takeaway: traditional payment APIs were designed for humans buying things from websites. x402 was designed for software agents buying things from other software agents. The protocol eliminates every step that assumes a human is present: account creation, payment method entry, redirect flows, and manual reconciliation.

Code Examples

Below are three practical examples showing how to interact with x402 endpoints. These examples use standard HTTP libraries and demonstrate the core pattern: make a request, handle the 402 response, pay, and retry.

cURL: Making an x402 Payment Request

This two-step example shows the raw HTTP flow. First, discover the payment requirements. Then, after paying on-chain separately, retry with proof.

# Step 1: Request the resource (will get 402 back)
curl -i https://api.example.com/v1/premium-data

# Response:
# HTTP/2 402 Payment Required
# X-Payment-Amount: 1000
# X-Payment-Token: 0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359
# X-Payment-Network: polygon
# X-Payment-Recipient: 0x8f2e4bD7B0A1E8c5F6d9A3b2C7e0D4f8A1B5c9E2
# X-Payment-Expiry: 1713312000

# Step 2: After signing and submitting tx on-chain, retry with proof
curl -i https://api.example.com/v1/premium-data \
  -H "X-Payment-Proof: 0xabc123def456789abcdef0123456789abcdef0123456789abcdef0123456789a"

# Response:
# HTTP/2 200 OK
# Content-Type: application/json
# { "data": "premium content here" }

JavaScript / Node.js: Handling 402 and Paying

This example shows a reusable function that detects 402 responses, constructs a payment, and retries automatically.

async function x402Fetch(url, options = {}) {
  // Step 1: Make the initial request
  const initialResponse = await fetch(url, options);

  // If not a 402, return the response as-is
  if (initialResponse.status !== 402) {
    return initialResponse;
  }

  // Step 2: Extract payment requirements from headers
  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");

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

  // Step 3: Sign and submit the payment on-chain
  // This uses your agent wallet to send the required token amount
  const txHash = await submitPayment({
    to: paymentRecipient,
    amount: paymentAmount,
    token: paymentToken,
    network: paymentNetwork,
  });

  // Step 4: Retry the original request with payment proof
  const paidResponse = await fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      "X-Payment-Proof": txHash,
    },
  });

  return paidResponse;
}

// Usage
const response = await x402Fetch("https://api.example.com/v1/premium-data");
const data = await response.json();
console.log(data);

Python: Basic x402 Client

A Python implementation using the requests library, following the same detect-pay-retry pattern.

import time
import requests

def x402_request(url, method="GET", **kwargs):
    """Make an HTTP request with automatic x402 payment handling."""

    # Step 1: Make the initial request
    response = requests.request(method, url, **kwargs)

    # If not a 402, return as-is
    if response.status_code != 402:
        return response

    # Step 2: Extract payment requirements
    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"),
    }

    # Verify the payment window is still open
    if time.time() > int(payment_requirements["expiry"]):
        raise ValueError("Payment window expired, retry to get new terms")

    # Step 3: Submit payment on-chain using agent wallet
    tx_hash = submit_payment(
        to=payment_requirements["recipient"],
        amount=payment_requirements["amount"],
        token=payment_requirements["token"],
        network=payment_requirements["network"],
    )

    # Step 4: Retry with payment proof
    headers = kwargs.pop("headers", {})
    headers["X-Payment-Proof"] = tx_hash

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


# Usage
response = x402_request("https://api.example.com/v1/premium-data")
data = response.json()
print(data)

In all three examples, the core pattern is identical: request, read 402 headers, pay, retry with proof. The protocol's simplicity means any HTTP client in any language can support x402 with minimal wrapper code.

Integrating x402 with MoltPe

MoltPe supports the x402 protocol natively, meaning your AI agents can both pay and collect x402 payments without writing the low-level blockchain code shown in the examples above. MoltPe handles wallet management, transaction signing, gas fees, and on-chain verification behind a clean interface.

How MoltPe Agents Use x402

When a MoltPe agent encounters an x402-enabled endpoint, the payment flow is handled automatically:

  1. Automatic 402 detection. The MoltPe agent runtime recognizes 402 responses and extracts payment requirements without developer intervention.
  2. Policy-checked signing. Before paying, the agent checks the request against its configured spending policies (per-transaction limits, daily caps, approved recipients). If the payment fits within policy, the agent signs it. If not, the request is rejected with a clear policy violation message.
  3. Gasless settlement. MoltPe sponsors gas fees on supported networks (Polygon PoS, Base, Tempo), so agents pay only the resource price, not network fees.
  4. Automatic retry. After payment settles, MoltPe retries the original request with the payment proof header attached and returns the resource to the calling code.

MCP Tool Calls

If your agent framework supports the Model Context Protocol (MCP), MoltPe exposes x402 as a tool call. The agent can call the call_x402_endpoint tool, and MoltPe handles the entire 402 negotiation cycle:

// MCP tool call within an agent framework
{
  "tool": "call_x402_endpoint",
  "arguments": {
    "url": "https://api.example.com/v1/premium-data",
    "method": "GET",
    "max_payment": "0.01"
  }
}

The max_payment field acts as a safety cap. If the server demands more than this amount in USD, the call is rejected before any payment is made.

REST API

For direct integration without MCP, MoltPe's REST API provides an x402 proxy endpoint. Send your request to MoltPe, and it forwards it to the target, handles any 402 negotiation, and returns the final response:

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"
}

This approach works with any language or framework. Your code makes one HTTP call to MoltPe and receives the final resource, with payment handled transparently.

Collecting x402 Payments

MoltPe agents are not limited to paying. They can also collect. When you configure an agent as a seller, MoltPe generates the 402 response headers automatically for incoming requests, verifies payments on-chain, and credits the agent's isolated wallet. This means you can monetize any API endpoint with x402 by pointing it through MoltPe, no smart contract deployment needed.

Use Cases

The x402 protocol unlocks economic models that were previously impractical due to payment friction and minimum transaction sizes. Here are the four most impactful categories.

API Monetization

Any API can become a paid API by adding x402 support. Instead of managing API keys, rate limits, and billing dashboards, the server simply returns 402 with a price. Clients that can pay, pay. Clients that cannot, get a clear signal of what is required. This is especially powerful for independent developers and small teams who want to monetize data or computation without building billing infrastructure.

Data Marketplace

x402 enables per-query pricing for data. An AI agent researching a topic can query multiple data providers, paying a fraction of a cent per data point retrieved. No subscriptions, no bulk data purchases, no data licensing negotiations. The agent pays exactly for what it uses, and providers earn exactly for what they serve. This granularity makes it economically viable to sell even small datasets or niche data points.

Agent-to-Agent Services

In a multi-agent system, specialized agents can sell services to other agents. A translation agent charges $0.002 per paragraph translated. A code review agent charges $0.05 per file reviewed. A market analysis agent charges $0.10 per report generated. x402 makes these micro-transactions seamless because each service call is a standard HTTP request that carries its own payment. No invoicing, no accounts receivable, no settlement delays. The rise of AI agent payments is driving demand for exactly this type of infrastructure.

Content Paywalls

x402 offers an alternative to subscription-based content access. Instead of requiring a $20/month subscription to read articles, a publisher can charge $0.05 per article via x402. Readers (human or agent) pay only for what they actually read. This model is particularly attractive for AI agents that need to access content across hundreds of different publishers without maintaining subscriptions to each one.