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 websockets

Basic 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

  1. Environment Variables: Always store API keys in environment variables

  2. Error Handling: Implement retry logic for network errors and rate limits

  3. Logging: Log all payment verifications for debugging and reconciliation

  4. Validation: Always validate payment amounts match expectations

  5. Security: Never expose API keys in client-side code

  6. Caching: Cache verified payments to avoid redundant verifications

  7. Testing: Test with small amounts before going live

Next Steps

Last updated