Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

I want to implement purchase via Telegram stars in my python app. As far as I understand…

  1. User

    I want to implement purchase via Telegram stars in my python app. As far as I understand the whole purchase via stars is made via UI in javascritp in my miniapp. And on the backend I need just implement reliable way to verify the transaction. I want to add some sort of payload to the transaction with format like f"{auth_user_uuid}:{item_uuid}" and then somehow just verify that this transaction indeed was paid by the user using tg bot key and telegram user id. Write me a code for this. Or better help me make an entire architecture for this. My app is written in FastAPI and uses websockets so I have a full duplex connection.

  2. Assistant

    Implementing purchases via Telegram Stars in your FastAPI application involves coordinating the frontend (JavaScript miniapp) with the backend (FastAPI) to handle transactions securely and efficiently. Below, I'll outline a comprehensive architecture for this integration and provide sample code snippets to help you get started.

    Architecture Overview

    1. Components Involved

    • Frontend (JavaScript Miniapp):

      • Embedded within Telegram (using Web Apps API)
      • Handles user interactions for purchasing stars
      • Initiates payment transactions
      • Sends transaction data to the backend
    • Backend (FastAPI):

      • Exposes REST endpoints for handling payment confirmations
      • Validates transactions using Telegram's API
      • Updates user credits or processes the purchased items
      • Utilizes WebSockets for real-time communication if needed
    • Telegram Bot:

      • Acts as an intermediary for handling payments
      • Receives updates about transactions
      • Communicates with the backend for verification

    2. Workflow Steps

    1. User Initiates Purchase:

      • The user interacts with the miniapp to buy stars.
      • The frontend generates a payload containing auth_user_uuid and item_uuid, formatted as {auth_user_uuid}:{item_uuid}.
    2. Payment Processing:

      • The frontend invokes Telegram's payment interface using the Web Apps API, passing the payload.
      • Telegram processes the payment and associates it with the user and the provided payload.
    3. Transaction Notification:

      • Upon successful payment, Telegram sends a callback (via webhook) to your backend with transaction details, including the payload.
    4. Backend Verification:

      • The backend receives the callback, parses the payload to extract auth_user_uuid and item_uuid.
      • It verifies the transaction's authenticity using the Telegram Bot API and ensures that the user ID matches.
      • Upon successful verification, the backend updates the database accordingly (e.g., credits the user's account for the purchased item).
    5. Real-time Updates (Optional):

      • Using WebSockets, the backend can notify the frontend in real-time about the transaction status, providing immediate feedback to the user.

    Implementation Details

    1. Setting Up Your Telegram Bot

    Ensure you have a Telegram bot set up with the necessary permissions to handle payments. Obtain the bot token, which will be used for API calls.

    2. Frontend Integration (JavaScript Miniapp)

    Your frontend will handle initiating the payment and sending transaction data to the backend.

    // Example: Initiating a Telegram Web App Payment
    
    // Initialize the Telegram Web App
    const tg = window.Telegram.WebApp;
    
    // Function to initiate payment
    function buyStars(authUserUuid, itemUuid) {
        const payload = `${authUserUuid}:${itemUuid}`;
        
        // Define payment parameters as per Telegram's Payment API
        const paymentParams = {
            // ... your payment parameters
            payload: payload, // Custom payload
            // other necessary fields
        };
        
        tg.sendData(JSON.stringify(paymentParams));
    }
    
    // Handle the payment result
    tg.onEvent('data', (data) => {
        const paymentData = JSON.parse(data);
        
        // Send payment data to the backend via WebSocket or HTTP
        sendPaymentToBackend(paymentData);
    });
    
    function sendPaymentToBackend(paymentData) {
        // Using WebSockets
        const socket = new WebSocket('wss://your-backend-url/ws/payment');
        socket.onopen = () => {
            socket.send(JSON.stringify(paymentData));
        };
        
        // Alternatively, using HTTP POST
        /*
        fetch('https://your-backend-url/api/payment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(paymentData),
        })
        .then(response => response.json())
        .then(data => {
            // Handle response
        });
        */
    }
    

    3. Backend Integration (FastAPI)

    Your backend will handle receiving and verifying transaction data.

    a. Dependencies

    First, install necessary dependencies:

    pip install fastapi uvicorn python-telegram-bot[asyncio] pydantic
    

    b. FastAPI Application

    from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends
    from pydantic import BaseModel
    import os
    import hmac
    import hashlib
    from typing import Dict
    import requests
    
    app = FastAPI()
    
    # Load your Telegram Bot Token from environment variables or a secure source
    TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
    TELEGRAM_API_URL = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/"
    
    # Pydantic models for incoming data
    class PaymentData(BaseModel):
        user_id: int
        transaction_id: str
        payload: str
        // Include other necessary fields as per Telegram's API
    
    class TransactionPayload(BaseModel):
        auth_user_uuid: str
        item_uuid: str
    
    # WebSocket Manager (Optional, for real-time communication)
    class ConnectionManager:
        def __init__(self):
            self.active_connections: Dict[int, WebSocket] = {}
    
        async def connect(self, websocket: WebSocket, user_id: int):
            await websocket.accept()
            self.active_connections[user_id] = websocket
    
        def disconnect(self, user_id: int):
            if user_id in self.active_connections:
                del self.active_connections[user_id]
    
        async def send_message(self, user_id: int, message: str):
            if user_id in self.active_connections:
                websocket = self.active_connections[user_id]
                await websocket.send_text(message)
    
    manager = ConnectionManager()
    
    # Endpoint to handle payment notifications via HTTP (if Telegram sends HTTP callbacks)
    @app.post("/api/payment")
    async def handle_payment(payment: PaymentData):
        # Parse the payload
        try:
            auth_user_uuid, item_uuid = payment.payload.split(":")
        except ValueError:
            raise HTTPException(status_code=400, detail="Invalid payload format")
    
        # Verify the transaction
        is_valid = await verify_transaction(payment)
        if not is_valid:
            raise HTTPException(status_code=400, detail="Invalid transaction")
    
        # Process the purchase (e.g., credit user's account)
        process_purchase(auth_user_uuid, item_uuid, payment.user_id, payment.transaction_id)
    
        return {"status": "success"}
    
    # WebSocket endpoint to handle real-time payment data
    @app.websocket("/ws/payment")
    async def websocket_endpoint(websocket: WebSocket):
        await websocket.accept()
        try:
            while True:
                data = await websocket.receive_text()
                payment = PaymentData.parse_raw(data)
                
                # Parse the payload
                try:
                    auth_user_uuid, item_uuid = payment.payload.split(":")
                except ValueError:
                    await websocket.send_text("Invalid payload format")
                    continue
    
                # Verify the transaction
                is_valid = await verify_transaction(payment)
                if not is_valid:
                    await websocket.send_text("Invalid transaction")
                    continue
    
                # Process the purchase
                process_purchase(auth_user_uuid, item_uuid, payment.user_id, payment.transaction_id)
                
                # Acknowledge the user
                await websocket.send_text("Purchase successful")
        except WebSocketDisconnect:
            manager.disconnect(payment.user_id)
    
    # Function to verify transaction authenticity
    async def verify_transaction(payment: PaymentData) -> bool:
        # Example: Verify the transaction using Telegram API
        # This will depend on how Telegram sends transaction data
        # For demonstration, we'll assume we need to get transaction details via Telegram API
    
        url = f"{TELEGRAM_API_URL}getTransaction"
        params = {"transaction_id": payment.transaction_id}
    
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()
            result = response.json()
            
            if not result.get("ok"):
                return False
    
            transaction = result.get("result")
            
            # Verify that the user ID matches
            if transaction.get("user_id") != payment.user_id:
                return False
    
            # Additional verification can be done here (e.g., amount, currency)
            return True
        except requests.RequestException as e:
            print(f"Error verifying transaction: {e}")
            return False
    
    # Function to process the purchase
    def process_purchase(auth_user_uuid: str, item_uuid: str, user_id: int, transaction_id: str):
        # Implement your business logic here
        # For example:
        """
        1. Retrieve the user from the database using auth_user_uuid
        2. Retrieve the item details using item_uuid
        3. Credit the user's account with the purchased item/stars
        4. Log the transaction for auditing
        """
        print(f"Processing purchase for user {auth_user_uuid}, item {item_uuid}, transaction {transaction_id}")
        # TODO: Add actual implementation
    

    c. Explanation of Backend Components

    1. Pydantic Models:

      • PaymentData: Represents the structure of incoming payment data.
      • TransactionPayload: Parses the custom payload to extract auth_user_uuid and item_uuid.
    2. WebSocket Manager (Optional):

      • Manages active WebSocket connections for real-time communication.
      • Allows sending messages to specific users based on user_id.
    3. Endpoints:

      • /api/payment: Receives HTTP POST requests from Telegram with payment details.
      • /ws/payment: Handles WebSocket connections for real-time payment data.
    4. Transaction Verification:

      • The verify_transaction function uses Telegram's API to validate the transaction.
      • Ensure that the user_id in the transaction matches the one provided.
      • Additional checks (e.g., amount, currency) can be added based on Telegram's API responses.
    5. Processing Purchase:

      • Upon successful verification, the process_purchase function executes business logic such as updating the database with the purchased item or crediting the user's account.

    4. Security Considerations

    • Data Validation: Always validate and sanitize incoming data to prevent injection attacks.
    • Secure Storage: Store your Telegram Bot Token securely, preferably using environment variables or a secrets manager.
    • HTTPS: Ensure all communications, especially those involving transactions, occur over HTTPS to protect data in transit.
    • Authentication: If you're exposing endpoints, ensure they're secured and authenticated to prevent unauthorized access.

    5. Handling Webhooks (Alternative Approach)

    If Telegram supports webhooks for payment confirmations, you can set up a webhook endpoint in your FastAPI application instead of (or in addition to) using WebSockets.

    from fastapi import BackgroundTasks
    
    @app.post("/webhook/telegram")
    async def telegram_webhook(background_tasks: BackgroundTasks, update: dict):
        # Parse the update received from Telegram
        # This depends on Telegram's webhook structure
        payment = PaymentData(
            user_id=update['message']['from']['id'],
            transaction_id=update['transaction']['id'],
            payload=update['transaction']['payload']
        )
        
        # Add verification and processing to background tasks
        background_tasks.add_task(handle_payment, payment)
        
        return {"status": "received"}
    

    Ensure you register this webhook URL with Telegram via the Bot API:

    curl -F "url=https://your-domain.com/webhook/telegram" https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook
    

    Conclusion

    Integrating Telegram Stars purchases into your FastAPI application involves setting up a secure and efficient communication flow between your frontend miniapp and backend services. By following the outlined architecture and implementing the provided code snippets, you can create a reliable system for handling transactions, verifying their authenticity, and processing purchases seamlessly.

    Next Steps:

    1. Refer to Telegram's Official Documentation: Ensure you comply with Telegram's latest API specifications and payment processing guidelines.

    2. Implement Detailed Business Logic: Customize the process_purchase function to fit your application's requirements, such as updating user databases, handling inventory, etc.

    3. Thorough Testing: Rigorously test the entire payment flow to handle edge cases, failures, and ensure data integrity.

    4. Monitoring and Logging: Implement logging mechanisms to monitor transactions and quickly identify and resolve issues.

    Feel free to reach out if you have further questions or need assistance with specific parts of the implementation!