LIVE PORTAL Telegram v11.8 API Synchronized Free Animated Stickers
translate Translated
admin_panel_settings ADMIN CONTROLS Guide #18461 • Beginner Basics

Telegram Mini Apps (TMA) Architecture: WebApp SDK & Viewports

[Telegram 188] Telegram Mini Apps (TMA) Architecture: WebApp SDK & Viewports
Module 08: Bots, TMA Mini Apps & Web3 TON Ecosystem

Step 088: Telegram Mini Apps (TMA) Architecture: WebApp SDK & Viewports

88% Complete (88/100)

The era of text-only chatbots has evolved into a multi-billion-dollar application ecosystem. Telegram Mini Apps (TMA) transform Telegram into an open super-app platform, allowing developers to embed full-stack web applications (built with React, Vue, Svelte, or WebGL) directly inside Telegram's mobile and desktop clients with zero installation friction. Powered by the official Telegram WebApp JavaScript SDK (window.Telegram.WebApp), Mini Apps gain bidirectional hardware-level bridges to native mobile controls: dynamic viewport sizing, theme event synchronization, sticky main buttons, native haptic feedback, and cryptographic InitData HMAC SHA-256 authentication. In this masterclass guide, we deconstruct the complete architectural blueprint of TMA engineering.

Telegram Mini Apps Architecture Banner
Figure 88.1: TMA Webview Container Bridge, Viewport Lifecycle & Native Device Hooks. TELEGRAM 188 • TMA CERTIFIED

1. Runtime Architecture: The WebApp JavaScript SDK Bridge

Telegram Mini Apps run inside an isolated WebKit (iOS) or Chromium (Android/Desktop) webview container embedded within the native MTProto client. To communicate across the webview barrier, your web page imports the official Telegram SDK:

<!-- Include in the <head> of your HTML document before any scripts execute -->
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<script>
  const tg = window.Telegram.WebApp;
  
  // Signal client that the app is ready and loaded
  tg.ready();
  
  // Expand the webview to fill maximum vertical screen real estate
  tg.expand();
  
  // Prevent user from accidentally swiping down to close the app
  if (tg.isVersionAtLeast('7.7')) {
    tg.disableVerticalSwipes();
  }
</script>
Platform Detection

tg.platform returns ios, android, tdesktop, weba, or webk, allowing targeted OS styling and optimization.

Theme Synchronization

Automatically inherits user's active theme palette via tg.themeParams and fires themeChanged events in real time.

Cloud Storage API

Store persistent client state using tg.CloudStorage (up to 1,024 key-value pairs per user) synchronized across all user devices.

2. Viewport Lifecycle & Touch Gesture Locking

Mobile webviews present complex viewport challenges. Telegram clients display Mini Apps in a partial modal bottom sheet by default. Developers must manage viewport transitions gracefully:

Critical Viewport APIs & Behaviors

  • tg.expand(): Stretches the webview container to occupy the full height of the mobile display, eliminating the top gap.
  • tg.disableVerticalSwipes(): Crucial for games, charts, and scrollable lists. Without this call, downward touch gestures inside the app will trigger Telegram's native "swipe-down to dismiss" gesture, unexpectedly closing your app.
  • tg.enableClosingConfirmation(): Displays a native "Are you sure you want to close this app?" dialog if the user attempts to exit, preventing loss of unsaved form data or game progress.
  • tg.viewportHeight vs. tg.viewportStableHeight: When the mobile on-screen virtual keyboard appears, viewportHeight contracts immediately. Bind UI layouts using CSS variable var(--tg-viewport-stable-height) to prevent jumping layouts.

3. Cryptographic InitData HMAC SHA-256 Authentication

Unlike traditional web apps that require passwords or email verifications, Telegram Mini Apps provide instant passwordless authentication via the signed tg.initData string:

validate_tma_init_data.py HMAC SHA-256 Server Validation
import hmac
import hashlib
import urllib.parse
import json
import time

def verify_telegram_init_data(init_data_str: str, bot_token: str) -> dict:
    parsed_data = dict(urllib.parse.parse_qsl(init_data_str, keep_blank_values=True))
    if "hash" not in parsed_data:
        raise ValueError("Missing hash in initData")
        
    received_hash = parsed_data.pop("hash")
    
    # 1. Sort remaining key-value pairs alphabetically
    data_check_arr = [f"{k}={v}" for k, v in sorted(parsed_data.items())]
    data_check_string = "
".join(data_check_arr)
    
    # 2. Derive secret key: HMAC_SHA256("WebAppData", bot_token)
    secret_key = hmac.new(b"WebAppData", bot_token.encode(), hashlib.sha256).digest()
    
    # 3. Calculate expected hash
    expected_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
    
    if not hmac.compare_digest(received_hash, expected_hash):
        raise PermissionError("Tampered initData signature! Access denied.")
        
    # 4. Check for replay attacks (token validity: 24 hours)
    auth_date = int(parsed_data.get("auth_date", 0))
    if time.time() - auth_date > 86400:
        raise TimeoutError("initData signature expired (>24 hours)")
        
    user_data = json.loads(parsed_data.get("user", "{}"))
    return {"authenticated": True, "user": user_data}
Interactive Lab Simulator

TMA WebApp Viewport & Native SDK Simulator

ENGINE: WEBAPP_SDK_V7.10

SDK Controller

← Back TGWAY Mini App ×
💎 TON Wallet Connected
Balance: 128.50 TON
User: @tgway_vip (ID: 8492019)
WEBAPP SDK EVENT LOG SYNCED
[SDK] WebApp.ready() executed. Handshake established.

5. Complete System Architecture Blueprint: TMA Ecosystem

Inspect the comprehensive architectural infographic detailing WebApp SDK lifecycle methods, HMAC SHA-256 InitData cryptographic verification, viewport dimensions, and native UI bindings:

Telegram Mini Apps Architecture Blueprint
Click to Enlarge High-Res Blueprint
Figure 88.2: Full 2:3 Masterclass Infographic Summary. Click to inspect high-resolution vector details.

6. Platform Comparison: TMA vs. Native iOS/Android vs. PWA vs. Standard Bot

Metric Telegram Mini App Native App (App Store) Progressive Web App Traditional Chatbot
Installation Friction Zero (Instant Tap) High (100MB+ Download) Moderate ("Add to Home") Zero
User Authentication Instant InitData HMAC Email/Social Login Cookies / OAuth Telegram User ID
App Store 30% Tax Exempt (TON / Crypto) Mandatory 30% IAP Exempt (Stripe) Exempt
UI & Graphics Richness Full HTML5/WebGL/3D Native GPU Rendering Full HTML5 Text & Buttons Only

7. Frequently Asked Questions (FAQ)

Q1: Can I trust initDataUnsafe on my frontend?

Never for secure operations. window.Telegram.WebApp.initDataUnsafe is unverified JSON parsed directly in the user's browser, which can be modified using browser developer tools or spoofed webviews. Always transmit the raw initData string to your backend server and perform cryptographic HMAC SHA-256 validation before granting access to balances, user data, or executing purchases.

Q2: How do I test Telegram Mini Apps on localhost during development?

Telegram requires Mini App URLs to use HTTPS with a valid SSL certificate. To test locally on localhost:3000, deploy a secure tunnel using Cloudflare Tunnels (cloudflared tunnel --url http://localhost:3000) or ngrok (ngrok http 3000), and configure the issued HTTPS tunnel URL in @BotFather.

Q3: How do I connect the bot's Menu Button directly to my Mini App?

Open @BotFather → send /setmenubutton → select your bot → choose "Configure menu button" → enter the URL of your WebApp → provide a button title (e.g., "Launch App 🚀"). Users will see a prominent permanent button beside the chat input field.

Q4: What is the maximum storage capacity of tg.CloudStorage?

WebApp.CloudStorage allows each user to store up to 1,024 individual keys, with each key up to 128 characters and each value up to 4,096 characters. This is ideal for storing game checkpoints, user UI preferences, and local cache pointers without needing an external relational database.

Q5: Can a Telegram Mini App scan QR codes using the device camera?

Yes. Mini Apps have native camera access via WebApp.showScanQrPopup({ text: 'Scan TON Address' }). When invoked, Telegram opens its native camera UI, scans the QR code, decodes the text, fires the qrTextReceived callback event to your JavaScript code, and closes the scanner automatically.

MODULE 08 • WEB3 HIGHWAY UNLOCKED Next Architecture Milestone: Step 089

Ready for Step 089: TON Wallet Integration: Non-Custodial Wallets, USDT & Jettons

With your Telegram Mini App frontend rendering natively and authenticating via HMAC InitData, step into the financial engine of Telegram: The Open Network (TON). Learn how to connect non-custodial wallets (Tonkeeper, Telegram Wallet), transact in native TON and official TON-USDT, and handle custom Jetton tokens.

Continue to Step 089 (TON Wallet Integration) →
← Prev: [Telegram 187] Inline Bots Architecture: @gif, @pic & Inline Queries Next: [Telegram 189] TON Wallet Integration: Non-Custodial Wallets, USDT & Jettons →
admin_panel_settings ADMIN Guide #18461 Actions
Enlarged Preview
Click anywhere outside or press ESC to close viewer
smart_display Telegram Video Short
1080p HD
Official Source: @TelegramTips Post #44 Press ESC or click outside to close