This example demonstrates integration using thirdweb’s x402 payment wrapper API. Perfect for applications already using the thirdweb ecosystem.
Overview
Integrate Snack Money payments using thirdweb’s x402 fetch wrapper, which handles payment negotiation through thirdweb’s managed infrastructure.
Features
- ✅ Base network support
- ✅ Managed infrastructure - thirdweb handles x402 flow
- ✅ x402 wrapper via API - Automatic payment negotiation
- ✅ Server-side wallet - Secure key management
- ✅ thirdweb ecosystem - Works with other thirdweb tools
Prerequisites
- Node.js 18+
- thirdweb account (Sign up)
- thirdweb Secret Key
- thirdweb server wallet with USDC balance on Base
Installation
Quick Start
1. Get thirdweb Credentials
- Visit thirdweb Dashboard
- Create a new project
- Get your Client ID and Secret Key
- Create a wallet and fund with USDC
2. Set Up Environment
Create a .env file:
THIRDWEB_SECRET_KEY=your_secret_key
WALLET_ADDRESS=your_thirdweb_server_wallet_address
RECEIVER=your_x_username
AMOUNT=0.01
Important: The WALLET_ADDRESS should be your thirdweb server wallet address that has USDC on Base network.
3. Implement Payment
Create base-send.ts:
import { config } from "dotenv";
config();
async function sendPayment() {
const receiver = process.env.RECEIVER as string;
const amount = parseFloat(process.env.AMOUNT || "0.01");
const secretKey = process.env.THIRDWEB_SECRET_KEY as string;
const walletAddress = process.env.WALLET_ADDRESS as string;
if (!receiver || !secretKey || !walletAddress) {
console.error("Missing required environment variables: RECEIVER, THIRDWEB_SECRET_KEY, and WALLET_ADDRESS");
process.exit(1);
}
console.log("🚀 Starting Snack Money payment with thirdweb\n");
console.log(`📍 Wallet Address: ${walletAddress}`);
console.log(`💡 Check balance: https://basescan.org/address/${walletAddress}\n`);
const url = "https://api.snack.money/payments/x/pay";
const encodedUrl = encodeURIComponent(url);
const usdcAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; // USDC on Base
const chainId = 8453; // Base network
const maxValue = 1000000; // 1 USDC in smallest units (6 decimals)
console.log(`💸 Sending ${amount} USDC to @${receiver} on X...\n`);
// Use thirdweb's x402 fetch wrapper
const response = await fetch(
`https://api.thirdweb.com/v1/payments/x402/fetch?from=${walletAddress}&url=${encodedUrl}&method=POST&chainId=${chainId}&maxValue=${maxValue}&asset=${usdcAddress}`,
{
method: "POST",
headers: {
"x-secret-key": secretKey,
"Content-Type": "application/json"
},
body: JSON.stringify({
amount,
currency: "USDC",
receiver,
description: "Payment via thirdweb x402 wrapper"
})
}
);
const data = await response.json();
if (response.status === 200) {
console.log("✅ Payment successful!");
console.log("\n📊 Response:", JSON.stringify(data, null, 2));
} else {
console.error("❌ Payment failed");
console.error("Status:", response.status);
console.error("Response:", JSON.stringify(data, null, 2));
}
}
sendPayment();
4. Run the Example
npm run base
# or
npx tsx base-send.ts
Expected Output
🚀 Starting Snack Money payment with thirdweb
✅ Initialized thirdweb client
💸 Sending 0.01 USDC to @username on X...
✅ Payment successful!
📊 Response: {
"code": 200,
"msg": "0.01 USDC sent successfully",
"data": {
"txn_id": "0xabc...def",
"amount": 0.01,
"receipt": "https://snack.money/x/username?txn=..."
}
}
How It Works
- Initialize thirdweb: Create client with API credentials
- Create Wallet: Load wallet from private key
- Convert Account: Convert to viem format for x402
- Wrap Axios: Add payment interceptor
- Send Payment: Make payment request
Why thirdweb?
Benefits
- Managed Infrastructure: thirdweb handles blockchain complexity
- Ecosystem Integration: Works with other thirdweb services
- Developer Experience: Simple, consistent APIs
- Multi-Chain Support: Easy to extend to other chains
Best For
- Apps already using thirdweb
- Need thirdweb ecosystem features
- Want managed infrastructure
- Building multi-chain apps
// X (Twitter)
await api.post("/payments/x/pay", {
amount: 0.01,
receiver: "username",
currency: "USDC"
});
// Farcaster
await api.post("/payments/farcaster/pay", {
amount: 0.5,
receiver: "username",
currency: "USDC"
});
// GitHub
await api.post("/payments/github/pay", {
amount: 1.0,
receiver: "username",
currency: "USDC"
});
thirdweb Features
Using thirdweb Wallets
import { inAppWallet } from "thirdweb/wallets";
// Create in-app wallet for users
const wallet = inAppWallet();
await wallet.connect({
client,
strategy: "email",
email: "[email protected]"
});
Smart Wallets
import { smartWallet } from "thirdweb/wallets";
const wallet = smartWallet({
chain: base,
gasless: true
});
Error Handling
try {
const response = await api.post("/payments/x/pay", {
amount: 0.01,
currency: "USDC",
receiver: "username"
});
console.log("Success:", response.data);
} catch (error) {
console.error("Payment failed:", error);
}
Full Example Repository
View on GitHub →
Includes:
- Complete implementation
- thirdweb configuration
- Environment setup
- Detailed README
Next Steps
Dependencies
{
"dependencies": {
"thirdweb": "^5.0.0",
"axios": "^1.6.0",
"x402-axios": "latest",
"viem": "^2.0.0"
}
}
Learn More