Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.swiftpay.finance/llms.txt

Use this file to discover all available pages before exploring further.

What is x402?

x402 is an open protocol that brings native payment to the HTTP layer. Instead of a checkout flow, your server returns an HTTP 402 Payment Required response when a caller has not yet paid. The caller signs a USDC transfer authorisation and retries — your server verifies and settles through SwiftPay, then serves the resource. This is the right choice when you are charging per request rather than per invoice:
  • API monetisation — charge per call without subscription management
  • Metered access — pay-as-you-go data, AI, or compute endpoints
  • Machine-to-machine payments — autonomous agents paying for on-chain services in real time
SwiftPay acts as the facilitator: it verifies the EIP-712 signature and executes the on-chain USDC settlement so your server never touches private keys.
x402 is currently supported on EVM chains only (Base, Ethereum, Polygon). USDC is the accepted token.

How it works

x402 uses a two-round HTTP flow between the caller, your server, and SwiftPay:
1

Round 1 — No payment header

The client makes a normal HTTP request. Your middleware detects the missing X-PAYMENT header, calls SwiftPay to fetch PaymentRequirements for that route, and returns HTTP 402 with the requirements JSON body.
2

Client signs the payment

The client wallet signs an EIP-3009 TransferWithAuthorization — a pre-authorised USDC transfer valid for 5 minutes. No transaction is broadcast at this point. The signed payload is base64-encoded and placed in the X-PAYMENT request header.
3

Round 2 — Retry with X-PAYMENT header

The client re-sends the same request with the X-PAYMENT header attached.
4

Middleware settles, then serves

Your middleware extracts the X-PAYMENT header and calls POST /v1/x402/settle. SwiftPay verifies the EIP-712 signature, atomically claims the nonce (replay protection), and executes the on-chain USDC transfer. On success, your server sets the X-PAYMENT-RESPONSE header and serves the resource.
x402 two-round payment flow

Setup

1. Register a forwarder

Go to Dashboard → x402 → Forwarders and click New Forwarder. SwiftPay derives a CREATE2 address — no on-chain transaction yet. The forwarder is deployed automatically the first time you register an endpoint. The forwarder is the per-merchant smart contract that receives incoming USDC and splits it between your treasury wallet and the SwiftPay protocol fee.

2. Register an endpoint

For each route you want to protect, register an endpoint via the API:
curl -X POST https://api.swiftpay.finance/v1/x402/endpoints \
  -H "X-Swift-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "endpointUrl": "https://api.example.com/v1/analyze",
    "description": "Sentiment analysis — $0.10 per call",
    "asset": "USDC",
    "network": "eip155:8453",
    "amountUsd": 0.10
  }'
The response includes a payment_requirements object — the exact payload your middleware returns inside the 402 body for this route.
Register one endpoint per distinct route + price combination. The same endpoint can be fetched by URL later, so your middleware only needs to know the protected URL, not the endpoint UUID.

Business server integration

Your server needs a middleware that implements the two-round gate. The middleware calls SwiftPay on every request — either to get requirements (round 1) or to settle (round 2).
import { Request, Response, NextFunction } from "express";

const SWIFTPAY_API = "https://api.swiftpay.finance";
const SECRET_KEY = process.env.SWIFTPAY_SECRET_KEY!;

export function x402Guard(endpointUrl: string) {
  return async (req: Request, res: Response, next: NextFunction) => {
    // Fetch requirements for this route (needed in both rounds)
    const reqsRes = await fetch(
      `${SWIFTPAY_API}/v1/x402/endpoints/requirements?url=${encodeURIComponent(endpointUrl)}`,
      { headers: { "X-Swift-Key": SECRET_KEY } }
    );
    const { data } = await reqsRes.json();
    const { x402Version, requirements } = data;

    const paymentHeader = req.headers["x-payment"] as string | undefined;

    // Round 1 — no payment header: return 402
    if (!paymentHeader) {
      return res.status(402).json({
        x402Version,
        accepts: [requirements],
      });
    }

    // Round 2 — settle the payment
    const settleRes = await fetch(`${SWIFTPAY_API}/v1/x402/settle`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        x402Version,
        paymentPayload: paymentHeader,
        paymentRequirements: requirements,
      }),
    });

    const result = await settleRes.json();

    if (!result.success) {
      return res.status(402).json({
        x402Version: 1,
        accepts: [requirements],
        error: result.error,
      });
    }

    res.setHeader("X-PAYMENT-RESPONSE", JSON.stringify(result));
    next();
  };
}
Always call SwiftPay from your server — never from the browser. Your sk_live_* key must stay server-side only.

Idempotent payment check

If a client retries a request after a network timeout it may send the same X-PAYMENT header again. Before calling settle, check whether that nonce was already processed:
GET https://api.swiftpay.finance/v1/x402/payments/status?nonce=0x1234…
{
  "nonce": "0x1234…",
  "status": "settled",
  "paymentId": "uuid",
  "transaction": "0xabc…",
  "network": "eip155:8453",
  "payer": "0xpayer…",
  "amount": "0.10",
  "settledAt": "2026-04-27T12:00:00Z"
}
Possible status values: not_found | pending | settled | failed. If settled, serve the resource immediately without calling settle again. If pending, the settlement is in progress — wait and retry. If failed, treat it as an unpaid request.

Webhook events

SwiftPay fires the following events after each x402 settlement attempt:
EventTrigger
x402.payment.settledOn-chain USDC transfer confirmed
x402.payment.failedOn-chain transaction reverted or timed out
See the Webhooks guide for signature verification, retry behaviour, and delivery logs.

API reference

Facilitator endpoints

supported, verify, settle, payment status

Endpoint management

register, list, deactivate, get requirements