Skip to content

Commit f0fac5a

Browse files
committed
added explanation to x402 pages
1 parent a24038f commit f0fac5a

File tree

1 file changed

+233
-8
lines changed
  • apps/portal/src/app/payments/x402

1 file changed

+233
-8
lines changed

apps/portal/src/app/payments/x402/page.mdx

Lines changed: 233 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,110 @@ Implement paid API calls using the x402 protocol. Every request is paid for by t
1212
href="https://playground.thirdweb.com/payments/x402"
1313
/>
1414

15-
## Client Side
15+
## Introduction & Core Concepts
16+
17+
The **x402 payment protocol** enables micropayments for API access, allowing developers to monetize their APIs with per-request pricing. Instead of traditional subscription models or API keys, users pay small amounts (typically $0.01-$0.10) for each API call using cryptocurrency.
18+
19+
### How it works
20+
When a user makes a request to a paid API:
21+
1. The API returns a `402 Payment Required` response with payment details
22+
2. The user's wallet signs a payment authorization
23+
3. The request is retried with a payment header
24+
4. The API validates the payment and returns the requested data
25+
5. The payment is settled on-chain to the API provider
26+
27+
### Benefits
28+
- **No subscriptions**: Users only pay for what they use
29+
- **Global access**: Works with any web3 wallet worldwide
30+
- **Instant monetization**: Start earning from your APIs immediately
31+
- **Micropayment friendly**: Perfect for small, frequent transactions
32+
33+
## X402 Protocol Fundamentals
34+
35+
### Payment Flow
36+
The x402 protocol follows a simple request-retry pattern:
37+
38+
1. **Initial request**: Client makes normal API call
39+
2. **402 response**: Server responds with payment requirements if payment needed
40+
3. **Payment authorization**: User signs payment message in their wallet
41+
4. **Retry with payment**: Request is retried with payment header
42+
5. **Content delivery**: Server validates payment and returns content
43+
44+
### Facilitators
45+
A **facilitator** is a service that handles payment verification and settlement for x402 payments. Think of it as the payment processor that:
46+
- Validates payment signatures from users
47+
- Executes on-chain transfers to collect payments
48+
- Provides payment infrastructure to API providers
49+
50+
### Payment Schemes
51+
Currently, x402 supports:
52+
- **"exact"**: Fixed price payments (e.g., exactly $0.01 USDC)
53+
- Additional schemes (percentage-based, auction-style) are planned for future versions
54+
55+
### Security Model
56+
- **Signature-based**: Users sign payment authorizations, no direct token transfers from client
57+
- **Replay protection**: Each payment includes unique identifiers to prevent reuse
58+
- **Amount validation**: Clients can set maximum payment limits for protection
59+
60+
## Supported Payment Networks & Tokens
61+
62+
### Supported Networks
63+
thirdweb's x402 facilitator currently supports payments on:
64+
- **Base** (mainnet)
65+
- **Base Sepolia** (testnet)
66+
- **Avalanche** (C-Chain)
67+
- **Avalanche Fuji** (testnet)
68+
- **IoTeX** (mainnet)
69+
- **Sei** (mainnet)
70+
- **Sei Testnet**
71+
72+
### Payment Tokens
73+
- **Primary**: USDC on all supported networks
74+
- **Stablecoins**: Other USD-pegged tokens as available per network
75+
- **Network selection**: Client and server automatically negotiate the best payment network
76+
77+
### Chain Switching
78+
If your wallet is connected to a different network than required for payment, the client will automatically:
79+
1. Detect the payment network requirement
80+
2. Prompt you to switch to the correct network
81+
3. Proceed with payment once switched
82+
83+
## thirdweb as X402 Facilitator
84+
85+
thirdweb provides a complete x402 facilitator service that handles all the payment infrastructure for your APIs.
86+
87+
### What thirdweb Provides
88+
- **Payment verification**: Validates user payment signatures and wallet balances
89+
- **Multi-chain settlement**: Supports payments across multiple blockchain networks
90+
- **Server wallet integration**: Uses your configured server wallet to receive payments
91+
- **Gasless transactions**: Handles all gas costs for payment settlement
92+
- **Automatic execution**: Payments are settled without manual intervention
93+
94+
### Server Wallet Concept
95+
Your **server wallet** is the blockchain address where all API payments are collected. When users pay for API access:
96+
1. They sign a payment authorization to your server wallet address
97+
2. thirdweb validates the payment signature and user's token balance
98+
3. thirdweb executes the token transfer to your server wallet
99+
4. You receive the payment automatically without gas costs
100+
101+
### Integration Benefits
102+
- **Simple setup**: Just provide your server wallet address and thirdweb secret key
103+
- **No blockchain complexity**: thirdweb handles all on-chain interactions
104+
- **Reliable settlement**: Payments are automatically executed when valid
105+
- **Multi-chain support**: Accept payments on multiple networks simultaneously
106+
107+
## Client-Side Implementation
108+
109+
### Basic Usage
16110

17111
`wrapFetchWithPayment` wraps the native fetch API to automatically handle `402 Payment Required` responses from any API call. It will:
18112
1. Make the initial request
19113
2. If a 402 response is received, parse the payment requirements
20114
3. Verify the payment amount is within the allowed maximum
21-
4. Sign a payment authorization
115+
4. Sign a payment authorization
22116
5. Create a payment header using the provided wallet signature
23117
6. Retry the request with the payment header
24118

25-
Here's an example:
26-
27119
```typescript
28120
import { wrapFetchWithPayment } from "thirdweb/x402";
29121
import { createThirdwebClient } from "thirdweb";
@@ -39,9 +131,82 @@ const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet);
39131
const response = await fetchWithPay('https://api.example.com/paid-endpoint');
40132
```
41133

42-
## Server Side
134+
### Advanced Configuration
135+
136+
You can configure payment limits and behavior:
137+
138+
```typescript
139+
// Set maximum payment amount (default: 1 USDC)
140+
const fetchWithPay = wrapFetchWithPayment(
141+
fetch,
142+
client,
143+
wallet,
144+
BigInt(5 * 10 ** 6) // Maximum 5 USDC
145+
);
146+
```
147+
148+
### Error Handling
149+
150+
Handle different payment scenarios:
151+
152+
```typescript
153+
try {
154+
const response = await fetchWithPay('/api/paid-endpoint');
155+
const data = await response.json();
156+
} catch (error) {
157+
if (error.message.includes("Payment amount exceeds maximum")) {
158+
// Handle payment too expensive
159+
console.error("Payment required exceeds your limit");
160+
} else if (error.message.includes("Wallet not connected")) {
161+
// Handle wallet connection issues
162+
console.error("Please connect your wallet");
163+
} else if (error.message.includes("Payment already attempted")) {
164+
// Handle retry scenarios
165+
console.error("Payment was already processed");
166+
} else {
167+
// Handle other errors (user rejected, insufficient funds, etc.)
168+
console.error("Payment failed:", error.message);
169+
}
170+
}
171+
```
172+
173+
### React Integration
174+
175+
Use with React hooks for better UX:
176+
177+
```typescript
178+
import { useActiveWallet } from "thirdweb/react";
179+
import { useMutation } from "@tanstack/react-query";
180+
181+
function PayableAPICall() {
182+
const wallet = useActiveWallet();
43183

44-
To make your API calls payable, you can use any x402 middleware library like x402-hono, x402-next, x402-express, etc.
184+
const paidApiCall = useMutation({
185+
mutationFn: async () => {
186+
if (!wallet) throw new Error("Wallet not connected");
187+
188+
const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet);
189+
const response = await fetchWithPay('/api/paid-endpoint');
190+
return response.json();
191+
},
192+
});
193+
194+
return (
195+
<button
196+
onClick={() => paidApiCall.mutate()}
197+
disabled={!wallet || paidApiCall.isPending}
198+
>
199+
{paidApiCall.isPending ? "Processing Payment..." : "Call Paid API"}
200+
</button>
201+
);
202+
}
203+
```
204+
205+
## Server-Side Implementation
206+
207+
### Basic Middleware Setup
208+
209+
To make your API calls payable, you can use any x402 middleware library like `x402-hono`, `x402-next`, `x402-express`, etc.
45210

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

@@ -57,7 +222,7 @@ const client = createThirdwebClient({
57222
});
58223

59224
export const middleware = paymentMiddleware(
60-
"0xdd99b75f095d0c4d5112aCe938e4e6ed962fb024",
225+
"0xdd99b75f095d0c4d5112aCe938e4e6ed962fb024", // Your server wallet address
61226
{
62227
"/api/paid-endpoint": {
63228
price: "$0.01",
@@ -69,7 +234,7 @@ export const middleware = paymentMiddleware(
69234
},
70235
facilitator({
71236
client,
72-
serverWalletAddress: "0x1234567890123456789012345678901234567890",
237+
serverWalletAddress: process.env.SERVER_WALLET_ADDRESS,
73238
}),
74239
);
75240

@@ -78,3 +243,63 @@ export const config = {
78243
matcher: ["/api/paid-endpoint"],
79244
};
80245
```
246+
247+
### Facilitator Configuration Deep-Dive
248+
249+
The `facilitator` function accepts several configuration options:
250+
251+
```typescript
252+
facilitator({
253+
client: thirdwebClient, // Your thirdweb client with secret key
254+
serverWalletAddress: "0x..." // Where payments are collected
255+
})
256+
```
257+
258+
### Multiple Endpoint Configuration
259+
260+
Configure different pricing for multiple API endpoints:
261+
262+
```typescript
263+
export const middleware = paymentMiddleware(
264+
serverWalletAddress,
265+
{
266+
"/api/basic-data": {
267+
price: "$0.01",
268+
network: "base-sepolia",
269+
config: { description: "Basic data access" },
270+
},
271+
"/api/premium-analytics": {
272+
price: "$0.05",
273+
network: "base", // Use mainnet for higher-value endpoints
274+
config: { description: "Premium analytics data" },
275+
},
276+
"/api/ai-processing": {
277+
price: "$0.10",
278+
network: "base",
279+
config: { description: "AI-powered data processing" },
280+
},
281+
},
282+
facilitator({ client, serverWalletAddress }),
283+
);
284+
285+
export const config = {
286+
matcher: ["/api/basic-data", "/api/premium-analytics", "/api/ai-processing"],
287+
};
288+
```
289+
290+
### Environment Variables
291+
292+
Set up the required environment variables:
293+
294+
```bash
295+
# .env.local
296+
THIRDWEB_SECRET_KEY=your_thirdweb_secret_key
297+
SERVER_WALLET_ADDRESS=0x1234567890123456789012345678901234567890
298+
```
299+
300+
### Security Considerations
301+
302+
- **Never expose your secret key**: Keep `THIRDWEB_SECRET_KEY` in server environment only
303+
- **Server wallet security**: Use a dedicated wallet for collecting payments, separate from development wallets
304+
- **Network selection**: Use testnets for development, mainnets for production
305+
- **Price validation**: Set appropriate prices to prevent abuse while maintaining accessibility

0 commit comments

Comments
 (0)