Payments

x402 Payments

x402 is an open-source protocol that turns the dormant HTTP 402 Payment Required status code into a fully-featured, on-chain payment layer for APIs, websites, and autonomous agents.

Learn more about the protocol at x402.org.

React

x402 Playground

Try out x402 payments in our live playground

Client Side

wrapFetchWithPayment wraps the native fetch API to automatically handle 402 Payment Required responses from any x402-compatible API:

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");
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, use the settlePayment function in a middleware or endpoint:

import { createThirdwebClient } from "thirdweb";
import { facilitator, settlePayment } from "thirdweb/x402";
import { arbitrumSepolia } from "thirdweb/chains";
const client = createThirdwebClient({ secretKey: "your-secret-key" });
const thirdwebX402Facilitator = facilitator({
client,
serverWalletAddress: "0xYourWalletAddress",
});
export async function GET(request: Request) {
const paymentData = request.headers.get("x-payment");
const result = await settlePayment({
resourceUrl: "https://api.example.com/premium-content",
method: "GET",
paymentData,
payTo: "0xYourWalletAddress",
network: arbitrumSepolia,
price: "$0.01",
facilitator: thirdwebX402Facilitator,
routeConfig: {
description: "Access to premium API content",
mimeType: "application/json",
maxTimeoutSeconds: 300,
},
});
if (result.status === 200) {
return Response.json({ data: "premium content" });
} else {
return Response.json(result.responseBody, {
status: result.status,
headers: result.responseHeaders,
});
}
}

Going Further