x402 Polygon Tutorial: Build a USDC-Paid API With HTTP 402
Learn how to build a USDC-paid Polygon API with x402, handle HTTP 402 payments, and understand when agent payment channels make sense.
On this page
Polygon published a new agent-payment architecture on September 24, 2026, after testing more than 11 million verified payment updates per second across 25 independently scaling hubs. The important detail for developers is not the headline number itself, but how the system separates frequent payment updates from slower onchain settlement. This x402 Polygon tutorial starts with the part you can build today: an API that returns HTTP 402, accepts USDC payments, verifies the payment through a facilitator, and then releases the requested resource. It also shows where the newer payment-channel architecture fits when one API call is no longer the right unit of settlement.
Why Polygon is separating payment speed from blockchain settlement
A normal blockchain payment puts every transfer on the chain's transaction path. That is reasonable when a person buys something occasionally, but it becomes awkward when software needs to pay for hundreds of API calls, data lookups, inference windows, or tool executions during one task. Polygon's new agent pay channels address that problem by allowing a payer to fund a reusable channel and then send signed payment updates through a hub while the accumulated value is settled onchain later. Polygon says its 25-hub test processed more than 11 million verified payment updates per second, while a full x402 path involving the agent, site, facilitator, and hub processed about 40,000 payments per second in its test.
Those numbers describe different layers, so they should not be read as an 11-million-transactions-per-second blockchain claim. The 11 million figure measures payment updates handled across the hub fleet, while the underlying funds remain secured by Polygon and are settled in batches. Polygon's test also used a live devnet payment path with an OpenRouter-style inference workload, with every 100-token window triggering a signed channel payment while the inference service itself was a stand-in.
Start with x402 before adding payment channels
x402 is the HTTP payment protocol underneath this design. It reuses the standard 402 Payment Required response so a server can tell a client that a resource requires payment, describe the accepted payment method, and then verify a signed payment before returning the resource. Polygon's current documentation supports x402 on both Polygon mainnet and Amoy testnet and describes it as a way to add pay-per-use API and agent payments without building a separate subscription system.
The distinction is useful when designing an application. x402 describes how a service asks for payment over HTTP, while a payment channel handles the high-frequency payment stream underneath it. You can therefore build and test a conventional x402 API first, then introduce channel-based settlement when repeated micropayments make individual onchain settlement impractical. Polygon's September architecture explicitly separates these two responsibilities.
Set up a Polygon x402 API on Amoy first
For a first implementation, use Polygon Amoy rather than putting a production private key and real USDC into an experimental payment flow. Polygon's seller quickstart requires a receiving wallet, Node.js 18 or newer, an existing server such as Express, Next.js, or Hono, and either Polygon Amoy or Polygon mainnet. The documentation provides separate middleware packages for those server frameworks, so the example below uses Express because its request flow is easy to see.
mkdir polygon-x402-api
cd polygon-x402-api
npm init -y
npm install express x402-express
Keep the receiving wallet and facilitator configuration outside the source code once you move beyond local testing. Polygon's documentation specifically warns that the examples are demonstrations and that private keys and facilitator URLs should be stored securely rather than hardcoded. The receiving address in the middleware is where the USDC payment is directed, while the facilitator handles the verification and settlement work required by the x402 flow.
Protect one API endpoint with an x402 payment requirement
The smallest useful seller application puts payment middleware in front of a normal API route. The server advertises the price and Polygon network, and an unpaid request receives a 402 response rather than the protected data. The buyer can then construct the required payment, sign it, and retry the same request with the payment payload. Polygon's documentation currently demonstrates this pattern with a weather endpoint priced at $0.001 USDC on Amoy.
import express from "express";
import { paymentMiddleware } from "x402-express";
const app = express();
app.use(
paymentMiddleware(
process.env.RECEIVER_WALLET,
{
"GET /weather": {
price: "$0.001",
network: "polygon-amoy",
config: {
description: "Get weather data"
}
}
},
{
url:
process.env.FACILITATOR_URL ||
"https://facilitator.x402.rs"
}
)
);
app.get("/weather", (req, res) => {
res.json({
report: {
weather: "sunny",
temperature: 70
}
});
});
app.listen(4021);
The exact middleware configuration can change as the x402 packages evolve, so treat the current Polygon documentation as the compatibility reference for package versions. Mechanically, however, the flow remains straightforward: the client requests the endpoint, the server responds with payment requirements, the client signs the required payment, and the server verifies it before returning the resource. The facilitator can perform the verification and settlement operations so your application does not have to implement the blockchain transaction path itself.
Understand what the 402 response is telling the buyer
A 402 response is not an error saying that the API is broken. It is a machine-readable challenge telling the client which payment requirement must be satisfied before the resource is released. The x402 documentation describes the response as containing payment requirements such as the accepted scheme, network, token, amount, and destination. Once the client selects a requirement, it creates a payment payload and sends the payment proof with the retry request.
{
"x402Version": 1,
"accepts": [
{
"scheme": "erc-3009",
"network": "polygon",
"token": "USDC_ADDRESS",
"maxAmountRequired": "1000000",
"description": "Access to premium API"
}
],
"error": null
}
The amount in this example is expressed in the token's smallest unit, so the application must understand the token's decimals rather than treating the value as a human-readable dollar amount. That distinction becomes especially important when you expose several endpoints with different prices. Your pricing layer should store and validate exact payment amounts, while the response should make the accepted network and asset unambiguous to the client.
Make the buyer retry the request after payment
The buyer side is where an ordinary HTTP client becomes a payment client. It first makes the normal request, receives the 402 response, chooses an accepted payment requirement, signs the required authorization, and retries the request with the payment payload. If verification succeeds, the resource server returns the requested data and can include a payment response containing settlement information. Polygon's x402 documentation describes this as the normal client flow and also supports the case where a client already knows the payment requirement and can skip the initial discovery step.
const firstResponse = await fetch(
"https://api.example.test/weather"
);
if (firstResponse.status === 402) {
const paymentRequirements =
await firstResponse.json();
// Select an accepted requirement.
// Sign the payment with the buyer wallet.
// Encode the resulting payment payload.
const paidResponse = await fetch(
"https://api.example.test/weather",
{
headers: {
"X-PAYMENT": encodedPaymentPayload
}
}
);
if (!paidResponse.ok) {
throw new Error("Payment or resource request failed");
}
const weather = await paidResponse.json();
}
The example deliberately leaves wallet signing as a separate operation because that part depends on the buyer's wallet and the selected payment scheme. Do not copy a private key into the application simply to make the example run. A production agent should have a constrained signing mechanism and explicit spending limits, especially when it can discover and pay for services without a person approving every individual request.
Know where the facilitator fits into the payment
The facilitator is the service that can verify a payment payload and settle it according to the selected x402 scheme. This keeps the resource server from having to implement all of the blockchain verification and transaction-submission logic itself. Polygon currently operates a facilitator endpoint and documents its use with the x402 middleware, while its wider documentation also lists third-party facilitators that can be used with Polygon.
This creates three distinct responsibilities. The resource server decides what the API costs and releases the data only after payment verification, the client controls the wallet and signs the payment, and the facilitator performs the verification and settlement operations required by the selected scheme. Keeping those responsibilities separate makes it easier to replace a facilitator or add another supported network without rewriting the API itself.
Move repeated micropayments into a payment channel
The standard x402 flow becomes less attractive when an agent makes an enormous number of tiny payments. Paying each unit independently adds settlement work that has little to do with the service itself. Polygon's new architecture instead has the payer deposit funds into a vendor-agnostic channel contract and bind a session key, giving the agent a bounded pool from which it can make repeated payments.
After the channel is funded, the agent does not need a new onchain transfer for every service unit. The service uses x402 to state what it wants to charge, while the agent sends signed cumulative vouchers through a hub. The hub checks the signature, price, replay identifier, authorization ceiling, and remaining escrow before returning a receipt. This lets the service confirm payment before releasing the next unit of work while the actual blockchain settlement can happen later.
The key architectural split: x402 remains the HTTP payment negotiation layer; the payment channel is the high-frequency accounting and settlement mechanism underneath it. You do not need to replace x402 to use this model.
Set settlement frequency independently from API frequency
One of the useful consequences of a reusable channel is that the application can separate how often it records usage from how often it settles onchain. Polygon describes settlement examples ranging from a single payment to 50,000 updates or even 100 million updates, depending on the service's requirements. The provider can therefore receive a payment confirmation for each unit of work without requiring the blockchain to process one transaction for every unit.
This is particularly relevant to machine-to-machine services. An AI agent might consume inference from one provider, retrieve information from another, and call a specialist tool several times before completing one task. Charging each operation through a conventional checkout or separate prepaid account would add friction at exactly the point where software needs the least human intervention. Channel-based payments instead keep a bounded balance available and let the service meter consumption against it.
Test the API before testing autonomous spending
Start with a fixed-price endpoint and a tiny test amount. Confirm that an unpaid request returns 402, that the payment requirement contains the expected network and asset, that the signed payment is rejected when it is invalid, and that a valid payment releases exactly the resource you intended to protect. Only after those checks work should you introduce automatic agent spending or repeated payment loops.
Then test the failure cases deliberately. Try an expired payment, a mismatched resource, an amount above the endpoint's limit, an unsupported network, and a reused payment authorization. The x402 flow depends on the server verifying the payment before returning the resource, so a test that only proves successful payments work is incomplete. Your logs should also distinguish a normal HTTP failure from a payment verification failure and from an onchain settlement failure.
Know what the 11 million figure does and does not prove
Polygon's 11-million figure came from a 25-hub benchmark, with each hub independently scaling and the payment updates moving offchain through the channels. Polygon reported 533,000 to 536,000 verified payments per second for a single hub in an engine-direct test on one 24-core server, while the full x402 path reached about 40,000 payments per second and processed 2.4 million payments with 100% success in that test. The company also reported approximately $0.15 of processing cost for one billion payment updates under the benchmark configuration.
Those are useful engineering measurements, but they are not a universal throughput guarantee for every deployment. The benchmark depends on the hub hardware, architecture, workload, network conditions, and the distinction between offchain payment updates and onchain settlement. Polygon's own description says the 11-million result came from its test architecture, so a production system should measure its complete path rather than substituting the headline benchmark for its own load testing.
For developers, the practical starting point is therefore smaller than the headline suggests: make one API payable through x402, test it on Polygon Amoy, and verify the complete 402-to-payment-to-response cycle. Once an application has a real workload involving repeated micropayments, the payment-channel model provides a way to keep those updates off the chain's per-transaction path while retaining onchain settlement. That is the part of Polygon's September 2026 announcement worth carrying into application architecture, because it changes how a paid API can meter work rather than simply making an existing transfer faster.
Written by


