Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 178 additions & 16 deletions apps/portal/src/app/payments/x402/page.mdx
Original file line number Diff line number Diff line change
@@ -1,29 +1,107 @@
import { ArticleIconCard } from "@doc";
import { ReactIcon } from "@/icons";

# x402 payments
# 402 Gated Payments

Implement paid API calls using the x402 protocol. Every request is paid for by the user with a micro payment onchain.
Implement gated API access with pay-per-request pricing. Users pay small amounts for each API call using cryptocurrency through the HTTP 402 Payment Required protocol.

<ArticleIconCard
title="x402 Playground"
description="Try out a x402 payment in our live playground"
title="402 Payments Playground"
description="Try out a 402 gated payment in our live playground"
icon={ReactIcon}
href="https://playground.thirdweb.com/payments/x402"
/>

## Client Side

`wrapFetchWithPayment` wraps the native fetch API to automatically handle `402 Payment Required` responses from any API call. It will:
## Introduction & Core Concepts

**402 gated payments** enable micropayments for API access using the HTTP 402 Payment Required status code, 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.

### How it works
When a user makes a request to a paid API:
1. The API returns a `402 Payment Required` response with payment details
2. The user's wallet signs a payment authorization
3. The request is retried with a payment header
4. The API validates the payment and returns the requested data
5. The payment is settled on-chain to the API provider

### Benefits
- **No subscriptions**: Users only pay for what they use
- **Global access**: Works with any web3 wallet worldwide
- **Instant monetization**: Start earning from your APIs immediately
- **Micropayment friendly**: Perfect for small, frequent transactions

## 402 Payment Protocol Fundamentals

### Payment Processors
A **payment processor** is a service that handles payment verification and settlement for 402 payments. Think of it as the backend service that:
- Validates payment signatures from users
- Executes on-chain transfers to collect payments
- Provides payment infrastructure to API providers

### Payment Schemes
thirdweb's 402 payment implementation currently supports:
- **"exact"**: Fixed price payments (e.g., exactly $0.01 USDC) - our first supported scheme
- Additional schemes (percentage-based, auction-style, variable pricing) are planned for future versions

## Supported Payment Networks & Tokens

### Supported Networks
thirdweb's 402 payment processor currently supports payments on:
- **Base** (mainnet)
- **Base Sepolia** (testnet)
- **Avalanche** (C-Chain)
- **Avalanche Fuji** (testnet)
- **IoTeX** (mainnet)
- **Sei** (mainnet)
- **Sei Testnet**
- **Solana (coming soon)**
- **Solana Devnet (coming soon)**

### Payment Tokens
- **Primary**: USDC on all supported networks
- **Stablecoins**: Other USD-pegged tokens as available per network
- **Network selection**: Client and server automatically negotiate the best payment network

## thirdweb 402 Payment Components

thirdweb provides a complete 402 payment system with components for both client and server sides, plus backend payment processing infrastructure.

### Client-Side Components
**For app developers integrating payment functionality:**
- **`wrapFetchWithPayment`**: Automatically handles 402 responses and payment flows
- **Wallet integration**: Works with any thirdweb-supported wallet (inapp, MetaMask, WalletConnect, etc.)
- **Payment authorization**: Prompts users to sign payment messages when needed
- **Chain switching**: Automatically switches to the required payment network
- **Error handling**: Manages payment failures, insufficient funds, and user rejections

### Server-Side Components
**For API providers implementing gated endpoints:**
- **Middleware libraries**: Integration with popular frameworks (`x402-next`, `x402-hono`, `x402-express`)
- **Payment verification**: Validates user payment signatures and wallet balances
- **Multi-chain support**: Accepts payments across multiple blockchain networks
- **Automatic settlement**: Executes token transfers to your server wallet
- **Gasless transactions**: thirdweb covers all gas costs for payment processing

### Server Wallet
Your **Server Wallet** is the blockchain address where all API payments are collected:
- **Payment destination**: Users authorize payments to this specific wallet address
- **Multi-network**: Same wallet can receive payments across different supported chains
- **Automatic collection**: thirdweb handles the transfer execution without manual intervention
- **Gasless payments**: Payment transfers are performed in gasless fashion to reduce friction
- **Real-time settlement**: Payments arrive in your wallet immediately after validation

## Client-Side Implementation

### Basic Usage

`wrapFetchWithPayment` wraps the native fetch API to automatically handle `402 Payment Required` responses, implementing thirdweb's "exact" payment scheme. It will:
1. Make the initial request
2. If a 402 response is received, parse the payment requirements
3. Verify the payment amount is within the allowed maximum
4. Sign a payment authorization
4. Sign a payment authorization
5. Create a payment header using the provided wallet signature
6. Retry the request with the payment header

Here's an example:

```typescript
import { wrapFetchWithPayment } from "thirdweb/x402";
import { createThirdwebClient } from "thirdweb";
Expand All @@ -39,11 +117,52 @@ const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet);
const response = await fetchWithPay('https://api.example.com/paid-endpoint');
```

## Server Side
### Advanced Configuration

You can configure payment limits and behavior:

```typescript
// Set maximum payment amount (default: 1 USDC)
const fetchWithPay = wrapFetchWithPayment(
fetch,
client,
wallet,
BigInt(5 * 10 ** 6) // Maximum 5 USDC
);
```

### Error Handling

Handle different payment scenarios:

```typescript
try {
const response = await fetchWithPay('/api/paid-endpoint');
const data = await response.json();
} catch (error) {
if (error.message.includes("Payment amount exceeds maximum")) {
// Handle payment too expensive
console.error("Payment required exceeds your limit");
} else if (error.message.includes("Wallet not connected")) {
// Handle wallet connection issues
console.error("Please connect your wallet");
} else if (error.message.includes("Payment already attempted")) {
// Handle retry scenarios
console.error("Payment was already processed");
} else {
// Handle other errors (user rejected, insufficient funds, etc.)
console.error("Payment failed:", error.message);
}
}
```

## Server-Side Implementation

### Basic Middleware Setup

To make your API calls payable, you can use any x402 middleware library like x402-hono, x402-next, x402-express, etc.
To make your API calls payable, you can use any 402 payment middleware library. thirdweb provides payment processor integration for popular frameworks like `x402-next`, `x402-hono`, `x402-express`, etc.

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

Here's an example with Next.js:

Expand All @@ -57,7 +176,7 @@ const client = createThirdwebClient({
});

export const middleware = paymentMiddleware(
"0xdd99b75f095d0c4d5112aCe938e4e6ed962fb024",
"0xdd99b75f095d0c4d5112aCe938e4e6ed962fb024", // Your server wallet address
{
"/api/paid-endpoint": {
price: "$0.01",
Expand All @@ -69,12 +188,55 @@ export const middleware = paymentMiddleware(
},
facilitator({
client,
serverWalletAddress: "0x1234567890123456789012345678901234567890",
}),
serverWalletAddress: process.env.SERVER_WALLET_ADDRESS,
}), // thirdweb payment processor configuration
);

// Configure which paths the middleware should run on
export const config = {
matcher: ["/api/paid-endpoint"],
};
```

### Payment Processor Configuration Deep-Dive

The `facilitator` function configures thirdweb's payment processor and accepts several options:

```typescript
facilitator({
client: thirdwebClient, // Your thirdweb client with secret key
serverWalletAddress: "0x..." // Where payments are collected
})
```

### Multiple Endpoint Configuration

Configure different pricing for multiple API endpoints:

```typescript
export const middleware = paymentMiddleware(
serverWalletAddress,
{
"/api/basic-data": {
price: "$0.01",
network: "base-sepolia",
config: { description: "Basic data access" },
},
"/api/premium-analytics": {
price: "$0.05",
network: "base", // Use mainnet for higher-value endpoints
config: { description: "Premium analytics data" },
},
"/api/ai-processing": {
price: "$0.10",
network: "base",
config: { description: "AI-powered data processing" },
},
},
facilitator({ client, serverWalletAddress }), // thirdweb payment processor
);

export const config = {
matcher: ["/api/basic-data", "/api/premium-analytics", "/api/ai-processing"],
};
```
Loading