Skip to content

1. Introduction

RAprogramm edited this page Nov 4, 2025 · 1 revision

Chapter 1: Introduction

What is telegram-webapp-sdk?

telegram-webapp-sdk is a comprehensive Rust library that provides type-safe bindings for the Telegram WebApp JavaScript API. It allows you to build Telegram Mini Apps (WebApps) using Rust and WebAssembly, with full framework support for Yew and Leptos.

Why Use This SDK?

Type Safety

Rust's strong type system catches errors at compile time instead of runtime:

// Compiler ensures user.id is always i64
let user_id: i64 = webapp.init_data_unsafe().user.unwrap().id;

// Optional fields are explicit
let username: Option<String> = webapp.init_data_unsafe().user.unwrap().username;

Zero Runtime Overhead

Rust code compiles to WebAssembly with performance close to native JavaScript:

// This Rust code:
webapp.expand_viewport();

// Compiles to direct JavaScript call:
window.Telegram.WebApp.expand();

Framework Integration

First-class support for popular Rust web frameworks:

  • Yew - Component-based UI with hooks and virtual DOM
  • Leptos - Fine-grained reactivity with minimal runtime

Complete API Coverage

Wraps the entire Telegram WebApp API (v9.2):

  • User interactions (contact sharing, phone number requests)
  • Payment processing (invoices)
  • Storage (cloud, device, secure)
  • Biometric authentication
  • Location services
  • Device sensors (accelerometer, gyroscope, orientation)
  • Haptic feedback
  • QR code scanning
  • Theme customization
  • And more...

How Telegram Mini Apps Work

┌──────────────────────────────────────────────────────────────┐
│                      Telegram User                           │
│                                                              │
│  ┌────────────────────────────────────────────────────────┐  │
│  │              Telegram Mobile/Desktop App               │  │
│  │                                                        │  │
│  │  ┌──────────────────────────────────────────────────┐ │  │
│  │  │                 Your WebApp                       │ │  │
│  │  │          (Rust → WASM → Browser)                  │ │  │
│  │  │                                                    │ │  │
│  │  │  • Built with telegram-webapp-sdk                 │ │  │
│  │  │  • Runs in embedded browser                       │ │  │
│  │  │  • Has access to Telegram context                 │ │  │
│  │  └──────────────────────────────────────────────────┘ │  │
│  └────────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────┘
                            │
                            │ HTTPS
                            ▼
┌──────────────────────────────────────────────────────────────┐
│                      Your Infrastructure                      │
│                                                              │
│  ┌─────────────────────┐       ┌────────────────────────┐  │
│  │   Static Hosting    │       │     Bot Backend        │  │
│  │                     │       │                        │  │
│  │  • Serves WASM      │◄─────▶│  • Telegram Bot API   │  │
│  │  • Serves HTML/CSS  │       │  • Processes WebApp   │  │
│  │  • HTTPS required   │       │    data               │  │
│  └─────────────────────┘       └────────────────────────┘  │
└──────────────────────────────────────────────────────────────┘

Architecture Overview

The SDK consists of several layers:

1. Core Layer (core/)

Fundamental types and initialization logic:

core/
├── init.rs          # SDK initialization (init_sdk, try_init_sdk)
├── context.rs       # Global Telegram context management
├── safe_context.rs  # Thread-safe context access
└── types/           # Type definitions
    ├── user.rs      # TelegramUser
    ├── init_data.rs # TelegramInitData
    ├── theme_params.rs
    └── ...

2. API Layer (api/)

High-level wrappers for Telegram features:

api/
├── biometric.rs          # Biometric authentication
├── cloud_storage.rs      # Cloud storage operations
├── device_storage.rs     # Local storage (localStorage)
├── secure_storage.rs     # Secure storage for sensitive data
├── haptic.rs             # Haptic feedback
├── accelerometer.rs      # Accelerometer sensor
├── gyroscope.rs          # Gyroscope sensor
├── device_orientation.rs # Device orientation
├── location_manager.rs   # Location services
├── settings_button.rs    # Settings button in UI
├── user.rs               # User operations (contact sharing)
├── viewport.rs           # Viewport and safe area
└── theme.rs              # Theme customization

3. WebApp Layer (webapp/)

Main TelegramWebApp struct that provides unified access:

use telegram_webapp_sdk::TelegramWebApp;

let webapp = TelegramWebApp::new();

// Core functionality
webapp.ready();
webapp.expand_viewport();

// UI controls
webapp.set_header_color("#FF0000");
webapp.set_background_color("#FFFFFF");

// Dialogs
webapp.show_popup(params);
webapp.show_scan_qr_popup(callback);

// Navigation
webapp.open_link("https://example.com");
webapp.share_url("https://example.com", "Check this out!");

4. Framework Layer (yew/, leptos/)

Framework-specific integrations:

Yew:

use telegram_webapp_sdk::use_telegram_context;
use yew::prelude::*;

#[function_component(App)]
fn app() -> Html {
    let ctx = use_telegram_context();

    html! {
        <div>
            <h1>{ "Telegram WebApp" }</h1>
        </div>
    }
}

Leptos:

use telegram_webapp_sdk::provide_telegram_context;
use leptos::prelude::*;

#[component]
fn App() -> impl IntoView {
    provide_telegram_context();

    view! {
        <div>
            <h1>"Telegram WebApp"</h1>
        </div>
    }
}

5. Macro Layer (macros/)

Declarative macros for common patterns:

use telegram_webapp_sdk::{telegram_app, telegram_page, telegram_router};

#[telegram_page(path = "/")]
fn Home() -> Html {
    html! { <h1>{ "Home" }</h1> }
}

#[telegram_page(path = "/profile")]
fn Profile() -> Html {
    html! { <h1>{ "Profile" }</h1> }
}

#[telegram_app(auto_init)]
fn App() -> Html {
    telegram_router! {
        "/" => Home,
        "/profile" => Profile,
    }
}

6. Router Layer (router/)

Page-based routing using compile-time registration:

use telegram_webapp_sdk::router::{navigate_to, get_registered_pages};

// Pages auto-register via telegram_page! macro
navigate_to("/profile");

// Get all pages
let pages = get_registered_pages();

7. Mock Layer (mock/)

Testing support without Telegram:

#[cfg(feature = "mock")]
use telegram_webapp_sdk::mock::{init_mock, MockConfig, MockUser};

let config = MockConfig {
    user: Some(MockUser {
        id: 12345,
        first_name: "Test User".into(),
        username: Some("testuser".into()),
        ..Default::default()
    }),
    platform: "ios",
    version: "7.0",
    ..Default::default()
};

init_mock(config);

Project Status

Property Value
Current Version 0.3.0
MSRV Rust 1.90+
Telegram WebApp API 9.2
License MIT
Repository github.com/RAprogramm/telegram-webapp-sdk
Crates.io crates.io/crates/telegram-webapp-sdk
Documentation docs.rs/telegram-webapp-sdk

Breaking Changes in v0.3.0

Version 0.3.0 removed client-side validation for security reasons. Bot tokens should never be exposed in client code.

Removed:

  • validate_init_data module
  • ValidationKey enum
  • TelegramWebApp::validate_init_data() method
  • verify_init_data_hash() function
  • Crypto dependencies: hmac-sha256, hex, base64, ed25519-dalek

Migration: Use server-side validation with init-data-rs:

// Server-side (backend)
use init_data_rs::{validate, InitData};

async fn authenticate(init_data_str: &str, bot_token: &str)
    -> Result<InitData, Box<dyn std::error::Error>>
{
    // Validates signature and expiration
    let init_data = validate(init_data_str, bot_token, Some(3600))?;
    Ok(init_data)
}

What You'll Learn

This Wiki covers:

  1. Installation & Setup - Getting started with your first project
  2. Core Concepts - Understanding initialization, context, and types
  3. Framework Integration - Using with Yew and Leptos
  4. API Reference - Complete guide to all APIs
  5. Common Patterns - Best practices and real-world examples
  6. Production Deployment - Deploying your WebApp
  7. Testing - Testing strategies with mock environment

Next Steps

Ready to build your first Telegram Mini App?

Chapter 2: Installation & Setup

Additional Resources

Clone this wiki locally