QBitFlow Documentation

    Complete guide to integrating cryptocurrency payments with QBitFlow

    Monitoring Transactions

    QBitFlow provides three ways to monitor transaction status: webhooks, success URLs, and WebSocket connections. Choose the method that best fits your use case.

    Overview

    Webhooks

    Recommended

    Server-to-server notifications. Most reliable method for production use.

    Success URLs

    User Feedback

    Redirect customers after payment. Great for immediate user feedback.

    WebSocket

    Real-time

    Real-time status updates. Use when immediate feedback is critical.

    Method 1: Webhooks (Recommended)

    Reliable Server-to-Server Notifications

    Webhooks are the most reliable way to receive payment notifications. When a transaction is processed, QBitFlow sends a POST request to your webhook URL with the transaction details. This happens regardless of whether the customer closes their browser or loses internet connection.

    Setting Up Webhook Handler

    Webhook Handler Implementation
    Handle webhook notifications from QBitFlow
    from fastapi import FastAPI
    from qbitflow import QBitFlow
    from qbitflow.dto.transaction.session import SessionWebhookResponse
    from qbitflow.dto.transaction.status import TransactionStatusValue
    app = FastAPI()
    client = QBitFlow(api_key="your_api_key")
    @app.post("/webhook")
    def handle_webhook(
    request: Request,
    x_webhook_signature_256: Annotated[str, Header()],
    x_webhook_timestamp: Annotated[str, Header()]
    ):
    """Handle webhook events from QBitFlow."""
    # Read raw request body for signature verification
    body = await request.body()
    # Verify the authenticity of the webhook request
    if not qbitflow_client.webhooks.verify(
    payload=body,
    signature=x_webhook_signature_256,
    timestamp=x_webhook_timestamp
    ):
    print("❌ Invalid webhook signature")
    raise HTTPException(status_code=401, detail="Invalid webhook signature")
    # Parse payload after verification
    try:
    event = SessionWebhookResponse.model_validate_json(body)
    except ValidationError as e:
    print(f"❌ Failed to parse webhook payload: {e}")
    raise HTTPException(status_code=401, detail="Invalid webhook payload")
    # Extract event details
    session_uuid = event.uuid
    transaction_status = event.status.status
    transaction_type = event.status.type
    session = event.session
    print(f"Session UUID: {session_uuid}")
    print(f"Transaction Type: {transaction_type.value}")
    print(f"Transaction Status: {transaction_status.value}")
    print(f"Product: {session.product_name}")
    print(f"Price: {session.price} USD")
    print(f"Customer UUID: {session.customer_uuid}")
    # Handle different transaction statuses
    # ... your business logic here ...
    print("=" * 60)
    # Always return 200 OK to acknowledge receipt
    return {
    "status": "received",
    "session_uuid": session_uuid,
    "transaction_status": transaction_status.value
    }

    ⚠️ Important: Always return a 200 status code to acknowledge webhook receipt. If QBitFlow doesn't receive a 200 response, it will retry the webhook delivery multiple times.

    Method 2: Success & Cancel URLs

    Redirect-Based Monitoring

    Success and cancel URLs provide immediate feedback to your customers by redirecting them back to your site after they complete or cancel a payment. While not as reliable as webhooks (customers might close their browser), they're excellent for providing instant user feedback.

    Creating Session with URLs

    Include Success/Cancel URLs
    Add redirect URLs when creating sessions
    response = client.one_time_payments.create_session(
    product_id=1,
    success_url=f"{MY_URL}/success?uuid={{{{UUID}}}}&transactionType={{{{TRANSACTION_TYPE}}}}",
    cancel_url=f"{MY_URL}/cancel",
    customer_uuid="customer-uuid",
    )
    print(f"✓ Payment session created with redirects!")
    print(f" - Session UUID: {response.uuid}")
    print(f" - Payment Link: {response.link}")

    Handling Success Redirect

    Success URL Handler
    Handle customers redirected after successful payment
    @app.get("/success")
    async def handle_success(uuid: str, transactionType: TransactionType):
    """
    Handle success redirect from QBitFlow payment page.
    This endpoint is called when a customer completes a payment
    and is redirected back to your application.
    Args:
    uuid: The session or transaction UUID
    transactionType: The type of transaction (payment, subscription, etc.)
    Returns:
    Success page data or redirect
    """
    print("=" * 60)
    print("✅ Success redirect received")
    print("=" * 60)
    print(f"UUID: {uuid}")
    print(f"Transaction Type: {transactionType.value}")
    try:
    # Fetch the current transaction status
    transaction_status = qbitflow_client.transaction_status.get(
    transaction_uuid=uuid,
    transaction_type=transactionType
    )
    print(f"Current Status: {transaction_status.status.value}")
    # Handle different statuses
    # ... your business logic here ...
    except Exception as e:
    print(f"
    ❌ Error fetching transaction status: {e}")
    raise HTTPException(
    status_code=500,
    detail=f"Error processing success redirect: {str(e)}"
    )

    Method 3: WebSocket (Real-Time)

    Real-Time Status Updates

    WebSocket connections provide real-time transaction status updates. This is useful when you need immediate feedback, but it's generally not recommended as the primary monitoring method since it requires maintaining an active connection. Use WebSockets for UI updates while relying on webhooks for business logic.

    WebSocket Monitoring
    Monitor transaction status in real-time
    # Note: WebSocket support varies by SDK
    # Check your SDK documentation for WebSocket implementation
    # Most applications should use webhooks instead
    # WebSockets are best for real-time UI updates

    ⚠️ Note: WebSockets are best used for real-time UI updates (like progress bars or status indicators). For reliable transaction processing, always implement webhook handlers as your primary monitoring method.

    Best Practices

    Use Webhooks as Primary Method

    Always implement webhook handlers for production. They're the most reliable way to receive payment notifications, working even if customers close their browser.

    ✅ Combine Webhooks with Success URLs

    Use webhooks for reliable server-side processing and success URLs for immediate customer feedback. This combination provides the best user experience.

    🔒 Always Return 200 for Webhooks

    Your webhook endpoint must return HTTP 200 to acknowledge receipt. If QBitFlow doesn't receive a 200 response, it will retry delivery.

    🔍 Verify Transaction Status

    In success URL handlers, always verify the transaction status by querying the API. Don't trust the redirect alone for critical business logic.

    🎨 Use WebSockets for UI Only

    WebSockets are perfect for real-time UI updates (progress bars, status badges), but rely on webhooks for actual payment processing logic.