x402 AI Inference Example
A fully working example of charging an 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:
For dynamic pricing, use verifyPayment() first, do the work, then settlePayment():
This is great for AI apis that need to charge based on the token usage for example. Check out 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 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: