Skip to content

How to x402: The Complete Guide to the AI Agent Payment Protocol

x402 cover

When a browser or app calls a website, the server returns an HTTP status code describing what happened. The most common are 200 "Success" (if you're reading this, it's what Simplescraper's server returned) and 404 "Not Found".

HTTP status code 402 "Payment Required" is less common - it was assigned in the early 1990s, with the expectation that future technology would one day make micropayments a core part of the web.

Three decades on, the rise of autonomous AI agents combined with near-zero-cost blockchain settlements means that day may have finally arrived.

x402, a protocol built on top of HTTP 402, makes per-request payments work via US dollar pegged stablecoins. Agents request resources, the resource requests payment, the agent pays, and the resource is unlocked - all done automatically via standard HTTP headers.

In this guide we'll show how x402 works, walk you through a live payment to Simplescraper's API, and show how to implement it in any endpoint.


Table of contents

Key terms

TermDefinition
x402Crypto-native protocol standard for paying for API/server resources using the HTTP 402 status code with stablecoin payments
HTTP HeaderMetadata attached to an HTTP request or response. x402 uses three custom headers to carry payment data alongside normal web traffic
StablecoinA cryptocurrency pegged to the US dollar whose price doesn't fluctuate. USDC (a stablecoin issued by Circle) is the default payment currency in x402
Layer 2 (L2)A blockchain built on top of Ethereum that processes transactions faster and cheaper. Base, Polygon, and Arbitrum are examples
BaseCoinbase's Layer 2 blockchain. Where most x402 payments settle, with gas costs under $0.001
GasThe transaction fee paid to process an operation on a blockchain. On Base, gas costs under $0.001. In x402, the facilitator pays gas on behalf of users
FacilitatorA server that verifies payment signatures and pays gas fees on behalf of the user, so your API never touches the blockchain directly

Part 1: How x402 Works

The History

The 402 status code was reserved as a means to charge for access to resources in the original HTTP specification, but credit card minimums made sub-dollar payments unworkable. Advertisement filled the gap, becoming the default monetization model for the web over the next three decades.

In the 2020s, Layer 2 blockchains like Base brought settlement costs below a tenth of a cent, making micropayments economically viable for the first time. Around the same time, Artificial Intelligence labs began releasing AI agents that acted autonomously and thus required a frictionless way to consume APIs and data feeds.

Coinbase launched the x402 protocol standard in May 2025 to connect these two developments - cheap settlement and agent demand. A V2 release followed within six months, and the x402 Foundation (co-founded with Cloudflare) now governs the open spec. Current work is focused on multi-chain support, framework integrations, and purpose-built SDKs for agent developers.

1990s
HTTP 402 Reserved

Tim Berners-Lee and the architects of HTTP reserve status code 402 "Payment Required" - expecting micropayments to become core to the web. The technology to fulfill it doesn't exist yet.

May 2025
Coinbase Launches x402

Coinbase publishes the x402 protocol spec and reference implementation. USDC payments on Base, gasless transfers, facilitator-based settlement. The 402 code gets its protocol after 30 years.

Jun 2025
Ecosystem Takes Shape

Public roadmap released. Community contribution guidelines published. First integrations across Ethereum, Solana, and BNB Smart Chain. x402 Scan launches as the discovery and testing platform.

Sep 2025
x402 Foundation

Cloudflare and Coinbase co-launch the x402 Foundation to develop an open standard. Members include Google, Visa, AWS, Circle, Anthropic, and Vercel.

Dec 2025
V2 Release

Major upgrade after six months in production and 100M+ transactions. Multi-chain support (Base, Solana), fiat integration (ACH, cards), reusable wallet sessions, modular SDK, automatic API discovery.

2026
Agents SDK and Framework Wrappers

Purpose-built SDK for AI agents making autonomous payments. Framework-specific packages for Express, Next.js, Hono, Axios. MCP server support for x402-enabled tools.

The Payment Flow

Every x402 payment - from the initial request to the on-chain settlement - happens over standard HTTP. The client requests a resource, the server responds with a price, the client signs a payment and retries, and the server delivers the resource.

01
Client → Server
GET /resource

Request a paid resource via standard HTTP. No special headers, no setup.

02
Server → Client
402 + PAYMENT-REQUIRED header

Respond with pricing in a base64-encoded HTTP header: asset, amount, chain, recipient.

03
Client (local)
Sign gasless USDC transfer

Sign a token transfer authorization using the wallet's private key. Nothing leaves the device.

04
Client → Server
Retry with PAYMENT-SIGNATURE header

Retry the same request with the signed payment attached in an HTTP header.

05
Server → Facilitator
Forward signed payment

Forward the signed payment to a facilitator who verifies the signature and settles on the blockchain.

06
Facilitator → Server
Confirmed + tx hash

Facilitator pays gas, settles on Base L2, returns the on-chain transaction hash.

07
Server → Client
200 OK + resource + PAYMENT-RESPONSE

Deliver the resource plus a settlement receipt with the transaction hash.


Key technical details:

  • The payment is a gasless USDC transfer on Base (an OP Stack L2). The user signs the transfer locally but doesn't submit it to the blockchain. Instead, they send the signature to the server, and the facilitator handles the on-chain settlement.
  • Each signature includes a unique ID that can only be used once, preventing replay attacks
  • No chargebacks. Every transfer in traditional finance (credit cards, ACH, wires) can be clawed back. Stablecoin transfers, once settled and confirmed on-chain, are final

x402 vs. Traditional API Billing

If you've integrated with a paid API, you know the setup: sign up, add a credit card, get an API key, manage billing limits, deal with monthly invoices. x402 skips all of that.

Traditional APIx402
SetupSign up, verify identity, add credit card, get API keyJust have a crypto wallet
PaymentMonthly invoice, credit extensionPer-request, instant
AuthorizationAPI key + OAuth + rate limitsSigned payment in HTTP header
FrictionNeed a human to sign up, manage keys, handle billingAgent signs payments on its own
Smallest payment~$0.30 (Stripe's per-transaction fee)~$0.001 (L2 gas cost)

x402 separates payment from identity. Traditional APIs require you to prove who you are before they let you pay. x402 only cares that payment is confirmed, which is what makes it work for AI agents that need to hit hundreds of different APIs without signing enterprise agreements for each one.

While the protocol is designed for AI agents, it works just as well for manual browsing - a site can request payment from an installed wallet extension, and the user pays to access the page without creating an account.


The Three Roles: Client, Server, and Facilitator

x402 involves three parties. None of them need to trust each other; the protocol handles everything through cryptographic verification.

RoleWhat it doesWho runs it
ClientAny app or agent with a crypto wallet. Parses 402 responses, signs payments, retries automaticallyYou, your users, or AI agents
ServerHosts the API. Returns 402 with pricing, verifies payment via the facilitator, then serves the resourceYou (the API builder)
FacilitatorIndependent verification and settlement service. Non-custodial, never holds your funds. Pays gas on behalf of usersThird parties like x402.org, Coinbase CDP, or 22+ others

Your server forwards the signed payment to the facilitator's /verify and /settle endpoints. The facilitator handles blockchain interaction, gas fees, and settlement on your behalf.

HTTP Headers and Payloads ⬥

Three HTTP headers handle the entire payment lifecycle, all base64-encoded so they pass cleanly through proxies, CDNs, and existing infrastructure:

HeaderDirectionWhenWhat's inside
PAYMENT-REQUIREDServer → ClientWith the 402 responsePrice, token address, chain, recipient wallet, accepted payment schemes
PAYMENT-SIGNATUREClient → ServerOn the retry requestSigned gasless USDC transfer authorization
PAYMENT-RESPONSEServer → ClientWith the 200 responseSettlement confirmation and on-chain transaction hash

Click through each step to see the exact headers and payloads that travel over the wire:

Backwards Compatibility

Putting payment data in headers (instead of the response body) is a deliberate design choice:

  • The 402 response body stays empty ({}) so existing error handlers and monitoring tools don't break
  • Non-x402 clients just ignore the headers. A browser or curl sees a normal 402 error, nothing crashes
  • Proxies and CDNs pass headers through unchanged. No special middleware needed on your infrastructure

You can add x402 to existing API endpoints without breaking current clients. x402-aware clients auto-pay; everyone else sees a standard 402.


Part 2: Building Your First Paid Endpoint

Now that you understand the protocol, let's build something. By the end of this section you'll have a running Express server that charges per request and a client that pays automatically.

Wallet Setup

You'll need an Ethereum-compatible wallet on Base Sepolia (the testnet) and some test USDC to pay with. The private key never leaves your machine; it's only used to sign payments locally.

There are a few ways to get a wallet:

Option A: MetaMask

  • Install the MetaMask browser extension
  • Create a new wallet and save the recovery phrase
  • Click the account icon > Account details > Show private key
  • Copy the private key (starts with 0x)
  • Copy your wallet address from the top of MetaMask

Option B: Generate one from the command line:

bash
npx tsx -e "import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; const key = generatePrivateKey(); console.log('PRIVATE_KEY=' + key); console.log('ADDRESS=' + privateKeyToAccount(key).address);"

Option C: If you already have MetaMask or Coinbase Wallet set up, switch to Base Sepolia (Chain ID: 84532) and export the private key.

WARNING

Use a dedicated test wallet. Never put real funds in a wallet whose private key sits in a .env file or source code.

Next, fund the wallet with test USDC:

  • Go to faucet.circle.com
  • Select Base Sepolia as the network
  • Paste your wallet address and request USDC
  • The faucet gives ~10 test USDC, enough for hundreds of test requests
  • Verify the balance at https://sepolia.basescan.org/address/YOUR_ADDRESS

For reference, the USDC contract on Base Sepolia is 0x036CbD53842c5426634e7929541eC2318f3dCF7e.

Finally, create a .env file in your project root:

PRIVATE_KEY=0xabc123...your_private_key

In the server code below, replace 0xYOUR_WALLET_ADDRESS with this same wallet address - it's where payments get sent.

Adding x402 to an Express Server

The x402 V2 SDK uses scoped @x402/* packages. On the server, @x402/express provides payment middleware. On the client, @x402/fetch wraps standard fetch to automatically intercept 402 responses, sign a payment, and retry - you just see a normal 200.

Libraries also exist for Next.js, Hono, and Axios.

typescript
/* v2 pattern: create a resource server with a facilitator client,
 * register the EVM payment scheme, then define which routes require
 * payment using a route config object. */
import express from "express";
import cors from "cors";
import { paymentMiddleware } from "@x402/express";
import { x402ResourceServer, HTTPFacilitatorClient } from "@x402/core/server";
import { registerExactEvmScheme } from "@x402/evm/exact/server";

const app = express();
const payTo = "0xYOUR_WALLET_ADDRESS";

/* expose custom x402 headers so cross-origin clients can read them.
 * without this, browser fetch can't access payment-required
 * or payment-response even after the browser receives them. */
app.use(cors({
  origin: true,
  exposedHeaders: ["payment-required", "payment-response"],
}));

const facilitator = new HTTPFacilitatorClient({
  url: "https://x402.org/facilitator"                   // testnet + mainnet
});
const resourceServer = new x402ResourceServer(facilitator);
registerExactEvmScheme(resourceServer);

app.use(paymentMiddleware({
  "POST /extract": {
    accepts: [{
      scheme: "exact",
      price: "$0.01",
      network: "eip155:8453",                            // base mainnet (CAIP-2)
      payTo,
    }],
    description: "Structured web scrape with extracted data",
    mimeType: "application/json",
  },
}, resourceServer));

app.get("/health", (req, res) => {
  res.json({ status: "ok" });
});

app.post("/extract", async (req, res) => {
  /* only runs after payment is verified and settled on-chain */
  const { url } = req.body;
  const result = await scrapeAndExtract(url);
  res.json(result);
});

app.listen(3000);
typescript
/* @x402/fetch wraps standard fetch with automatic 402 handling.
 * create an x402 client, register the EVM scheme with your signer,
 * and wrap fetch. 402 responses are handled transparently. */
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount("0xYOUR_PRIVATE_KEY");
const client = new x402Client();
registerExactEvmScheme(client, { signer: account });
const paidFetch = wrapFetchWithPayment(fetch, client);

const res = await paidFetch("https://your-api.com/extract", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ url: "https://example.com" }),
});
const data = await res.json();
console.log(data);
typescript
/* x402 for MCP tools. connect to a facilitator, register the EVM scheme,
 * then build payment requirements for any tool you want to charge for.
 * initialize() must be called before building requirements. */
import { x402ResourceServer } from "@x402/mcp";
import { registerExactEvmScheme } from "@x402/evm/exact/server";
import { HTTPFacilitatorClient } from "@x402/core/server";

const facilitator = new HTTPFacilitatorClient({
  url: "https://x402.org/facilitator"
});
const resourceServer = new x402ResourceServer(facilitator);
registerExactEvmScheme(resourceServer);
await resourceServer.initialize();

const paymentReqs = await resourceServer.buildPaymentRequirements({
  scheme: "exact",
  network: "eip155:8453",                              // base mainnet (CAIP-2)
  amount: "10000",                                      // $0.01 USDC (6 decimals)
  asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
});

What the Middleware Handles

When a request hits a paid endpoint:

  1. No payment header: Returns 402 + PAYMENT-REQUIRED header with your pricing
  2. Invalid payment: Returns 402 with error details
  3. Valid payment: Sends it to the facilitator for verification and settlement, then calls your handler and adds the PAYMENT-RESPONSE header
  4. Free endpoint: Middleware isn't applied, everything works normally

Your handler code only runs after payment is verified and settled on-chain.

Testing Your Endpoint

With the server and client code in place, let's verify the whole flow works. Install the dependencies and start the server from the Express example above:

bash
npm install express cors @x402/express @x402/core @x402/evm
node server.js

Test the free endpoint first (should return 200):

bash
curl http://localhost:3000/health
# {"status":"ok"}

Then hit the paid endpoint without any payment header:

bash
curl -v -X POST http://localhost:3000/extract \
  -H "Content-Type: application/json" \
  -d '{"url":"https://example.com"}'

You'll get a 402 Payment Required response. The payment requirements travel in the PAYMENT-REQUIRED header as base64-encoded JSON. Grab that header value and decode it:

bash
echo 'eyJ4NDAyVm...' | base64 -d | jq .
json
{
  "x402Version": 2,
  "error": "Payment required",
  "resource": {
    "url": "POST /extract",
    "description": "Structured web scrape with extracted data",
    "mimeType": "application/json"
  },
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "amount": "10000",
      "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "payTo": "0xYOUR_WALLET_ADDRESS",
      "maxTimeoutSeconds": 300,
      "extra": {
        "name": "USD Coin",
        "version": "2"
      }
    }
  ]
}

The resource object identifies the endpoint. Each element in accepts is a complete payment requirement: amount is in the token's smallest unit (10000 = $0.01 with 6 decimal USDC), extra carries EIP-712 domain parameters needed for signing, and maxTimeoutSeconds sets the payment validity window.

Finally, run the client script to complete a full payment cycle:

bash
# in a separate terminal, with .env containing PRIVATE_KEY:
node client.js

The client's paidFetch handles the entire flow transparently:

  • Receives the 402 and reads the payment requirements from the header
  • Signs a gasless USDC transfer using your private key
  • Retries the request with the PAYMENT-SIGNATURE header attached
  • Returns a normal 200 response with your data

The response also includes a PAYMENT-RESPONSE header containing the on-chain settlement transaction hash. You can look it up on sepolia.basescan.org to confirm the payment settled.

Make a Real x402 Payment ⬥

Walk through the full x402 payment flow from your browser. Generate a testnet wallet, fund it with test USDC, and make a real paid request to Simplescraper's extract API on Base Sepolia.

Adding x402 to an Existing Authenticated Endpoint

If you already have an API with key-based authentication, you don't need to create a separate route for x402. The payment middleware and your existing auth can serve the same endpoint.

One important detail: the x402 middleware returns 402 for any matching route that doesn't have a PAYMENT-SIGNATURE header. That means if you mount it before your route handler, API-key requests (which don't have payment headers) will get a 402 instead of reaching your auth logic. The fix is two middleware layers: a dual-auth wrapper that routes requests to x402 or your existing auth, and an auth middleware that resolves permissions before the route handler runs.

typescript
import express from "express";
import cors from "cors";
import { paymentMiddleware } from "@x402/express";
import { x402ResourceServer, HTTPFacilitatorClient } from "@x402/core/server";
import { registerExactEvmScheme } from "@x402/evm/exact/server";

const app = express();
const payTo = "0xYOUR_WALLET_ADDRESS";

app.use(cors({
  origin: true,
  exposedHeaders: ["payment-required", "payment-response"],
}));

/* set up the x402 resource server and facilitator */
const facilitator = new HTTPFacilitatorClient({
  url: "https://x402.org/facilitator"
});
const resourceServer = new x402ResourceServer(facilitator);
registerExactEvmScheme(resourceServer);

/* create the x402 payment middleware */
const x402Mw = paymentMiddleware({
  "POST /extract": {
    accepts: [{
      scheme: "exact",
      price: "$0.01",
      network: "eip155:8453",
      payTo,
    }],
    description: "Structured web scrape with extracted data",
    mimeType: "application/json",
  },
}, resourceServer);

/* dual-auth wrapper: API key requests skip x402 entirely.
 * for requests without an API key, x402 middleware handles it.
 * the wrapped next() callback ensures req.paidViaX402 is only
 * set AFTER x402 has verified the payment. if x402 returns 402
 * or rejects the payment, it never calls next(). */
app.use((req, res, next) => {
  const apiKey = req.headers.authorization
    ? req.headers.authorization.split(" ")[1]
    : req.query.apikey;
  if (apiKey) return next();
  return x402Mw(req, res, () => {
    req.paidViaX402 = true;
    next();
  });
});

/* auth middleware for /extract: resolves permissions before the
 * route handler runs. sets req.user for API key path, or passes
 * through for x402 (payment already verified by the wrapper). */
async function extractAuth(req, res, next) {
  if (req.paidViaX402) return next();

  const apiKey = req.headers.authorization?.split(" ")[1]
    || req.query.apikey;
  if (!apiKey) return res.status(401).json({ error: "unauthorized" });

  const user = await getUserByApiKey(apiKey);
  if (!user) return res.status(401).json({ error: "invalid API key" });
  if (!user.credits) return res.status(402).json({ error: "out of credits" });

  req.user = user;
  next();
}

app.post("/extract", extractAuth, async (req, res) => {
  /* auth already resolved - just run business logic */
  const { url } = req.body;
  const result = await scrapeAndExtract(url);

  /* deduct credits for API key users (x402 already paid on-chain) */
  if (req.user) {
    await deductCredits(req.user.uid, 1);
  }

  res.json(result);
});

Three request types hit the same URL:

  1. Valid payment - no API key, so the wrapper passes to x402. x402 verifies the signed payment and calls the wrapped next(), setting req.paidViaX402 = true. extractAuth sees the flag and passes through. The handler runs without credit deduction.
  2. API key - the wrapper skips x402 entirely. extractAuth validates the key, loads the user, checks credits, and sets req.user. The handler runs and deducts credits.
  3. Neither - the wrapper passes to x402, which returns 402 Payment Required with pricing in the response header. next() is never called, so the route handler never runs.

The key detail is the wrapped next() callback on the x402 middleware. Passing next directly would set the trust flag before payment verification. Wrapping it means req.paidViaX402 is only set after x402 has confirmed the payment is valid - if verification fails, x402 returns an error and never calls next().

The result is a single endpoint that serves both traditional API key users and x402 clients. Auth is fully resolved in middleware before the route handler runs. New clients can pay per-request without creating an account.


Part 3: From Testnet to Production

At this point you have a working paid endpoint on testnet. Shipping it to production means changing four configuration values.

Configuration Changes

WhatTestnetProduction
Networkeip155:84532 (Base Sepolia)eip155:8453 (Base Mainnet)
USDC contract0x036CbD53842c5426634e7929541eC2318f3dCF7e0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
WalletTest wallet funded via faucet.circle.comProduction wallet with real USDC
Pricing$0.001 (test amounts)Your real per-request price

Two facilitator endpoints are available:

FacilitatorNetworksUse case
https://x402.org/facilitatorBase Sepolia, Solana DevnetTestnet only
https://api.cdp.coinbase.com/platform/v2/x402Base, Base Sepolia, Solana, Solana DevnetTestnet and production
  • The x402.org facilitator is community-run and good for development, but only supports testnets
  • The CDP facilitator requires a Coinbase Developer Platform account but handles production traffic
  • Over 22 additional facilitators are listed in the ecosystem directory, covering various chains and use cases

The facilitator pays gas on Base (~$0.001 per settlement).

Deploying to Production

  1. Generate or use a production wallet. Hardware wallets or secure key management (AWS KMS, GCP Cloud KMS) are recommended - the private key controls where payments are received
  2. Switch the network from eip155:84532 (Base Sepolia) to eip155:8453 (Base mainnet) in your route config
  3. Switch to a production-capable facilitator like CDP: https://api.cdp.coinbase.com/platform/v2/x402
  4. Set real pricing based on your compute costs. The testnet $0.001 was for testing - price to cover your actual cost per request
  5. The USDC contract changes automatically with the network. The SDK resolves the correct contract address for mainnet (0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913) when you set the network to eip155:8453
  6. Monitor settlements at basescan.org (mainnet, not sepolia.basescan.org). Search your payTo address to see every settlement transaction

Part 4: The Ecosystem

You've seen how to build, test, and deploy a paid endpoint. Here's the broader picture of where x402 stands today.

Growth and Traction

x402 has processed over 100 million payments since launching in May 2025. Real money on real chains.

  • 22+ facilitators operating as independent settlement providers
  • 10,000+ resources (paid API endpoints live in the ecosystem)
  • $3M+ in volume and growing fast
  • Chains: Base (dominant), Solana (growing fast), Polygon, Avalanche, and more

The x402 Foundation (Coinbase + Cloudflare) governs the spec, but anyone can build a facilitator, client library, or paid endpoint.

What People Are Building

Early adoption is clustering around categories where per-request pricing is a natural fit:

AI inference - Pay-per-prompt wrappers around model APIs. Anyone can stand up an LLM endpoint and charge per call.

Data enrichment - Weather, prediction markets, company lookup, email verification. Per-call pricing for data that has real-time value.

Walled garden data - Access to data behind platform walls (LinkedIn profiles, X/Twitter posts) where official APIs are nonexistent or prohibitively expensive. CRM-style enrichment at ~1 cent per lookup.

Web scraping - Structured extraction from any URL, rendered screenshots, PDF conversion. Services like Simplescraper handle the scraping and return structured data for cents per request.

API fractionalization - Enterprises buying bulk unlimited API access and rewrapping it as usage-based x402 endpoints. Thousands of agents pay per-call against a single fixed-cost subscription.

AI agents are bad at parsing bloated HTML, managing headless browser instances, and bypassing modern bot protection. Structured data extraction behind an x402 endpoint lets agents autonomously buy clean, parsed data when they need it. If you're running a scraping service (like we do at Simplescraper), you can expose paid endpoints that return exactly the structured JSON an LLM needs.

typescript
import express from "express";
import { paymentMiddleware } from "@x402/express";
import { x402ResourceServer, HTTPFacilitatorClient } from "@x402/core/server";
import { registerExactEvmScheme } from "@x402/evm/exact/server";

const app = express();
const payTo = process.env.PAY_TO_ADDRESS;

const facilitator = new HTTPFacilitatorClient({
  url: "https://x402.org/facilitator"
});
const resourceServer = new x402ResourceServer(facilitator);
registerExactEvmScheme(resourceServer);

app.use(paymentMiddleware({
  "GET /scrape": {
    accepts: [{ scheme: "exact", price: "$0.01", network: "eip155:8453", payTo }],
    description: "Structured web scrape with extracted text and metadata",
    mimeType: "application/json",
  },
  "GET /hn-digest": {
    accepts: [{ scheme: "exact", price: "$0.005", network: "eip155:8453", payTo }],
    description: "Top 10 HN stories with top comment and category tags",
    mimeType: "application/json",
  },
}, resourceServer));

app.get("/scrape", async (req, res) => {
  const url = req.query.url;
  if (!url) return res.status(400).json({ error: "url parameter required" });
  const result = await scrapeAndStructure(url);
  res.json(result);
});

app.get("/hn-digest", async (req, res) => {
  const stories = await fetchHNTopStories(10);
  res.json(stories);
});

app.listen(3000, () => {
  console.log("Scraping API running on port 3000");
});

From the buyer's perspective: an agent pays cents for structured data that would otherwise require a massive prompt window and complex tooling to scrape itself. From the seller's perspective: get paid per request without managing API keys, billing systems, or user accounts.

What Comes Next

The web's payment infrastructure was built on a set of assumptions: identity verification, credit extension, monthly billing cycles, minimum transaction sizes. x402 operates on a different set entirely: instant settlement, sub-cent fees, payment without identity.

We've seen this pattern before. In the mid-1990s, typing a credit card into a website felt reckless. Now our payment details are stored across hundreds of sites and saved in our browsers without a second thought. What seemed absurd became unremarkable once the infrastructure matured and businesses caught up.

x402 is following a similar arc. The protocol is viable today. It's being tested across thousands of endpoints with real money.

The next phase is infrastructure-level adoption: some browsers already ship built-in crypto wallets, Coinbase's extension wallet has tens of millions of users, and Stripe launched x402 support in February 2026.

The question was never whether agents would transact online. It was how. Suddenly it looks like all the pieces are in place. Crypto finds a real use case, HTTP code 402 gets the protocol it was reserved for, and AI agents get rails that enable permissionless payments.

The how is solved. As we saw in the early days of ecommerce, next comes scale.


Get Started

  1. Try it yourself: Clone the x402 implementation examples and run the test suite
  2. Read the spec: docs.x402.org for the official protocol documentation
  3. Explore live resources: x402scan.com to discover and test x402 endpoints
  4. Build a paid endpoint: Use the Express middleware example above

Scrape Data with Simplescraper

Turn websites into structured data in seconds.