Payments

x402 payments

Implement paid API calls using the x402 protocol. Every request is paid for by the user with a micro payment onchain.

React

x402 Playground

Try out a x402 payment in our live playground

Client Side

wrapFetchWithPayment wraps the native fetch API to automatically handle 402 Payment Required responses from any API call. It will:

  • Make the initial request
  • If a 402 response is received, parse the payment requirements
  • Verify the payment amount is within the allowed maximum
  • Sign a payment authorization
  • Create a payment header using the provided wallet signature
  • Retry the request with the payment header

Here's an example:

import { wrapFetchWithPayment } from "thirdweb/x402";
import { createThirdwebClient } from "thirdweb";
import { createWallet } from "thirdweb/wallets";
const client = createThirdwebClient({ clientId: "your-client-id" });
const wallet = createWallet("io.metamask"); // or any other wallet
await wallet.connect({ client });
const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet);
// Make a request that may require payment
const response = await fetchWithPay(
"https://api.example.com/paid-endpoint",
);

Server Side

To make your API calls payable, you can use any x402 middleware library like x402-hono, x402-next, x402-express, etc.

Then, use the facilitator configuratino function settle transactions with your thirdweb server wallet gaslessly and pass it to the middleware.

Here's an example with Next.js:

import { createThirdwebClient } from "thirdweb";
import { facilitator } from "thirdweb/x402";
import { paymentMiddleware } from "x402-next";
const client = createThirdwebClient({
secretKey: process.env.THIRDWEB_SECRET_KEY as string,
});
export const middleware = paymentMiddleware(
"0xdd99b75f095d0c4d5112aCe938e4e6ed962fb024",
{
"/api/paid-endpoint": {
price: "$0.01",
network: "base-sepolia",
config: {
description: "Access to paid content",
},
},
},
facilitator({
client,
serverWalletAddress: "0x1234567890123456789012345678901234567890",
}),
);
// Configure which paths the middleware should run on
export const config = {
matcher: ["/api/paid-endpoint"],
};