Skip to main content
Logo
Back to Protocols
X402
payments
stable

HTTP-Native Payments

Instant digital payments via HTTP 402. Zero fees, ~2 second settlement, blockchain-agnostic. Pay-per-API-call, pay-per-GB, micropayments as low as $0.001.

Organization: Coinbase
Integration:
advanced

Overview

X402 is a web protocol that uses HTTP 402 Payment Required to enable instant micropayments for API calls, data transfers, and usage-based billing. It’s built on blockchain technology for instant settlement and zero platform fees.

The protocol is named after HTTP status code 402 (Payment Required), which was defined in RFC 7231 but rarely used until X402 revived it for practical payments.

Key Characteristics

Instant Settlement

  • Transactions settle in ~2 seconds on blockchain
  • No intermediaries or payment processors
  • Direct peer-to-peer payments
  • Cryptocurrency (stablecoins) for global access

Zero Fees

  • Payment goes directly to recipient
  • No platform fees or middlemen
  • Minimal blockchain gas costs
  • Suitable for even tiny payments ($0.001)

Micropayment-Friendly

  • Enable new business models
  • Pay-per-API-call
  • Pay-per-byte or per-request
  • Fine-grained usage metering

Blockchain-Agnostic

  • Works on Ethereum, Polygon, Base, Solana, etc
  • Support for stablecoins (USDC, USDT)
  • Cross-chain capable
  • L2 networks for speed and cost

HTTP 402 Flow

Client                                    Server
  │                                         │
  ├─ GET /api/data ──────────────────────→ │
  │                                         │
  │ ← 402 Payment Required ─────────────── │
  │   (price: $0.001, paymentAddress: ...) │
  │                                         │
  ├─ Send payment to blockchain ──────────→ ⟳
  │                                         │
  ├─ GET /api/data ──────────────────────→ │
  │   (X-Payment-Hash: 0x123...) ────────→ │
  │                                         │
  │ ← 200 OK ──────────────────────────── │
  │   (data content) ←────────────────────┤

Ontology Integration

X402 integrates with the 6-dimension ontology for payment tracking:

Things

  • payment_ledger: Records of X402 payments
  • usage_meter: Tracks billable usage
  • All scoped to group for accounting

Connections

  • transacted: Between user and service provider
  • Payment metadata (amount, asset, txHash)

Events

  • payment_verified: Payment confirmed on blockchain
  • usage_metered: Usage recorded and charged
  • Complete audit trail with txHash

Knowledge

  • Payment history: All past transactions
  • Usage patterns: Learn normal vs unusual
  • Cost analytics: Understand billing patterns

Use Cases

Pay-Per-API-Call

API Provider: $0.0001 per API call
User makes 10,000 calls = $1.00
Instant payment via X402

Pay-Per-Gigabyte

Download Provider: $0.001 per GB
User downloads 5 GB = $0.005
Streaming payments as data transfers

Usage-Based SaaS

AI Service: $0.001 per 1,000 tokens
User uses 2M tokens = $2.00
Fine-grained metering and billing

Cycle Payments

Model API: $0.0001 per cycle
User runs 100 cycles = $0.01
Real-time payment per request

Blockchain Selection

Choose blockchain based on needs:

BlockchainSettlementCostBest For
Base2-5 seconds$0.0001-0.001Small micropayments
Polygon2-5 seconds$0.0001-0.001Higher volume
Ethereum12 seconds$0.10-1.00Large payments
Solana400ms$0.00025Ultra-fast

Stablecoins

X402 typically uses stablecoins for stability:

  • USDC: Circle’s stablecoin (broadest support)
  • USDT: Tether stablecoin (highest liquidity)
  • DAI: Decentralized stablecoin
  • EURS: Euro stablecoin

Security Considerations

  • Payment Verification: Verify blockchain transaction
  • Double Spending: Blockchain prevents double-spend
  • Wallet Security: User responsible for wallet safety
  • Rate Limiting: Prevent abuse even with X402
  • Timeout: Request expires if payment not received

Pricing Strategy

X402 enables new pricing models:

Fixed-Price

  • $0.001 per API call
  • Same price regardless of compute cost
  • Simplest for users

Usage-Based

  • $0.00001 per millisecond of compute
  • $0.000001 per byte of storage
  • Fine-grained cost allocation

Tiered

  • First 1,000 calls free
  • Next 10,000 calls: $0.0001 each
  • Above 10,000: $0.00005 each

Comparison with Other Protocols

AspectX402AP2ACP
Primary UseMicropaymentsAgent paymentsMessaging
SettlementSecondsMinutes/hoursN/A
FeesZeroVariableN/A
BlockchainRequiredOptionalN/A

Business Models Enabled by X402

Before X402

  • APIs charge flat monthly fee (min $20/month)
  • Users must commit to usage
  • Unused capacity = wasted cost

With X402

  • APIs charge per request (even $0.0001)
  • Users pay only for what they use
  • New market for specialized services
  • Service providers can compete on efficiency

Getting Started

  1. Choose blockchain and stablecoin
  2. Get smart contract for payments (or use existing)
  3. Implement X402 handler in API
  4. Price your service in X402 terms
  5. Guide users to set up wallet
  6. Monitor payments and ledger
  7. Settle payments regularly

Ledger Management

X402 supports accounting via things:

// Payment ledger entry
{
  type: "payment_ledger",
  properties: {
    protocols: {
      x402: {
        from: "user_wallet",
        to: "service_wallet",
        amount: "0.001",
        asset: "USDC",
        network: "base",
        txHash: "0x123...",
        timestamp: 1698765432,
        description: "API call"
      }
    }
  }
}

Ontology Mapping

How this protocol maps to the 6-dimension ontology

groups

X402 payments scoped to groups for payment isolation

people

Payment permission determined by agent role

things

Payment ledger entries stored as things

connections

Payment flows between agents and services tracked

events

Every payment creates a payment_verified event with blockchain proof

knowledge

Payment history and ledger state stored for accounting

Features

Zero Fees

No platform fees - payment goes directly to recipient

~2 Second Settlement

Transactions settle in seconds, not days

Blockchain-Agnostic

Works on any blockchain or payment rail

Micropayments

Enable payments as small as $0.001

Use Cases

Pay-Per-API-Call

Users only pay for API calls they make, per millisecond of compute

X402
Pay-Per-Gigabyte Downloads

Bandwidth metering with instant micro-payments

X402
Usage-Based SaaS

Platform A bills user for exact usage (tokens, requests, storage)

X402
AI Model Cycle Payments

Pay for every cycle call to AI models in real-time

X402
AP2

Code Examples

Set Up X402 Payment Endpoint
typescript
                      // HTTP 402 endpoint that requires payment
import { HttpPaymentRequired } from "@x402/sdk";

export const protectedEndpoint = mutation({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    // Check for X402 payment header
    const paymentHeader = ctx.headers?.get("x-payment-required");

    if (!paymentHeader) {
      // Return 402 Payment Required
      throw new HttpPaymentRequired({
        amount: "0.001", // $0.001 = 1 cent
        currency: "USD",
        asset: "USDC",
        paymentAddress: "0x1234...5678",
        timeout: 30 // seconds
      });
    }

    // Payment received, process request
    const result = await processRequest(args);

    // Log payment event
    await ctx.db.insert("events", {
      type: "payment_verified",
      groupId: ctx.auth?.getOrganizationId?.(),
      metadata: {
        protocol: "x402",
        network: paymentHeader.network,
        txHash: paymentHeader.txHash,
        amount: "0.001"
      },
      timestamp: Date.now()
    });

    return result;
  }
});

                    
Client Pays for API Call
typescript
                      // Client making X402 payment for API call
import { X402Client } from "@x402/sdk";

const x402 = new X402Client({
  wallet: "user_wallet_address",
  network: "base", // Optimized for speed
  asset: "USDC"
});

// Make API call with payment
const response = await x402.fetch("https://api.example.com/search", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ query: "find documents" })
});

// X402 automatically:
// 1. Gets payment quote from server
// 2. Sends payment on blockchain
// 3. Resends request with payment proof
// 4. Gets response

const results = await response.json();
console.log(`Paid $0.001, got ${results.length} results`);

                    
Meter and Bill Usage with X402
typescript
                      // Track usage and bill via X402
const startTime = Date.now();
const startStorage = await getStorageUsage();

// User makes requests
for await (const request of requestStream) {
  const result = await processRequest(request);

  // Calculate usage
  const elapsedMs = Date.now() - startTime;
  const bytesUsed = getStorageUsage() - startStorage;
  const computeCost = (elapsedMs / 1000) * 0.0001; // $0.0001 per second
  const storageCost = (bytesUsed / 1024 / 1024 / 1024) * 0.00001; // $0.00001 per GB
  const totalCost = computeCost + storageCost;

  // Send X402 payment for usage
  const paymentResult = await x402.pay({
    amount: totalCost.toString(),
    recipient: "service_wallet",
    metadata: {
      computeMs: elapsedMs,
      storageBytes: bytesUsed,
      requestId: request.id
    }
  });

  // Log to ledger thing
  await ctx.db.insert("things", {
    type: "payment_ledger",
    name: `Usage charge for ${request.id}`,
    groupId: ctx.auth?.getOrganizationId?.(),
    properties: {
      protocols: {
        x402: {
          computeCost,
          storageCost,
          totalCost,
          txHash: paymentResult.txHash,
          network: "base",
          asset: "USDC"
        }
      }
    },
    status: "active",
    createdAt: Date.now(),
    updatedAt: Date.now()
  });
}

                    
Standards
HTTP 402 Payment Required
Coinbase Commerce
Multi-blockchain support
Prerequisites
  • Cryptocurrency wallet or payment processor
  • Blockchain network access (Base, Ethereum, Polygon, etc)
  • X402-compatible SDK
  • User wallets or payment methods