Python
Complete examples for accepting x402 payments with Yuzu402 using Python.
Installation
pip install requests python-dotenv websocket-client
# For async support:
pip install aiohttp websocketsBasic Payment Verification
Verify a Payment
import requests
import os
from dotenv import load_dotenv
load_dotenv()
def verify_payment(payment_proof: str, amount: int, recipient: str) -> dict:
"""Verify an x402 payment using Yuzu402"""
url = 'https://api.yuzu402.dev/v1/payments/verify'
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {os.getenv("API_KEY")}'
}
payload = {
'payment_proof': payment_proof,
'amount': amount,
'recipient': recipient
}
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
data = response.json()
if data['verified']:
print(f'✅ Payment verified!')
print(f'Transaction ID: {data["transaction_id"]}')
print(f'Amount: {data["amount"]}')
else:
print('❌ Payment invalid')
return data
except requests.exceptions.RequestException as e:
print(f'Error verifying payment: {e}')
raise
# Usage
result = verify_payment(
payment_proof='BASE64_ENCODED_PAYMENT_PROOF',
amount=1000000,
recipient='YOUR_WALLET_ADDRESS'
)Flask Integration
Protect an API Endpoint
Payment Middleware
FastAPI Integration
Modern Async API
WebSocket for Real-Time Notifications
Basic WebSocket Connection
Async WebSocket with websockets
Error Handling
Robust Error Handling with Retry
Django Integration
Django View with Payment Protection
Complete Example: Payment-Protected API
Async/Await Examples
Async Payment Verification
Best Practices
Environment Variables: Always store API keys in environment variables
Error Handling: Implement retry logic for network errors and rate limits
Logging: Log all payment verifications for debugging and reconciliation
Validation: Always validate payment amounts match expectations
Security: Never expose API keys in client-side code
Caching: Cache verified payments to avoid redundant verifications
Testing: Test with small amounts before going live
Next Steps
See JavaScript examples for JavaScript/TypeScript integration
Check out the API Reference for all endpoints
Read about error handling best practices
Last updated

