DEV Community

Simplr
Simplr

Posted on

Telegram Mini Apps Creation Handbook

This handbook outlines the process of creating Telegram Mini Apps. It emphasizes accuracy, provides detailed explanations, and includes optional/required tagging for clarity.

1. Understanding Telegram Mini Apps

  • Definition: Telegram Mini Apps are web applications that run directly within the Telegram app. They offer a seamless user experience without requiring users to leave the Telegram environment.
  • Key Features:
    • Native Integration: Deep integration with Telegram features like payments, contacts, and location.
    • Cross-Platform: Works on all Telegram platforms (iOS, Android, Desktop).
    • Secure: Uses Telegram's secure infrastructure.
    • Discoverable: Can be launched from chats, bots, or directly.

2. Prerequisites

  • Tool: A web development environment (e.g., VS Code, Sublime Text).
  • Skills:
    • HTML, CSS, JavaScript/TypeScript: Essential for building the user interface and logic.
    • Backend Development (Optional): If your Mini App requires server-side logic, you'll need a backend language (e.g., Node.js, Python, Go).
  • Telegram Bot: A Telegram bot is required to host and launch your Mini App. You can create one using the BotFather (see previous handbook).

3. Setting Up Your Development Environment

  1. Choose a Framework (Recommended): While you can build a Mini App with vanilla JavaScript, using a framework like React, Vue, or Svelte can significantly improve development efficiency and maintainability. React is a solid choice due to its component-based architecture and large ecosystem.

  2. Create a New Project (React Example):

    npx create-react-app my-telegram-miniapp --template typescript
    cd my-telegram-miniapp
    
  3. Install the Telegram Web App SDK: This SDK provides access to Telegram's Mini App API.

    npm install @twa-dev/sdk
    
  4. Install telegram-web-app types:

    npm install --save-dev @types/telegram-web-app
    

4. Initializing the Telegram Web App SDK

  • Importance: The SDK must be initialized before you can use any of its features.
  1. Initialize the SDK in your main component (e.g., src/App.tsx):
import React, { useEffect } from 'react';
import './App.css';
import { useTelegram } from './hooks/useTelegram';

function App() {
  const { tg, onToggleButton } = useTelegram();

  useEffect(() => {
    tg.ready();
  }, [tg]);

  return (
    <div className="App">
      Content
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
// src/hooks/useTelegram.ts
import { useEffect, useState } from 'react';

const tg = window.Telegram.WebApp;

export function useTelegram() {

    const onClose = () => {
        tg.close()
    }

    const onToggleButton = () => {
        if(tg.MainButton.isVisible) {
            tg.MainButton.hide();
        } else {
            tg.MainButton.show();
        }
    }

    return {
        tg,
        onClose,
        onToggleButton,
        user: tg.initDataUnsafe?.user,
        queryId: tg.initDataUnsafe?.query_id,
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Explanation:
*   **`window.Telegram.WebApp`:** This global object is provided by Telegram when the Mini App is running within the Telegram environment.
*   **`tg.ready()`:**  This function signals to Telegram that your Mini App is ready to be displayed.  It's crucial to call this early in your app's lifecycle.
*   **`useEffect`:**  The `useEffect` hook ensures that `tg.ready()` is called only once after the component mounts.
Enter fullscreen mode Exit fullscreen mode

5. Implementing Basic Features

  • Objective: Demonstrate core Mini App functionalities.
  1. Setting the Background Color:
useEffect(() => {
    tg.setBackgroundColor("#f0f0f0");
}, [tg]);
Enter fullscreen mode Exit fullscreen mode
  1. Showing and Hiding the Main Button:
useEffect(() => {
    tg.MainButton.setText('Close')
    tg.MainButton.onClick(onClose)
}, [tg])
Enter fullscreen mode Exit fullscreen mode
  1. Accessing User Data:
const { user } = useTelegram();

// ...

{user?.id}
Enter fullscreen mode Exit fullscreen mode
  1. Explanation:
*   **`tg.setBackgroundColor()`:** Sets the background color of the Mini App.
*   **`tg.MainButton`:**  Provides access to the main button at the bottom of the Mini App.  You can customize its text, color, and click handler.
*   **`tg.initDataUnsafe.user`:** Contains information about the current user (ID, first name, last name, username).  **Important:** This data is *unsafe* because it's not cryptographically verified.  For sensitive operations, you should verify the data using the `initData` property (see Security Considerations).
Enter fullscreen mode Exit fullscreen mode

6. Handling Events

  • Importance: Mini Apps can respond to various events triggered by the user or Telegram.
  1. Listening for the themeChanged Event:
useEffect(() => {
    tg.onEvent('themeChanged', function(){
        document.body.style.backgroundColor = tg.themeParams.bg_color;
    })
}, [tg])
Enter fullscreen mode Exit fullscreen mode
  1. Explanation:
*   **`tg.onEvent()`:**  Registers a callback function to be executed when a specific event occurs.
*   **`themeChanged`:**  This event is triggered when the user changes the Telegram theme (e.g., from light to dark mode).
*   **`tg.themeParams`:**  Provides access to the current theme parameters (e.g., background color, text color).
Enter fullscreen mode Exit fullscreen mode

7. Sending Data Back to the Bot

  • Mechanism: Mini Apps can send data back to the bot that launched them.
  1. Sending Data Using tg.sendData():
const sendDataToBot = () => {
    tg.sendData(JSON.stringify({ message: 'Hello from the Mini App!' }));
};
Enter fullscreen mode Exit fullscreen mode
  1. Handling the Data in Your Bot (Node.js Example):
bot.on('message', (msg) => {
  if (msg.web_app_data) {
    const data = JSON.parse(msg.web_app_data.data);
    console.log('Received data from Mini App:', data);
    bot.sendMessage(msg.chat.id, `You sent: ${data.message}`);
  }
});
Enter fullscreen mode Exit fullscreen mode
  1. Explanation:
*   **`tg.sendData()`:** Sends a string of data back to the bot.  It's common to serialize the data as JSON.
*   **`msg.web_app_data`:**  In your bot's message handler, check for the `web_app_data` property.  This contains the data sent from the Mini App.
*   **`msg.web_app_data.data`:**  The actual data string sent by the Mini App.
Enter fullscreen mode Exit fullscreen mode

8. Security Considerations

  • Data Verification: Always verify the initData using the bot's token to ensure the data hasn't been tampered with.
  • Input Sanitization: Sanitize user input to prevent cross-site scripting (XSS) attacks.
  • HTTPS: Your Mini App must be served over HTTPS.
  1. Verifying initData (Simplified Example - Node.js):
import crypto from 'crypto';

function verifyTelegramWebAppInitData(initData: string, botToken: string): boolean {
  const secretKey = crypto
    .createHmac('sha256', 'WebAppData')
    .update(botToken)
    .digest();

  const dataCheckString = new URLSearchParams(initData).sort().toString();
  const hmac = crypto
    .createHmac('sha256', secretKey)
    .update(dataCheckString)
    .digest('hex');

  const expectedHash = new URLSearchParams(initData).get('hash');

  return hmac === expectedHash;
}
Enter fullscreen mode Exit fullscreen mode

9. Launching Your Mini App

  1. Create a Bot Command: Use BotFather to create a command that launches your Mini App (e.g., /webapp).

  2. Implement the Command in Your Bot:

bot.onText(/\/webapp/, (msg) => {
  const chatId = msg.chat.id;
  bot.sendWebApp(chatId, {
    url: 'YOUR_MINI_APP_URL',
  });
});
Enter fullscreen mode Exit fullscreen mode
  1. Explanation:
*   bot.sendWebApp():  Sends a message with a button that launches the Mini App.

  • url: The URL of your deployed Mini App.
Enter fullscreen mode Exit fullscreen mode

  1. Testing and Debugging

  • Telegram Desktop: Use Telegram Desktop for easier debugging. Open the developer tools (usually by pressing F12) to inspect the Mini App's console and network requests.
  • Remote Debugging (Android): Use Chrome's remote debugging feature to debug your Mini App running on an Android device.

11. Deployment

  • Platforms: Deploy your Mini App to any web hosting platform that supports HTTPS (e.g., Netlify, Vercel, AWS S3, Google Cloud Storage).
  • Continuous Integration/Continuous Deployment (CI/CD): Automate the deployment process.

12. Advanced Features and Considerations

  • Payments: Integrate Telegram Payments into your Mini App.
  • Location: Access the user's location (with their permission).
  • Haptic Feedback: Provide haptic feedback to enhance the user experience.
  • Theme Customization: Adapt your Mini App to the user's Telegram theme.
  • Data Storage: Use localStorage or sessionStorage for client-side data storage.

References

This handbook provides a comprehensive guide to creating Telegram Mini Apps. Remember to consult the official Telegram documentation for the most up-to-date information and advanced features. Good luck!

Top comments (0)