Sendy X402 Documentation
Complete guide to integrating and using Sendy X402 micro-payments in your application. All documentation is freely accessible.
Basics
Getting Started with Sendy X402
Learn the fundamentals of Sendy X402 micro-payments. This guide covers the basic concepts and how to integrate Sendy X402 into your application.
Sendy X402 is a revolutionary payment protocol that enables instant micro-transactions on the blockchain. Unlike traditional payment systems that require subscriptions or large upfront costs, Sendy X402 allows users to pay exactly what they use, when they use it.
Key Features:
- Instant payments with no intermediaries
- Support for multiple blockchains including BNB Chain
- Sub-cent transaction costs
- Developer-friendly API
- Secure wallet integration
Getting started is simple:
1. Connect your MetaMask wallet
2. Fund your account with BNB
3. Start making micro-payments
4. Track all transactions in real-time
The Sendy X402 protocol is designed to be developer-friendly and user-centric. Whether you're building a content platform, API service, or any application that requires per-use payments, Sendy X402 provides the infrastructure you need.
Development
Integration Guide
Step-by-step guide to integrate Sendy X402 payments into your application. Learn how to implement payment endpoints and handle transactions.
Integration Overview:
Sendy X402 provides a simple REST API for handling payments. Here's what you need to know:
API Endpoints:
- POST /api/payment/process - Initiate a payment
- POST /api/payment/verify - Verify payment completion
- GET /api/content/[id] - Fetch protected content
Implementation Steps:
1. Setup Your Environment
- Install the Sendy X402 SDK
- Configure your API keys
- Set up environment variables
2. Create Payment Endpoints
- Define your pricing structure
- Implement payment verification
- Handle transaction callbacks
3. Protect Your Content
- Add payment checks to your routes
- Return HTTP 402 for unpaid access
- Implement content delivery after payment
4. Frontend Integration
- Add MetaMask connection
- Implement payment UI
- Handle transaction confirmation
Example Code:
```javascript
const response = await fetch('/api/payment/process', {
method: 'POST',
body: JSON.stringify({
amount: 0.01,
currency: 'BNB',
contentId: 'article-1'
})
})
```
Best Practices:
- Always verify payments server-side
- Implement proper error handling
- Use HTTPS for all transactions
- Store transaction history for auditing
Security
Security Best Practices
Essential security guidelines for implementing Sendy X402 payments. Protect your users and your platform with these proven practices.
Security is paramount when handling blockchain transactions. Follow these guidelines to ensure your implementation is secure:
Wallet Security:
- Never store private keys on your server
- Always use hardware wallets for large amounts
- Implement multi-signature wallets for critical operations
- Educate users about phishing attacks
Transaction Security:
- Verify all transactions server-side
- Implement rate limiting on payment endpoints
- Use nonces to prevent replay attacks
- Monitor for suspicious activity
Smart Contract Security:
- Audit all smart contracts before deployment
- Use established libraries and patterns
- Implement emergency pause mechanisms
- Test thoroughly on testnet first
User Protection:
- Display clear transaction confirmations
- Show gas fees before transactions
- Implement transaction timeouts
- Provide transaction history and receipts
Compliance:
- Follow local regulations for payments
- Implement KYC/AML if required
- Maintain audit logs
- Report suspicious transactions
Common Vulnerabilities to Avoid:
1. Front-running attacks
2. Reentrancy vulnerabilities
3. Integer overflow/underflow
4. Unchecked external calls
5. Improper access controls
Testing:
- Use testnet for development
- Implement comprehensive test coverage
- Perform security audits
- Monitor production for anomalies
Advanced
Advanced Payment Flows
Explore advanced payment patterns and workflows. Learn how to implement complex payment scenarios and optimize for user experience.
Advanced Payment Patterns:
1. Subscription-like Recurring Payments
- Implement auto-renewal mechanisms
- Handle failed payment retries
- Provide subscription management UI
- Track subscription status
2. Tiered Pricing
- Implement different price tiers
- Handle tier upgrades/downgrades
- Prorate charges appropriately
- Manage tier-specific features
3. Batch Payments
- Process multiple payments efficiently
- Implement batch verification
- Handle partial failures
- Optimize gas costs
4. Conditional Payments
- Pay based on usage metrics
- Implement dynamic pricing
- Handle overage charges
- Provide usage dashboards
5. Escrow Payments
- Hold funds in escrow
- Implement dispute resolution
- Release funds on conditions
- Handle refunds
Optimization Strategies:
Gas Optimization:
- Batch transactions when possible
- Use layer 2 solutions for high volume
- Implement payment channels
- Cache frequently accessed data
User Experience:
- Implement one-click payments
- Show payment history
- Provide payment receipts
- Enable payment scheduling
Monitoring and Analytics:
- Track payment success rates
- Monitor transaction costs
- Analyze user payment patterns
- Implement alerting for anomalies
Example: Tiered Pricing Implementation
```javascript
const tiers = {
basic: { price: 0.01, features: ['read'] },
pro: { price: 0.05, features: ['read', 'download'] },
enterprise: { price: 0.10, features: ['read', 'download', 'api'] }
}
async function processPayment(userId, tier) {
const tierConfig = tiers[tier]
// Process payment
// Grant access to features
}
```
Reference
API Reference
Complete API reference for Sendy X402 payment endpoints. Detailed documentation of all available methods and parameters.
Payment Processing API
POST /api/payment/process
Initiates a payment transaction.
Request Body:
{
"amount": 0.01,
"currency": "BNB",
"contentId": "article-1",
"walletAddress": "0x...",
"metadata": {}
}
Response:
{
"transactionId": "tx_123",
"status": "pending",
"amount": 0.01,
"currency": "BNB",
"timestamp": 1234567890
}
Payment Verification API
POST /api/payment/verify
Verifies payment completion.
Request Body:
{
"transactionId": "tx_123",
"walletAddress": "0x..."
}
Response:
{
"verified": true,
"status": "confirmed",
"blockNumber": 12345678,
"gasUsed": 21000
}
Content Retrieval API
GET /api/content/[id]
Retrieves protected content.
Query Parameters:
- walletAddress: User's wallet address
- transactionId: Payment transaction ID
Response (Paid):
{
"id": "article-1",
"title": "Article Title",
"content": "Full article content...",
"accessGranted": true
}
Response (Unpaid - HTTP 402):
{
"status": 402,
"message": "Payment Required",
"amount": 0.01,
"currency": "BNB",
"walletAddress": "0x..."
}
Error Responses
400 Bad Request
Invalid parameters or malformed request
401 Unauthorized
Missing or invalid authentication
402 Payment Required
Payment needed to access resource
500 Internal Server Error
Server-side error occurred
Rate Limiting:
- 100 requests per minute per IP
- 1000 requests per hour per wallet
- Burst limit: 10 requests per second
Support
Troubleshooting Guide
Common issues and solutions for Sendy X402 integration. Find answers to frequently encountered problems and how to resolve them.
Common Issues and Solutions
Issue: MetaMask Connection Fails
Solution:
1. Ensure MetaMask is installed and enabled
2. Check that you're on the correct network
3. Try refreshing the page
4. Clear browser cache and cookies
5. Restart MetaMask extension
Issue: Payment Transaction Pending
Solution:
1. Check network congestion
2. Verify sufficient gas fees
3. Wait for network confirmation
4. Check transaction on block explorer
5. Contact support if stuck for >1 hour
Issue: Insufficient Balance
Solution:
1. Check wallet balance
2. Ensure BNB is on correct network
3. Bridge tokens if on wrong chain
4. Purchase more BNB from exchange
5. Use testnet for development
Issue: Content Not Unlocking After Payment
Solution:
1. Verify transaction confirmation
2. Check transaction ID in response
3. Clear browser cache
4. Try refreshing page
5. Check browser console for errors
Issue: High Gas Fees
Solution:
1. Use layer 2 networks
2. Batch multiple transactions
3. Wait for lower network congestion
4. Use payment channels
5. Implement gas optimization
Debugging Tips:
Enable Debug Mode:
```javascript
localStorage.setItem('sendy_x402_debug', 'true')
```
Check Transaction Status:
- Use block explorer (BscScan)
- Verify transaction hash
- Check gas used vs gas limit
- Monitor pending transactions
Browser Console:
- Check for JavaScript errors
- Monitor network requests
- Verify API responses
- Track state changes
Getting Help:
- Check documentation
- Review error messages
- Search GitHub issues
- Contact support team
- Join community channels
Ready to integrate Sendy X402?
Start building with our payment protocol today.