ByAUJay
Metered Web3 Services: Designing Per‑Request Pricing with x402
A Practical Guide for Product and Platform Teams to Ship Pay-Per-Request APIs and Web Services Using the x402 Protocol
In this guide, we’ll dive into how product and platform teams can effectively roll out pay-per-request APIs and web services utilizing the x402 protocol (HTTP 402 “Payment Required”). We’ll cover some solid patterns, share handy code snippets, and highlight some up-and-coming best practices along the way.
Why x402?
The x402 protocol is designed specifically to handle payment requests in a straightforward way. By integrating it into your API, you can ensure that users pay as they go--making it a win-win for both you and your customers.
Key Patterns
Here are a few patterns that are essential for implementing the x402 protocol efficiently:
- Request Flow: Make sure your request flow is clear. Users should understand when and how they’ll be charged.
- Error Handling: Set up robust error handling to manage payment failures. It’s important to provide clear feedback to users about what went wrong.
- User Notifications: Keep users in the loop with notifications for both successful and failed payment requests.
Code Snippets
Here are some snippets to help you get started with the x402 protocol:
Basic Payment Request Example
POST /api/endpoint HTTP/1.1
Host: example.com
Content-Type: application/json
{
"request": "request_data"
}
Payment Required Response
HTTP/1.1 402 Payment Required
Content-Type: application/json
{
"error": "Payment is required to process your request."
}
Emerging Best Practices
As we embrace the x402 protocol, here are some best practices to keep in mind:
- Clear Documentation: Make sure your API documentation is spot-on. This will help users understand how to interact with your service.
- Testing Payment Scenarios: Rigorously test various payment scenarios to iron out any issues before going live.
- User Experience Focus: Design your payment process to be as seamless as possible. A smooth user experience can make all the difference.
By following these guidelines, you’ll be well on your way to shipping effective pay-per-request APIs and web services that users will appreciate. Happy coding!
x402 takes the unused HTTP 402 status and transforms it into a seamless payment handshake for the web. It's open, works across different blockchains, and is made for both people and AI agents to make payments per call using stablecoins and other tokens--without the hassle of accounts, OAuth, or complicated checkout processes. Check it out here: (docs.cdp.coinbase.com)
TL;DR (meta description)
x402 lets you sell API calls and web resources on a per-request basis using the HTTP 402 status along with just one header. In this post, 7Block Labs walks you through how to create pricing models, select a facilitator, implement the exact/upto schemes, and launch on chains that settle in about 2 seconds with no protocol fees at all. Check it out here: (github.com)
Why per‑request pricing now
- Nowadays, buyers are all about software: think AI agents, background jobs, and server-to-server integrations. They want payments to happen seamlessly within the same HTTP flow, instead of dealing with separate user checkouts or those pesky monthly invoices. That’s where x402 comes in, embedding payments into your existing request-response cycle. Check it out here: (coinbase.com)
- The best part? The protocol is open-source (Apache-2.0) with a public spec and SDKs available in multiple languages (TypeScript, Python, Go, Java). It's all managed in Coinbase’s GitHub repo, and there's a growing community around it too. Dive into it here: (github.com)
- And here’s where it gets exciting: adoption is really picking up speed! Reports from October 2025 show a staggering 10,000%+ monthly growth and hundreds of thousands of weekly transactions across various chains as more x402 endpoints and facilitators come into play. While you should take those numbers as rough estimates, there’s no denying the momentum is definitely there. For more details, check this out: (finance.yahoo.com)
What x402 actually standardizes
At its core, x402 lays out:
- A 402 JSON response shape (Payment Required Response) that lets your server share accepted payment options.
- After making a payment, clients should attach a single request header: X‑PAYMENT (base64‑encoded JSON payload).
- An optional response header: X‑PAYMENT‑RESPONSE is available for you to send back transaction details for reconciliation.
- A handy facilitator API that includes /verify and /settle endpoints, which means your service doesn’t need to manage chain nodes or hold onto any keys. (github.com)
x402 is all about keeping things simple and sticking to pure HTTP--no fancy RPCs or custom protocols getting in the way. When you send back a 402, you’ll include some structured metadata. The client then pays up and retries the same URL, but this time with the header X‑PAYMENT. If you already have the payment details sorted out (like a set price), you can skip the initial 402 challenge altogether. Check it out on github.com!
The protocol flow (concrete)
- So, the client asks for a paid resource.
- Then, the server hits back with a 402 response, laying out the pricing details and accepted rails (you know, chain, token, scheme).
- Next, the client puts together a payment payload that's specific to the scheme, signs it with EIP-712 if needed, and makes the payment.
- Finally, the client gives it another shot with X-PAYMENT; the server checks everything using its local logic or through a facilitator (/verify), settles it with /settle, and then sends back a 200 response along with your data and a possible X-PAYMENT-RESPONSE. (github.com)
Example 402 Body
Here's a simplified version showing the valid fields from the spec:
{
"id": "402",
"type": "payment",
"amount": {
"currency": "USD",
"value": "50.00"
},
"description": "Payment for services rendered",
"status": "completed",
"timestamp": "2023-10-01T12:00:00Z"
}
{
"x402Version": 1,
"accepts": [
{
"scheme": "exact",
"network": "base",
"asset": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"maxAmountRequired": "1000",
"resource": "https://api.example.com/premium-data",
"description": "Stock price snapshot",
"mimeType": "application/json",
"payTo": "0xYourMerchantAddress",
"maxTimeoutSeconds": 30,
"extra": { "name": "USD Coin", "version": "2" }
}
]
}
What the Client Sends Next
When the client reaches out again, here’s what you can expect:
- Clear Requirements: They’ll usually lay out their needs pretty straightforwardly. It helps if they give specific examples or references, so you know exactly what they’re aiming for.
- Feedback on Previous Work: Expect some thoughts on what you’ve done so far. This feedback can be constructive--likely pointing out what they liked, and where they think improvements can be made.
- Deadlines and Timelines: Keep an eye out for any urgent timelines they might mention. If they need something by a certain date, they’ll definitely let you know.
- Budget Considerations: Sometimes, they’ll also touch upon budget constraints or adjustments. It’s important to keep this in mind as you move forward.
- Any Additional Resources: They might share links to articles, videos, or documents that can help clarify their vision. Don’t overlook these--they can be gold when it comes to understanding their expectations!
Once you have their input, you’ll be better equipped to tailor your work to match their vision.
X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6MSwic2NoZW1lIjoiZXhhY3QiLCJuZXR3b3JrIjoiYmFzZSIsInBheWxvYWQiOns... (base64 JSON)
The server's success response might include:
X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0eEhhc2giOiIweDk4Yy4uLiIsIm5ldHdvcmtJZCI6ImJhc2UifQ==
Check out the spec for all the TypeScript type definitions and header encoding rules. You can find it here.
Schemes: exact now, upto for variable units
- exact: You can charge a set fee for each request, like $0.01 for an endpoint. This is already part of the core spec and works across all EVM implementations. Check it out on GitHub.
- upto: This option allows the caller to authorize "up to" a certain number of units, and you figure out the final amount based on what was actually used after the work is done (think tokens generated or MB processed). Several SDKs, like thirdweb’s facilitator, offer this "upto" mode for EVM and SVM pilots while everyone in the community works towards a standard approach. It’s a great choice for LLMs or any workloads where costs can vary. More details are available at thirdweb.
Choosing chains and tokens (what works in production)
- EVM + USDC (EIP‑3009): This setup allows for gasless, signature-based transfers using
transferWithAuthorizationandreceiveWithAuthorization. A lot of x402 stacks use USDC as their go-to choice since it naturally supports EIP‑3009. If you use it right (definitely go withreceiveWithAuthorizationfrom contracts), you can dodge those annoying front-running issues. Check out the details on EIP-3009. - EVM + any ERC‑20 with ERC‑2612 permit: Great news! thirdweb’s facilitator has now got a cool feature that automatically figures out if a token is all about that permit life or if it leans towards EIP‑3009 and picks the best flow for you. This opens up the door to over 170 EVM chains and a huge range of tokens. Dive into the specifics at thirdweb's portal.
- Settlement times: The x402 docs rave about “~2-second settlement” and being chain-agnostic. In reality, for the smoothest experience, it's best to choose networks with quick finality and native USDC. While the protocol-level fees are zero, keep in mind you’ll still need to cover gas and any facilitator fees. More info can be found at x402.org.
Here are some key details we’ve confirmed through our fieldwork:
- ERC‑3009 is based on EIP‑712, so make sure to use
receiveWithAuthorizationwhen moving tokens into your contract. This will help you avoid issues like mempool preimage sniping. Check it out here: (eips.ethereum.org) - Just a heads up: not all chains’ “USDC” are created equal. Bridged versions might not work with EIP‑3009. Always double-check the token ABIs and domain separators (like name and version) for permit/EIP‑3009 during runtime. More info here: (web3-ethereum-defi.readthedocs.io)
- If you're dealing with legacy tokens, they might not support ERC‑2612. It’s a good idea to set up a smooth fallback (like the approve flow) or consider switching to Permit2 depending on how much risk you're willing to take. Learn more at: (0x.org)
Facilitators: who verifies and settles the payment?
A facilitator takes care of the nitty-gritty details like RPCs, gas, and signature checks, so your API team doesn’t have to worry about them. You can use:
- Coinbase x402 Facilitator: This one's your go-to for all the official docs, Embedded Wallets integration, and business treasury settlement. If you're looking for an easy operational setup and want the option for a fiat off-ramp through Coinbase Business, this is a solid choice. Check it out here: (coinbase.com)
- thirdweb x402: With client/server SDKs, wrapFetchWithPayment, and node-free verification/settlement, this has got you covered for ERC-2612 and EIP-3009 flows. Plus, it comes with both exact and up-to modes. Dive in here: (portal.thirdweb.com)
- Ecosystem Facilitators and Gateways:
- AEON on BNB Chain: This one’s great for managing tokens, whether they use EIP-3009 or not. More info here: (finance.yahoo.com)
- Sol402: Quick and easy USDC pay-per-link/pay-per-API setup for Solana, done in just minutes. Check it out at: (sol402.app)
- 402x: A handy dashboard tool that’s “powered by x402.” Take a look: (402x.io)
- Payin: They have a detailed public explainer/spec that outlines the 4-step protocol flow. Get the scoop here: (payin.com)
All facilitators are required to stick to the same basic REST endpoints: POST /verify, POST /settle, and GET /supported. This way, you can switch providers without having to rewrite your entire application. Check out the details on GitHub!
Implementation: minimum viable 402 in under 30 minutes
Server Setup (Express, EVM, USDC on Base) using the Reference Middleware Pattern
Alright, let’s dive into setting up a server using Express along with the Ethereum Virtual Machine (EVM) and USDC on Base. We'll go with the reference middleware pattern, which is super handy for keeping things organized and scalable.
Step 1: Setting Up Your Project
First things first, let’s create a new directory for your project and jump into it:
mkdir my-express-app
cd my-express-app
Next, you’ll want to initialize your project with npm. This will create a package.json file for you:
npm init -y
Step 2: Installing Dependencies
Now, let’s get the necessary packages installed. You'll need Express for handling requests and other utilities for dealing with EVM and USDC:
npm install express body-parser dotenv
If you're going to interact with the EVM, don’t forget to grab the Web3.js library:
npm install web3
Step 3: Setting Up Express Server
Create a new file named server.js:
const express = require('express');
const bodyParser = require('body-parser');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
// Your API routes will go here
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 4: Adding Middleware
Now let’s add some middleware to handle transactions. You can create a middleware function that checks for valid USDC transactions:
function checkUSDC(req, res, next) {
const { amount } = req.body;
if (amount && amount > 0) {
next(); // All good, move to the next middleware
} else {
res.status(400).json({ error: "Invalid transaction amount" });
}
}
// Use the middleware in your route
app.post('/send-usdc', checkUSDC, (req, res) => {
const { amount } = req.body;
// Logic to send USDC goes here
res.json({ message: `Successfully sent ${amount} USDC!` });
});
Step 5: Connecting to EVM
Now, to connect to the EVM, you can set up Web3. Just add this in your server.js file:
const Web3 = require('web3');
const web3 = new Web3(process.env.EVM_URL); // EVM_URL should be set in your .env file
// Add your logic to interact with the blockchain here
Step 6: Final Touches
Don't forget to set up your environment variables in a .env file. You might need entries for things like your EVM URL and possibly some API keys:
EVM_URL=https://your-evm-url-here
PORT=3000
Conclusion
And there you have it! You've set up a basic server using Express that can handle USDC transactions on the EVM. Feel free to expand this as needed, maybe adding more routes or more complex middleware. Happy coding!
// server.ts
import express from "express";
import { paymentMiddleware } from "x402/server"; // representative import per README
const app = express();
// Charge $0.01 per call; receive funds to your address
app.use(paymentMiddleware("0xYourMerchantAddress", { "/v1/report": "$0.01" }));
app.get("/v1/report", async (_req, res) => {
res.json({ ok: true, data: await buildReport() });
});
app.listen(3000);
The middleware takes care of a few key tasks: it returns a standard 402 JSON response, checks X‑PAYMENT using /verify, processes settlements through /settle, and sends back the X‑PAYMENT‑RESPONSE along with txHash when everything goes smoothly. For the full setup of your environment, check out the examples in the repo. (github.com)
Client (browser/Node) that auto-pays on 402:
If you're looking to set up a client--whether it's in the browser or Node.js--that automatically handles payments for a 402 error, you’re in the right place. Let’s break down how to get this done smoothly.
Step 1: Understand the 402 Error
Before diving in, it's essential to know that a 402 error indicates “Payment Required.” This typically means that the client needs to make a payment before proceeding. So, our goal is to automate that process.
Step 2: Set Up Your Client
Here’s how you can set up your client to handle these payments.
In the Browser
If you’re working with a web-based client, you can use the Fetch API to manage payment requests. Here’s a simple example:
fetch('https://example.com/payment', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: 1000, // Amount in cents
currency: 'USD',
// Include additional payment info here
}),
})
.then(response => {
if (response.status === 402) {
// Handle payment
console.log('Payment required, processing...');
} else {
console.log('Payment successful or another error');
}
})
.catch(error => console.error('Error:', error));
In Node.js
For a Node.js client, you can use libraries like Axios to make things easier. Here’s a quick example:
const axios = require('axios');
axios.post('https://example.com/payment', {
amount: 1000, // Amount in cents
currency: 'USD',
// Any other payment details you need
})
.then((response) => {
if (response.status === 402) {
console.log('Payment required, proceeding with the payment...');
// Code to handle payment
} else {
console.log('Payment completed successfully or encountered another issue');
}
})
.catch((error) => {
console.error('There was an error processing the request:', error);
});
Step 3: Handle Payment Confirmation
Once the payment is processed, make sure to handle the confirmation appropriately. This could involve displaying a success message to the user or updating their account status.
Conclusion
Setting up an auto-paying client for a 402 response in both browser and Node.js isn’t too complicated. Just ensure you have the right payment details and handling mechanisms in place. With the examples provided, you should be good to go!
If you have any questions or need further help, feel free to reach out!
import { wrapFetchWithPayment } from "thirdweb/x402";
import { createThirdwebClient } from "thirdweb";
import { createWallet } from "thirdweb/wallets";
const client = createThirdwebClient({ clientId: process.env.TW_CLIENT_ID! });
const wallet = await createWallet("io.metamask").connect({ client });
const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet);
// Will automatically parse the 402, sign EIP-712, pay USDC, and retry
const r = await fetchWithPay("https://api.example.com/v1/report");
console.log(await r.json());
This path doesn't ask for any account setup, redirects, or annoying UI prompts--perfect for agents and backends. Check it out here: (portal.thirdweb.com)
Pricing models that map well to x402
- Fixed per-call (exact)
- This one's great for specific, limited tasks: think “$0.01 per lookup” or “$0.05 per image upscaling.”
- Setup: Just have one accept entry with maxAmountRequired set to price_in_atomic_units; if it goes over the quota, hit them with a 402 response again. Check it out on (github.com).
2) Elastic Usage (Up To)
- When it comes to tokenized workloads like LLMs, storage, or egress, expect to pay around “$0.10 for every 1K tokens” and “$0.002 per MB.”
- Here’s how it works: you set a maximum cap, the client gives the green light for up to N, and once everything’s done, you just settle based on the actual usage, which should be ≤ cap. Be sure to send over a usage meter and include a receipt that details the usage in your response body. Good news--thirdweb’s stack already shows up to controls as a preview. Check it out at (portal.thirdweb.com).
3) Bundled Bursts
- Offer a pre-paid bundle (like a $5 option) that has an expiry date. You’ll want to track the usage on the server-side, reducing the balance until it hits zero. Make sure to only trigger the 402 roundtrip when the bundle is all used up. The spec's extra and outputSchema fields work perfectly for sharing the semantics and units. Check it out on GitHub!
- Dual-rail fallbacks
- Provide a couple of options for accepting entries, like Base USDC or Solana USDC. Clients can choose whichever is the fastest or cheapest for them. This way, you maintain just one code path. (github.com)
Pricing Calibration Tips We Use with Clients:
When it comes to pricing, getting it just right can be tricky. Here are some handy tips we've found useful while working with clients:
1. Know Your Costs
Understanding your costs is essential. Take the time to break down all expenses--fixed and variable. This will give you a solid foundation for pricing. You don’t want to end up in the red.
2. Understand Your Market
Research your competitors and see what they’re charging. This helps you position yourself without underselling or overpricing your services. You want to stand out, but not scare off potential customers.
3. Value Perception
Think about the value your product or service brings to customers. If you can clearly demonstrate how you’re solving their problems or meeting their needs, you can justify a higher price. People are often willing to pay more for something they see as valuable.
4. Test Pricing Strategies
Don't hesitate to experiment with different pricing models. Consider offering:
- Tiered pricing: Different levels of service at different price points.
- Freemium: Basic services for free with the option to upgrade.
- Bundles: Group related services together at a discounted rate.
Try a few and see what resonates with your audience.
5. Collect Feedback
Ask your customers for feedback on your pricing. Are they willing to pay what you’re asking? This information is invaluable and can lead to adjustments that better align with what your market wants.
6. Monitor and Adjust
Pricing isn’t a set-it-and-forget-it process. Keep an eye on your sales and market conditions. If you see a dip in demand, it might be time to reassess your pricing.
7. Transparency is Key
Be clear about why your prices are what they are. Sharing the rationale helps build trust with customers. If they understand the quality and effort behind your pricing, they’re more likely to accept it.
8. Keep It Simple
Avoid overly complicated pricing structures. The more straightforward your pricing, the easier it is for customers to make decisions. No one likes to sift through a maze of options.
9. Leverage Psychological Pricing
Consider using prices that end in .99 or .95. They tend to be more appealing and can make a big difference in customer perception.
10. Regular Review
Finally, make it a habit to review your pricing strategy at least once a year. This allows you to stay competitive and adjust to any changes in the market.
By following these tips, we're able to help our clients find a pricing strategy that fits their business and resonates with their audience. Happy calibrating!
- Try out “shadow metering” for a couple of weeks, around 2 to 4: keep track of per-request units at a $0 price to get a sense of a workable schedule before you start settling up.
- Start by pricing in stablecoins like USDC; hold off on dabbling in volatile tokens until you’ve nailed down your unit economics and hedging.
- In your documentation, quote prices in user-friendly fiat, but make sure you stick to on-chain amounts using asset decimals in maxAmountRequired.
Security, trust, and auditability
- EIP‑712 everywhere: Make sure your typed data includes the right chainId, verifyingContract, and the token name/version when you're signing permits or EIP‑3009 authorizations. This is super important for preventing cross‑chain replay issues and mis‑domain signatures. You can check out more details here.
- Prefer receiveWithAuthorization: When you're moving USDC into your contract, go for
receiveWithAuthorizationinstead oftransferWithAuthorization. This connects the payee and helps cut down on front‑run vectors. Want to learn more? Head over to this link. - KYT/AML: Just a heads up, production facilitators might block addresses that get flagged. You should also show errors from the 402 JSON error field, which will help callers recover smoothly. Check out the specifics here.
- Idempotency: It’s a good idea to accept an Idempotency‑Key header, link it to the payment preimage/txHash, and that way, you can avoid any double work if a client decides to retry.
- Refunds/chargebacks: These aren’t included in the base specification. You might want to think about implementing credits (negative usage) on your end or issue a compensating on‑chain transfer with a new X‑PAYMENT‑RESPONSE correlation ID.
- Observability: Always keep track of the X‑PAYMENT payload, the response from the facilitator’s /verify call, and your final X‑PAYMENT‑RESPONSE. Don’t forget to pipe txHash into your BI stack for smooth analysis!
Compliance and accounting
- Treasury Ops: With Coinbase, you can easily route your proceeds to a Coinbase Business account that allows for fiat conversion. Other options let you pay directly into your merchant wallet. It’s a good idea to set up a reconciliation job that matches the
txHashin theX‑PAYMENT‑RESPONSEto your invoice line items. Check out more details on coinbase.com. - Tax: Make sure to treat each API call as recognized revenue the moment you deliver the response. Keep track of the transaction hash, the chain, the payer's address, and your unit economics in your ledger.
- Privacy: The x402 API doesn’t ask for email or account IDs, which is pretty great for privacy. If you need to keep track of who’s who, just throw in a signed client tag in your request body or consider using per-buyer wallet derivation.
Architecture patterns we recommend
- Edge 402 enforcement: Make sure to set up the x402 middleware right at the edge--using something like a Cloudflare Worker, an nginx module, or a gateway provided by your facilitator. This way, you won't have to compute anything before payment comes in. Some gateways, like g402, can operate under your own domain through CNAME, which helps keep those SSL chains intact and maintains enterprise trust. Check it out at g402.ai.
- Decouple metering from business logic: It’s a smart move to route all your paid endpoints through one verifier module. This module will send out a standard “PaymentVerified” event, which you can then subscribe to for tracking analytics and handling refunds.
- Strict timeouts: Always stick to the maxTimeoutSeconds set from your own 402 challenges. If your processing goes over, just return a partial response along with a fresh 402 for whatever remains. You can find more details on this on GitHub.
- Discovery: If you’re looking to get some agent traffic, consider advertising in up-and-coming catalog layers like the “x402 Bazaar.” It’s essentially a search and discovery index specifically for agent-grade endpoints. More info can be found on CoinDesk.
Concrete example: pay‑per‑1K tokens for an LLM endpoint (upto)
- Metering unit: output tokens; price: $0.10 per 1K.
- Challenge: We need to set a cap for the requested max_tokens. For example, you can calculate maxAmountRequired like this:
maxAmountRequired = ceil(max_tokens/1000 * $0.10in atomic USDC. - Client: The client gives the green light for the cap and sets a deadline of 60 seconds. If needed, they can retry using X-PAYMENT.
- Server: The server takes care of the inference, figures out the actual token usage, settles the amount (which should be less than or equal to the cap), and responds with a 200 status. The response body looks like this:
{ usage: { tokens: 642, cost_usdc: "0.0642" }, txHash }. - Observability: Make sure to emit metrics for each buyer wallet, tracking the p95 end-to-end latency from the initial 402 response to the final 200.
thirdweb’s upto support makes this pattern super user-friendly right now, even as the core spec is evolving. Check it out at (portal.thirdweb.com).
Ecosystem snapshot (Nov-Dec 2025)
- Spec & Reference: Check out the coinbase/x402 repo for some solid examples and the ROADMAP. You’ll find formal type definitions like PaymentRequirements, the X‑PAYMENT schema, and the Facilitator API right there. (github.com)
- Docs: The Coinbase x402 docs do a great job of breaking down the 402 semantics, how to use the agent, and getting into EIP‑712 signing. (docs.cdp.coinbase.com)
- Tooling:
- Thirdweb x402: Supports over 170 EVM chains and can automatically detect whether you need a permit or EIP‑3009. (portal.thirdweb.com)
- Sol402: This one’s all about Solana -- it allows for USDC pay-per-link/API. (sol402.app)
- 402x Dashboard: A handy tool for multi-chain commercialization. (402x.io)
- Payin Explainer/Spec: A super developer-friendly walkthrough of the protocol. (payin.com)
- Market Signals: We've seen some significant volume spikes and new facilitators popping up, like AEON on the BNB Chain. Just a heads up, the numbers can vary depending on where you look, so we recommend tracking your rails through Dune or looking at your facilitator’s analytics. (finance.yahoo.com)
Pitfalls to avoid
- First up, if we’re talking about “USDC” being the same across the board, make sure to check for the EIP‑3009 presence. For ERC‑2612, you’ll want to grab the token name and version on-the-fly for the EIP‑712 domain. Check it out here: (web3-ethereum-defi.readthedocs.io).
- Don’t forget about replay protection! It's essential to include the chainId and verifyingContract. And hey, it’s a good idea to keep those validity windows (validBefore) short on authorizations. More details here: (ercs.eips.fyi).
- If you’re thinking about key management, consider letting a facilitator or integrated wallets, like Coinbase Embedded Wallets, take care of custody and signing wherever you can. It might simplify things a lot! Learn more at: (docs.cdp.coinbase.com).
- Lastly, when you're customizing the 402 JSON, stick to the fields listed in the spec (resource, asset, payTo, maxAmountRequired, extra). Clients really rely on those predictable structures. You can find the spec here: (github.com).
Launch checklist (7Block Labs playbook)
- Product
- Define the metering unit (request, 1K tokens, MB).
- Begin with exact measurements; once you have accurate metering, you can shift to approximate.
- Price in USDC; create and share a fiat mapping table for the documentation.
- Engineering
- Connect the facilitator and middleware, ensuring we get a spec-compliant 402 back.
- Set up idempotency and rate limits, and make sure to emit canonical events.
- Keep a log of X-PAYMENT, /verify results, and txHash for our accounting purposes.
- Security & Compliance
- We're implementing EIP‑712 domain checks, keeping those deadlines short, and using receiveWithAuthorization. Check it out here.
- You’ll now see KYT outcomes in the error field, plus we’ve got a fallback UX for any blocked payers. More info can be found here.
- We’re rolling out a reconciliation job that ties txHash to request and revenue line.
- Ops
- Keep the shadow meter running for about 2 to 4 weeks before flipping the switch on settlement.
- Connect Dune or your data lake to transaction hashes for those live dashboards.
- Make sure to jot down what buyers need to handle (like wallet funding and supported rails).
If you’re comparing to L402/LSAT (Lightning)
Lightning’s L402 (previously known as LSAT) is a game-changer in 402-based paid APIs, using a combination of macaroons and Lightning invoices. It's been tried and tested in real-world scenarios, like with the Aperture proxy, and it's perfect for those tiny sats-denominated micropayments. Now, x402 takes the 402 concept even further, expanding it across different blockchains and tokens, not to mention focusing on stablecoin transactions and HTTP-first headers.
When product teams are making their choices, they'll often look at the availability of the underlying rails and how ready their organization is. Both pathways ensure that payments keep flowing smoothly. Check it out for more details: (docs.lightning.engineering)
Where this is heading
We're noticing a blend of ideas around:
- You've got this neat 402 response shape that shows up across different chains and tokens.
- Then there’s the agent-first tooling that makes life easier with SDKs that automatically negotiate 402, choose the right rails, and retry when needed. Check it out here: (docs.cdp.coinbase.com).
- Don’t forget about the discovery layers, like the x402 Bazaar, which help agents find and price endpoints. You can read more about it on (coindesk.com).
- Plus, we’re seeing some fresh schemes (like upto, streaming, and Permit2) along with broader token support. Dive into the details here: (docs.cdp.coinbase.com).
Work with 7Block Labs
We've rolled out x402 pilots on Base, Optimism, and Solana for on-demand APIs in data, media, and AI inference. If you’re looking to:
- Set up an edge 402 gateway within your domain,
- Analyze per-request costs and implement precise/up-to-date pricing,
- Connect facilitators without needing to modify keys, and
- Implement Dune-grade analytics linked to txHash,
Get in touch with us--our accelerator packages can have you up and running in just weeks, not months.
References and further reading
- Check out the x402 specs, headers, facilitator API, and some examples over on the Coinbase x402 repo.
- If you want to dive deeper, the Coinbase x402 docs cover everything from HTTP 402 semantics to Embedded Wallets and agent flow. You can find it here.
- Don’t miss the thirdweb x402, which includes server/client setups and supports ERC‑2612 and EIP‑3009, plus options for exact/upto. All the details are on their portal.
- For some Solana action, check out Sol402 (that’s Solana USDC), the 402x dashboard, and a Payin explainer on their site at sol402.app.
- Stay updated with the latest adoption signals and ecosystem news from sources like CoinDesk, Yahoo Finance, and Cointelegraph. You can read more about it here.
- And for the tech-savvy, check out L402/LSAT and Aperture for Lightning-native paid APIs -- all the info you need is on docs.lightning.engineering.
Like what you're reading? Let's build together.
Get a free 30-minute consultation with our engineering team.
Related Posts
ByAUJay
Building 'Private Social Networks' with Onchain Keys
Creating Private Social Networks with Onchain Keys
ByAUJay
Tokenizing Intellectual Property for AI Models: A Simple Guide
## How to Tokenize “Intellectual Property” for AI Models ### Summary: A lot of AI teams struggle to show what their models have been trained on or what licenses they comply with. With the EU AI Act set to kick in by 2026 and new publisher standards like RSL 1.0 making things more transparent, it's becoming more crucial than ever to get this right.
ByAUJay
Creating 'Meme-Utility' Hybrids on Solana: A Simple Guide
## How to Create “Meme‑Utility” Hybrids on Solana Dive into this handy guide on how to blend Solana’s Token‑2022 extensions, Actions/Blinks, Jito bundles, and ZK compression. We’ll show you how to launch a meme coin that’s not just fun but also packs a punch with real utility, slashes distribution costs, and gets you a solid go-to-market strategy.

