x402 is an open payment protocol for HTTP services. A server returns 402 Payment Required with payment requirements. A compatible client submits a payment authorization. The server verifies and settles the payment through the configured flow before it delivers the protected response. This involves multiple requests, not one HTTP round trip.

The x402 introduction describes the protocol flow. Network, asset, payment scheme, SDK, and facilitator support must match. Do not assume that every listed network works with every facilitator.

When x402 fits an API

A per-request payment flow can suit a service that sells a defined result, such as a data response or a computation. A compatible agent can handle the payment exchange without a manual checkout for each request.

The buyer still needs a supported payment method, funds, and a spending policy. The seller still needs prices, error handling, records, and a customer support process. Middleware does not remove these requirements.

The protocol has no mandatory protocol fee. Network, facilitator, wallet, and service costs can still apply. Measure the complete cost of your chosen setup before setting a small per-request price. See the x402 project overview.

How the Payment Flow Works

The x402 payment flow uses three HTTP headers:

HeaderDirectionPurpose
PAYMENT-REQUIREDServer to ClientBase64 JSON containing price, network, wallet address
PAYMENT-SIGNATUREClient to ServerSigned payment payload proving authorization
PAYMENT-RESPONSEServer to ClientSettlement confirmation with transaction hash

Here is the sequence:

  1. Client sends GET /api/weather to the server
  2. Server returns 402 Payment Required with a PAYMENT-REQUIRED header specifying $0.001 on Base
  3. Client SDK automatically parses the requirement, signs a USDC transfer with the user's wallet
  4. Client retries the request with a PAYMENT-SIGNATURE header
  5. Server verifies the payment and completes settlement through the configured facilitator flow
  6. Server returns 200 OK with the weather data and a PAYMENT-RESPONSE header confirming settlement

Compatible SDKs can automate this exchange. The application still needs spending limits, error handling, and retry rules.


Example payment middleware configuration

This illustrative x402 V2 configuration protects an Express route. The network identifier eip155:84532 selects Base Sepolia. Replace the address placeholder. Add a route handler and startup code before running it:

TS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import express from "express";
import { paymentMiddleware } from "@x402/express";
import { x402ResourceServer, HTTPFacilitatorClient } from "@x402/core/server";
import { ExactEvmScheme } from "@x402/evm/exact/server";

const server = new x402ResourceServer(
    new HTTPFacilitatorClient({ url: "https://x402.org/facilitator" })
);
server.register("eip155:*", new ExactEvmScheme());

const app = express();
app.use(paymentMiddleware({
    "GET /weather": {
        accepts: [{
            scheme: "exact",
            price: "$0.001",
            network: "eip155:84532",
            payTo: "0xYourWallet",
        }],
    },
}, server));

This configures the payment middleware. It does not implement the weather response, start the server, or define all failure handling. The example uses a test facilitator; confirm current support before use.

FindUtils offers a free x402 Config Generator that generates this code for seven frameworks (Express, Hono, Next.js, Fastify, Gin, FastAPI, Flask) with visual route configuration. Review the generated template before use.


Match the generated code to your SDK

FindUtils offers templates for several server frameworks and client libraries. A generated file is a starting point. Check package versions, imports, facilitator support, and the current framework example before integration.

Integration itemCheck before use
Server frameworkMiddleware lifecycle and route matching
Client libraryPayment wrapper and retry behavior
NetworkMainnet or testnet identifier
Asset and schemeSupport at both client and facilitator
RecipientA valid address on the chosen network
PriceUnits, decimals, and the advertised payment requirement
CredentialsServer-side storage and least privilege

The official seller quickstart provides current framework examples. Do not assume that TypeScript, Go, and Python use identical configuration syntax.

AI agents, discovery, and payment policy

A payment client can sit behind an MCP tool or another agent integration. The agent must still receive an appropriate budget and permission to spend. MCP alone does not give a model a wallet or authorize a payment.

Bazaar is a discovery extension. A participating service can publish descriptions and schemas for compatible discovery clients. Configuration alone does not prove that a service appears in a catalog or that an agent will select it.

For a buyer, review the endpoint and schema before payment. For a seller, publish a clear result contract and failure policy. The related article on API marketplaces for AI agents separates discovery from payment execution.

Compare payment models by requirements

RequirementPer-request x402 integrationAccount or subscription integration
Access decisionUsually follows the configured payment flowUsually follows an account entitlement
Buyer setupSupported wallet or payment client and fundsAccount and supported billing method
Repeat usePayment, authorization, or extension-specific accessQuota, credits, or subscription rules
RecordsPayment result plus application recordsBilling records plus application records
Failure handlingPayment, settlement, and endpoint failure pathsBilling, entitlement, and endpoint failure paths
Refund policyImplement for the chosen payment systemImplement for the chosen provider and product

This compares design requirements, not current provider prices. Payment providers offer different products and machine-access options. Do not infer that a card-based service cannot serve an agent.

Choose the model that fits the customer and the result. Check tax, invoicing, refund, and other business requirements separately. A protocol does not determine those requirements for your service.

Extensions need separate review

The x402 extension system includes discovery, payment identifiers, wallet-based sign-in, signed offers and receipts, and gas-sponsoring options. Availability and behavior depend on the installed SDK and the selected network.

A payment identifier can support payment retry handling. It does not automatically make the endpoint's business action idempotent. For example, a paid export endpoint still needs a rule for duplicate export creation.

Sign-in support also needs an entitlement policy. A valid wallet signature does not establish permanent access to every resource. Define the resource, expiration, and prior-payment conditions.

Check the official extension overview before enabling an extension. Test each resulting failure and retry path.

Configure and test a paid endpoint

  1. Open the x402 Config Generator.
  2. Select a supported framework.
  3. Add the method, path, and price for one route.
  4. Choose a test network and a compatible facilitator.
  5. Replace the recipient placeholder with a test address.
  6. Review the generated code against the installed SDK version.
  7. Add the route handler and required server configuration.
  8. Test an unpaid request and a valid payment.
  9. Test an expired authorization, wrong network, and insufficient funds.
  10. Test duplicate requests, settlement failure, and a failed route handler.

For a buyer, set a maximum price and allowed recipients or services. Do not let an automatic payment wrapper accept every advertised payment requirement without a policy.

Keep testnet and mainnet configuration separate. Use a small, controlled integration test before you accept production payments.

Tools Used in This Article

  • x402 Config Generator — Prepare templates for the supported frameworks
  • API Docs Generator — Document your payment-protected endpoints
  • JWT Decoder — Inspect unrelated JWT authentication claims; x402 payment payloads are not necessarily JWTs
  • cURL to Code — Convert request syntax for supported programming languages

Frequently asked questions

Does x402 remove the need to understand wallets?

No. SDKs simplify request handling. You still need to manage funds, recipients, network selection, and signing credentials safely.

Are payments free and instant?

No universal claim applies. The protocol does not mandate a protocol fee, but network and provider costs can apply. Settlement time depends on the chosen system.

Is generated configuration production-ready?

It requires review and integration tests. Add real handlers, valid addresses, error handling, payment records, and the appropriate secret management.

Can I combine x402 with existing authentication?

Yes, if your application defines the access policy explicitly. Check the installed SDK's hooks and extension behavior. Authentication and payment establish different facts.

What should happen if settlement fails?

Do not treat signature verification as confirmed settlement. Follow the configured scheme and facilitator result. Keep a failure record and return the appropriate error without granting unpaid access.

How should I handle refunds?

Publish a refund policy for your service and selected payment system. Do not assume that a completed transfer has a built-in chargeback. Implement and test the required return-payment or credit process.

Keep the payment contract current

Review SDK release notes and facilitator support before an upgrade. Repeat the paid and unpaid request tests after changes. Preserve the advertised price, route, and network as an auditable contract.

The x402 Config Generator helps prepare configuration. The official buyer quickstart explains the corresponding client flow.