X402

Automate and integrate X402 protocols and workflows efficiently

X402 is a community skill for implementing HTTP 402 payment-required flows in web services, covering payment negotiation headers, micropayment protocols, pay-per-request APIs, invoice generation, and automated payment verification patterns.

What Is This?

Overview

X402 provides patterns for building HTTP-native payment flows using the 402 Payment Required status code. It covers payment negotiation through HTTP headers that specify accepted payment methods and pricing, pay-per-request API endpoints that require payment before returning responses, invoice generation that creates machine-readable payment requests with amounts and destination addresses, automated payment verification that confirms on-chain or off-chain payments before granting access, and client-side payment handling that detects 402 responses and initiates payment flows. The skill enables developers to build APIs and web services that natively monetize access through HTTP payment protocols.

Who Should Use This

This skill serves API developers building pay-per-use services with machine-to-machine payments, teams implementing content paywalls with cryptocurrency micropayments, and engineers designing autonomous agent payment infrastructure.

Why Use It?

Problems It Solves

Traditional API monetization requires subscription management and key provisioning before access. Micropayments through payment processors are impractical due to high minimum transaction fees. Machine-to-machine payments need automated flows without human intervention at each transaction. Content monetization at the request level requires payment verification integrated into the HTTP request lifecycle.

Core Highlights

402 response handler returns payment requirements with accepted methods and pricing. Invoice generator creates payment requests with amount, recipient, and expiration. Payment verifier confirms transaction completion before serving the response. Client interceptor detects 402 responses and automates payment submission.

How to Use It?

Basic Usage

import express from 'express';

const app = express();

// Middleware: check payment
function requirePayment(
  priceUsd: number
) {
  return async (
    req: express.Request,
    res: express.Response,
    next: express.NextFunction
  ) => {
    const paymentProof =
      req.headers[
        'x-payment-proof'];

    if (!paymentProof) {
      return res.status(402)
        .json({
          type: 'payment_required',
          price: {
            amount: priceUsd,
            currency: 'USD' },
          methods: ['usdc',
            'lightning'],
          recipient:
            process.env.WALLET,
          expires: Date.now()
            + 300000,
        });
    }

    const valid =
      await verifyPayment(
        paymentProof as string,
        priceUsd);
    if (!valid) {
      return res.status(402)
        .json({
          error:
            'Invalid payment' });
    }
    next();
  };
}

app.get('/api/premium-data',
  requirePayment(0.01),
  (req, res) => {
    res.json({ data:
      'premium content' });
  });

Real-World Examples

// Client-side 402 handler
class PaymentClient {
  private wallet: {
    sendPayment: (
      to: string,
      amount: number
    ) => Promise<string>;
  };

  constructor(wallet: typeof
      this.wallet) {
    this.wallet = wallet;
  }

  async fetchWithPayment(
    url: string,
    options?: RequestInit
  ): Promise<Response> {
    const res = await fetch(
      url, options);

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

    const invoice =
      await res.json();
    const proof =
      await this.wallet
        .sendPayment(
          invoice.recipient,
          invoice.price.amount);

    return fetch(url, {
      ...options,
      headers: {
        ...options?.headers,
        'x-payment-proof': proof,
      },
    });
  }
}

// Usage
const client =
  new PaymentClient(myWallet);
const res = await client
  .fetchWithPayment(
    '/api/premium-data');
const data = await res.json();

Advanced Tips

Cache payment verifications with short TTLs so repeated requests within the payment window do not require re-verification. Batch small payments into periodic settlements to reduce on-chain transaction costs. Use Lightning Network invoices for instant settlement of small payments. Implement receipt tokens that grant access for a time window after a single payment.

When to Use It?

Use Cases

Build a pay-per-request AI inference API that charges per query using stablecoin payments. Create a content paywall that unlocks articles via micropayments. Implement machine-to-machine payment flows for autonomous agent service consumption.

Related Topics

HTTP 402, micropayments, payment protocols, Web3 commerce, and API monetization.

Important Notes

Requirements

A payment verification service for confirming on-chain or Lightning payments. HTTP server framework supporting custom middleware for payment checks. Wallet infrastructure for receiving and verifying payments. Client-side wallet library for constructing and submitting payment transactions.

Usage Recommendations

Do: include clear pricing and accepted payment methods in 402 responses. Set expiration times on invoices to prevent stale payment attempts. Verify payment amounts match the requested price before granting access.

Don't: accept unverified payment proofs without on-chain confirmation. Charge for failed or error responses that provide no value. Require payment for health check or documentation endpoints.

Limitations

HTTP 402 is not widely supported by standard clients or browsers. On-chain payment verification adds latency to request processing. Payment channel economics may not justify the complexity for low-volume endpoints. Micropayment economics depend on low transaction fees which vary by network.