x402 AI Inference Example
A fully working example of charging for AI inference with x402
Accept x402 payments in your APIs using any x402-compatible client. Your server can verify and settle payments using thirdweb's facilitator service or any custom facilitator.
The x402 protocol follows this flow:

The thirdweb x402 client/server stack supports two payment schemes: exact and upto.
exact - The client pays the exact amount specified in the payment requirements.upto - The client pays any amount up to the specified maximum amount.By default, the payment scheme is exact. You can specify the payment scheme in the settlePayment() or verifyPayment() arguments.
Use settlePayment() to verify and settle the payment in one step. This is the default and simplest approach:
With the upto payment scheme, you can charge only what the client actually uses, and can also settle multiple times up to the authorized maximum amount. Use verifyPayment() first to verify the payment is valid for the maximum amount, do the work, then settlePayment():
This is great for AI apis that need to charge based on the token usage for example. For a fully working example check out this x402 ai inference example.
Here's a high level example of how to use the upto payment scheme with a dynamic price based on the token usage. First we verify the payment is valid for the max payable amount and then settle the payment based on the actual usage.
You can call verifyPayment() and settlePayment() multiple times using the same paymentData, as long as its still valid. verifyPayment() will check that:
If any of these checks fail, verifyPayment() will return a 402 response requiring a new payment authorization.
wrapFetchWithPayment() and useFetchWithPayment() will automatically handle the caching and re-use of the payment data for you, so you don't need to have any additional state or storage on the backend.
You can configure the expiration of the payment signature in the routeConfig parameter of the settlePayment() or verifyPayment() functions.
You can specify prices in multiple ways:
This will default to using USDC on the specified network.
You can use any ERC20 token that supports the ERC-2612 permit or ERC-3009 sign with authorization.
Simply pass the amount in base units and the token address.
Payments in native tokens are not currently supported.
Protect individual API endpoints with x402 payments:
Protect multiple endpoints with a shared middleware: