UNPKG

tg-mini-app-binder

Version:

A modular and extendable wrapper for the Telegram Mini App API to simplify interactions between your web app and the Telegram client.

202 lines (169 loc) 7.67 kB
# Telegram Mini App Binder A modular and extendable wrapper for the Telegram Mini App API (window.Telegram.WebApp). This library simplifies interactions between your web app and the Telegram client by providing a clean, object-oriented, and fully-documented interface. It's designed to be lightweight, easy to use, and works seamlessly in both static web apps and modern JavaScript projects that use bundlers like Webpack or Rollup. ## ✨ Features **Modular Architecture:** Functionality is split into logical modules (app, user, ui, messaging, links) for clarity and maintainability. **Simplified API:** Abstracts away the raw Telegram.WebApp object into intuitive methods. **Mock Mode:** Provides a mock object for easier development and testing outside the Telegram client, preventing crashes and logging actions to the console. **User Management:** Easily access user data and the critical initData string for backend validation. **UI Controls:** Effortlessly manage the Main Button, Back Button, and trigger Haptic Feedback. **Contact Request:** A simplified, promise-based method to request the user's phone number. **Messaging:** Send data from your Mini App directly to your bot. **App Lifecycle:** Control the app by closing or expanding it, and listen for key events like theme changes. **Navigation:** Open other Telegram Mini Apps, user profiles, or payment invoices. ## 🚀 Installation You can use the library in two ways: by directly including it in your HTML or by installing it via NPM. ## 1. For Static Web Apps (HTML, JS) If you are not using a bundler, you can include the library files directly in your HTML. Make sure to load the official Telegram script first. ```javascript <!-- 1. The official Telegram script --> <script src="https://unpkg.com/tg-mini-app-binder@1.0.0/src/index.js"></script> <!-- 2. The library modules --> <script type="module" src="path/to/src/modules/WebAppModule.js"></script> <script type="module" src="path/to/src/modules/UserModule.js"></script> <script type="module" src="path/to/src/modules/MessagingModule.js"></script> <script type="module" src="path/to/src/modules/UIModule.js"></script> <script type="module" src="path/to/src/modules/LinksModule.js"></script> <script type="module" src="path/to/src/index.js"></script> <!-- 3. Your application logic --> <script type="module" src="your-app.js"></script> ``` ## 2. For Node.js Environments (with a bundler) For projects using NPM and a bundler like Webpack, Rollup, or Vite: 1. Install the package: ``` bash npm install tg-mini-app-binder ``` 2. Import and use it in your project: ``` javascript import TelegramMiniAppBinder from 'tg-mini-app-binder'; const tgBinder = new TelegramMiniAppBinder(); // Now you can use the binder console.log('User First Name:', tgBinder.user.getData()?.first_name); ``` ## 📖 API Reference & Examples First, instantiate the library. All functionalities are accessed through this instance. ``` javascript const tgBinder = new TelegramMiniAppBinder(); ``` ## App Module (tgBinder.app) Manages general app properties and lifecycle events. **Close the App** ``` javascript // Closes the Mini App window tgBinder.app.close(); ``` **Expand the App** ``` javascript // Expands the Mini App to its maximum height tgBinder.app.expand(); ``` **Get Platform and Color Scheme** ``` javascript console.log('Platform:', tgBinder.app.getPlatform()); // "ios", "android", "desktop" console.log('Color Scheme:', tgBinder.app.getColorScheme()); // "light" or "dark" ``` **Listen for Events** ``` javascript // Fired when the user's Telegram theme changes tgBinder.app.onEvent('themeChanged', () => { console.log('Theme has changed to:', tgBinder.app.getColorScheme()); // You can update your app's CSS variables here }); // Fired when the viewport size changes (e.g., keyboard appears) tgBinder.app.onEvent('viewportChanged', () => { console.log('Viewport height is now:', tgBinder.tg.viewportHeight); }); ``` ## User Module (tgBinder.user) Handles user-related data. **Get User Data** This data is "unsafe" and should only be used for display purposes. For authentication, validate the initData on your backend. ``` javascript const user = tgBinder.user.getData(); if (user) { console.log(`Hello, ${user.first_name}!`); // user object: { id, first_name, last_name?, username?, language_code, is_premium? } } ``` **Get Init Data** This is the raw, encrypted data string you should send to your backend for validation to authenticate the user. ``` javascript const initData = tgBinder.user.getInitData(); // Send this 'initData' string to your backend fetch('/your-api/authenticate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ initData }) }); ``` ## Messaging Module (tgBinder.messaging) Manages sending data to your bot. **Send Data to Bot** The bot will receive this as a web_app_data message in the chat. ``` javascript const orderData = { productId: 'item-123', quantity: 2, timestamp: new Date().toISOString() }; // The library automatically stringifies the object tgBinder.MessagingData(orderData); ``` ## UI Module (tgBinder.ui) Controls native Telegram UI elements. **Request User's Phone Number** This method configures the MainButton to ask for the user's contact information. ``` javascript tgBinder.ui.requestContact({ text: "Share Contact to Proceed", onSuccess: (granted) => { console.log('Contact access request sent!', granted); // true // The bot will receive the contact information }, onFailure: () => { console.log('User denied contact access.'); } }); ``` **Trigger Haptic Feedback** Provide tactile feedback for user actions. ``` javascript // For light taps (e.g., selecting an option) tgBinder.ui.impactOccurred('light'); // For notifications (e.g., action completed successfully) tgBinder.ui.notificationOccurred('success'); // For errors tgBinder.ui.notificationOccurred('error'); ``` ## Links Module (tgBinder.links) Handles opening other Telegram links. **Open Another Mini App or a Telegram Link** You can use this to navigate between different Mini Apps or to a user's profile. ``` javascript // URL to another bot's Mini App const anotherAppUrl = 'https://t.me/notcoin_bot'; // Example with Notcoin tgBinder.links.openTelegramLink(anotherAppUrl); ``` **Open a Payment Invoice** Open an invoice link generated by your bot. ``` javascript const invoiceUrl = 'https://t.me/invoice/your_invoice_payload'; tgBinder.links.openInvoice(invoiceUrl, (status) => { // This callback is fired when the invoice is closed console.log(`Invoice closed with status: ${status}`); // 'paid', 'cancelled', 'failed', 'pending' }); ``` ## 🔧 Mock Mode for Development When you run your web app in a regular browser (not inside Telegram), the library automatically enters mock mode. All function calls will be logged to the console instead of throwing errors. This allows you to develop and test your app's UI and logic without needing to constantly deploy to a server. ``` javascript // Console output when running in a normal browser: [Mock Mode] Mock App Ready [Mock Mode] Mock Haptic Impact: medium [Mock Mode] Mock opening Telegram link: https://t.me/notcoin_bot ``` ## 🤝 Contributing Contributions, issues, and feature requests are welcome! Feel free to check the issues page for this project. ## author y0red ## 📄 License This project is MIT licensed.