x402 Payment Integration Guide
Overview
The x402 protocol enables crypto payment requirements for API endpoints using the Coinbase Developer Platform (CDP). This guide covers how to integrate x402 payments into your ElizaOS deployment.What is x402?
x402 is a payment protocol that allows you to monetize your API endpoints by requiring crypto payments (USDC) for each request. It works seamlessly with both testnet (for development) and mainnet (for production).Key Benefits
- Monetize APIs: Charge per API call in USDC
- Blockchain-native: Payments are verified on-chain
- Easy integration: Simple environment variable configuration
- Flexible pricing: Set different prices per endpoint
- Testnet support: Test with Base Sepolia before going live
Quick Start
1. Get Your Wallet Address
You need an EVM-compatible wallet address to receive payments. This should be a Base or Base Sepolia address. Important: Your wallet address must:- Start with
0x - Be exactly 42 characters long
- Contain only hexadecimal characters (0-9, a-f, A-F)
0x1234567890abcdef1234567890abcdef12345678
2. Configure Environment Variables
Add these variables to your.env file:
Required (when enabling x402)
Optional Configuration
3. Testnet Setup (Recommended First)
Start with Base Sepolia testnet to test your integration:4. Mainnet Setup
For production, you’ll need CDP API credentials:Get CDP Credentials
- Sign up at Coinbase Developer Platform
- Create an API key
- Save your API Key ID and Secret
Configure Mainnet
Authentication Modes
The x402 middleware supports multiple authentication configurations:Mode 1: x402 Only
Users pay with crypto, no API key required.Mode 2: API Key Only
Traditional API key authentication, no payment required.Mode 3: Both x402 + API Key
Requires BOTH valid API key AND payment.Mode 4: Open Access
No authentication required (not recommended for production).Jobs API Integration
The Jobs API (POST /api/messaging/jobs) and status endpoint (GET /api/messaging/jobs/:jobId) both use x402 middleware for consistent authentication.
Per-Endpoint Configuration
You can customize pricing and metadata per endpoint:Making Payments as a Client
When x402 is enabled, clients must include anX-PAYMENT header with payment proof.
Using x402 SDK (JavaScript/TypeScript)
Example: Complete Client Flow
Security Best Practices
1. Protect Your Wallet Private Keys
Never commit private keys to version control:2. Use Different Wallets for Test/Prod
Keep separate wallets for testnet and mainnet:3. Rotate CDP API Keys Regularly
Set up key rotation for your CDP credentials:4. Monitor Payment Flow
Track payments and detect anomalies:Troubleshooting
Error: “Invalid or missing X-PAYMENT”
Cause: Payment header is missing or invalid Solution: Ensure client is sending valid payment proof inX-PAYMENT header
Error: “X402_WALLET_ADDRESS must start with 0x”
Cause: Wallet address format is invalid Solution: Verify your wallet address:- Starts with
0x - Is exactly 42 characters
- Contains only hex characters (0-9, a-f, A-F)
Error: “Mainnet facilitator requires CDP_API_KEY_ID”
Cause: Mainnet is enabled but CDP credentials are missing Solution: Set bothCDP_API_KEY_ID and CDP_API_KEY_SECRET when using mainnet
Payment Not Received
Check:- Wallet address is correct
- Network matches (testnet vs mainnet)
- Client is using correct facilitator URL
- USDC is available in client wallet
Testing
Unit Tests
Test your x402 configuration:Integration Tests
Test the complete payment flow:Production Deployment with Nginx
Why Use Nginx?
Nginx acts as a reverse proxy to provide:- SSL/TLS termination: Secure HTTPS connections
- Rate limiting: Prevent abuse and DDoS attacks
- Load balancing: Distribute traffic across multiple instances
- Static file serving: Offload static content from your API
- Security headers: Add security layers
- Access control: Restrict access by IP, geography, etc.
Step 1: Install Nginx
Ubuntu/Debian
CentOS/RHEL
macOS
Step 2: Basic Nginx Configuration
Create a new configuration file for your ElizaOS API:Step 3: SSL/TLS with Let’s Encrypt
Install Certbot
Obtain SSL Certificate
- Enter your email
- Agree to Terms of Service
- Choose whether to redirect HTTP to HTTPS (recommended: yes)
Auto-renewal
Certbot automatically sets up renewal. Test it:Step 4: Rate Limiting
Protect your API from abuse with rate limiting:Step 5: DDoS Protection
Enable Connection Limits
Install Fail2ban
Automatically ban IPs with suspicious behavior:Step 6: Geographic Restrictions (Optional)
Restrict access by country using GeoIP:Step 7: Monitoring and Logging
Enhanced Logging Format
Log Rotation
Monitor with GoAccess (Real-time)
https://api.yourdomain.com/report.html
Step 8: Advanced Security
IP Whitelist for Admin Endpoints
Hide Nginx Version
Add WAF (Web Application Firewall)
Install ModSecurity:SecRuleEngine DetectionOnly to SecRuleEngine On
Request Body Validation
Step 9: High Availability Setup
Multiple ElizaOS Instances
Run Multiple Instances with PM2
Step 10: Production Deployment Checklist
Before going live, verify:Security Checklist
- SSL/TLS certificate installed and valid
- HTTP to HTTPS redirect enabled
- Security headers configured
- Rate limiting enabled on all endpoints
- Fail2ban configured and running
- Admin endpoints IP-whitelisted
- Nginx version hidden (
server_tokens off) - WAF/ModSecurity enabled (optional but recommended)
- Log rotation configured
- Firewall rules set (only ports 80, 443 open)
x402 Configuration Checklist
-
X402_ENABLED=truefor production -
X402_WALLET_ADDRESSset to mainnet address - Wallet address validated (starts with 0x, 42 chars, hex only)
-
X402_USE_MAINNET=trueset -
CDP_API_KEY_IDandCDP_API_KEY_SECRETconfigured -
X402_NETWORK=base(not base-sepolia) - Pricing configured appropriately
- Endpoint metadata added for API discovery
Environment Checklist
-
.envfile secured (not committed to git) - Secrets stored in vault/secrets manager
- Database backups configured
- Monitoring and alerting set up
- Error tracking configured (Sentry, etc.)
- Log aggregation set up (ELK, Datadog, etc.)
Testing Checklist
- Load testing completed
- DDoS protection tested
- SSL certificate verified (SSL Labs test)
- API endpoints tested with x402 payments
- Failover tested (if using multiple instances)
- Backup and restore tested
Complete Production Nginx Configuration
Here’s a complete, production-ready configuration:Monitoring Production
Setup Prometheus + Grafana
Monitor Nginx metrics:Alerting
Set up alerts for:- High error rates (> 5%)
- Response time > 2s
- Rate limit hits
- SSL certificate expiry (< 30 days)
- Disk space (> 80%)
Resources
- Coinbase Developer Platform - x402 Quickstart
- x402 Protocol Specification
- Base Sepolia Testnet Faucet
- ElizaOS Jobs API Documentation
- Nginx Official Documentation
- Let’s Encrypt Documentation
- Mozilla SSL Configuration Generator
- SSL Labs Server Test
Support
For issues and questions:- GitHub Issues: elizaOS/eliza
- Discord: ElizaOS Community
- Documentation: docs.elizaos.ai

