When building an e-commerce catalog inside a Telegram Mini App using Vue 3, frontend state management requires a fundamental shift from traditional web apps. Telegram runs Mini Apps inside an embedded webview framework across iOS, Android, and Desktop clients. Mobile operating systems aggressively suspend or completely dispose of these webview contexts when a user toggles to another chat, answers an incoming call, or opens a native Telegram payment interface.

If your Vue application relies solely on an in-memory Pinia store for cart management, a webview reload flushes the customer's selected items immediately. The customer returns to an empty cart or, worse, triggers a checkout with a stale or zero-value payload. Furthermore, binding payment actions directly to Telegram's native MainButton without strict lifecycle hooks leads to duplicate event handlers, where a single tap issues multiple backend invoice requests.

In this guide, we will implement a resilient Vue 3 e-commerce catalog featuring a persistent Pinia store, synchronized Telegram native MainButton controls, and a secure checkout pipeline that passes initData to a backend server before calling Telegram's openInvoice API.

Synchronizing Pinia Cart State with Telegram LocalStorage and WebApp Viewport

A naive implementation of a Vue 3 cart store keeps state in reactive refs or Pinia properties. When Telegram reloads the webview or updates the viewport, those refs reset to their initial empty values. To preserve state across webview lifecycle interruptions, every store mutation must sync with localStorage, while validating item schemas to prevent corruption if product prices or IDs change on the backend.

We also need to initialize Telegram's WebApp SDK cleanly before rendering component tree nodes. Calling window.Telegram.WebApp.ready() and window.Telegram.WebApp.expand() guarantees that the viewport fills the user's screen before Pinia attempts to calculate UI bounds or calculate layout heights.

Here is the production-ready Pinia cart store that persists items to local storage, handles quantity calculations, and exposes computed getters for total amounts in cents:

import { defineStore } from 'pinia'; const STORAGE_KEY = 'tg_app_cart_v1'; export const useCartStore = defineStore('cart', { state: () => ({ items: JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'), isProcessing: false, }), getters: { totalCount: (state) => state.items.reduce((sum, item) => sum + item.quantity, 0), totalAmountCents: (state) => { return state.items.reduce((sum, item) => sum + item.priceCents * item.quantity, 0); }, formattedTotal: (state) => { const total = state.items.reduce((sum, item) => sum + (item.priceCents * item.quantity), 0); return (total / 100).toFixed(2); } }, actions: { addItem(product) { const existing = this.items.find(i => i.id === product.id); if (existing) { existing.quantity += 1; } else { this.items.push({ id: product.id, title: product.title, priceCents: product.priceCents, quantity: 1 }); } this.persist(); }, removeItem(productId) { const index = this.items.findIndex(i => i.id === productId); if (index !== -1) { if (this.items[index].quantity > 1) { this.items[index].quantity -= 1; } else { this.items.splice(index, 1); } this.persist(); } }, clearCart() { this.items = []; this.persist(); }, persist() { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(this.items)); } catch (e) { console.error('Failed to save cart to localStorage', e); } } } }); 

With this store in place, refreshing the Telegram webview preserves user selections. However, syncing local state is only half the battle. We must now bind this state to Telegram's native MainButton without creating dangling event listeners.

Building the Product Catalog Component with Native Telegram MainButton Integration

In a Telegram Mini App, web designers often replace or supplement web-based action buttons with Telegram's native MainButton. The MainButton floats at the bottom of the client window, providing a native look and feel.

The primary pitfall with MainButton in Vue 3 is handler duplication. If you call Telegram.WebApp.MainButton.onClick(callback) inside a component setup function or onMounted hook without unregistering it in onUnmounted, switching routes or re-mounting the catalog component attaches additional click listeners. When the user taps "Pay", the handler fires multiple times simultaneously, creating duplicate payment requests on your server.

To fix this, we encapsulate MainButton behavior inside the component lifecycle. We attach the click handler on mount, update its text and visibility whenever Pinia cart totals change using Vue watchers, and explicitly detach the event listener using offClick when the component unmounts.

Here is the CatalogView.vue component demonstrating clean MainButton lifecycle binding and product rendering:

<template> <div class="catalog-container"> <h1>Hardware Catalog</h1> <div class="product-grid"> <div v-for="product in products" :key="product.id" class="product-card"> <h3>{{ product.title }}</h3> <p class="price">${{ (product.priceCents / 100).toFixed(2) }}</p> <div class="controls"> <button @click="cart.removeItem(product.id)">-</button> <span>{{ getItemQuantity(product.id) }}</span> <button @click="cart.addItem(product)">+</button> </div> </div> </div> </div> </template> <script setup> import { ref, watch, onMounted, onUnmounted } from 'vue'; import { useCartStore } from '../stores/cart'; import { useCheckout } from '../composables/useCheckout'; const cart = useCartStore(); const { startCheckout } = useCheckout(); const products = ref([ { id: 'p1', title: 'YubiKey 5 NFC', priceCents: 5500 }, { id: 'p2', title: 'Hardware Wallet', priceCents: 14900 }, { id: 'p3', title: 'Encrypted Drive 1TB', priceCents: 21000 } ]); function getItemQuantity(id) { const item = cart.items.find(i => i.id === id); return item ? item.quantity : 0; } const handleMainButtonClick = () => { if (cart.totalCount > 0 && !cart.isProcessing) { startCheckout(); } }; const updateMainButton = () => { const tg = window.Telegram?.WebApp; if (!tg || !tg.MainButton) return; if (cart.totalCount > 0) { tg.MainButton.setText(`CHECKOUT ($${cart.formattedTotal})`); tg.MainButton.show(); tg.MainButton.enable(); } else { tg.MainButton.hide(); } }; watch(() => cart.totalCount, () => { updateMainButton(); }); onMounted(() => { const tg = window.Telegram?.WebApp; if (tg) { tg.ready(); tg.expand(); tg.MainButton.onClick(handleMainButtonClick); updateMainButton(); } }); onUnmounted(() => { const tg = window.Telegram?.WebApp; if (tg) { tg.MainButton.offClick(handleMainButtonClick); } }); </script> 

By maintaining strict control over MainButton.onClick and MainButton.offClick, we ensure that tapping the button executes exactly one checkout operation.

Executing Secure Checkouts via Backend Pre-Validation and WebApp openInvoice

A common architectural mistake in Telegram Mini Apps is relying on Telegram.WebApp.sendData() for multi-item checkouts. sendData() closes the Mini App webview immediately and sends a string back to the bot via a service message. This approach has critical drawbacks: it fails if the payload exceeds Telegram's size constraints, cannot open native Telegram Stars or third-party payment gateways directly, and yields an awkward user experience by closing the webview before payment verification completes.

The correct production architecture follows a three-step pattern:

  1. The Vue frontend sends the cart payload along with Telegram.WebApp.initData to your backend API.
  2. The backend verifies the initData HMAC signature using your Telegram Bot Token to ensure the user ID and session are legitimate. It then generates a Telegram Bot API invoice link via createInvoiceLink.
  3. The backend returns the invoice URL to Vue, which calls window.Telegram.WebApp.openInvoice(invoiceUrl, callback).

Below is the checkout composable handling the backend invocation and native invoice popup:

import { useCartStore } from '../stores/cart'; export function useCheckout() { const cart = useCartStore(); const startCheckout = async () => { const tg = window.Telegram?.WebApp; if (!tg) { alert('Telegram WebApp context unavailable.'); return; } cart.isProcessing = true; tg.MainButton.showProgress(); try { const response = await fetch('/api/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ initData: tg.initData, items: cart.items.map(i => ({ id: i.id, quantity: i.quantity })) }) }); const data = await response.json(); if (!response.ok || !data.invoiceUrl) { throw new Error(data.error || 'Failed to generate checkout invoice.'); } tg.MainButton.hideProgress(); tg.openInvoice(data.invoiceUrl, (status) => { cart.isProcessing = false; if (status === 'paid') { cart.clearCart(); tg.MainButton.hide(); tg.showAlert('Payment successful! Your order is being processed.'); } else if (status === 'cancelled') { tg.showAlert('Payment was cancelled.'); updateButtonState(tg, cart); } else { tg.showAlert(`Payment status: ${status}`); updateButtonState(tg, cart); } }); } catch (err) { console.error('Checkout error:', err); tg.MainButton.hideProgress(); cart.isProcessing = false; tg.showAlert(err.message || 'An error occurred during checkout.'); } }; const updateButtonState = (tg, cart) => { if (cart.totalCount > 0) { tg.MainButton.enable(); tg.MainButton.show(); } }; return { startCheckout }; } 

Now, here is the backend server handler in Node.js/Express that validates the raw initData string before talking to Telegram's API. Never trust item prices sent from the client—look up product prices from your backend database:

const express = require('express'); const crypto = require('crypto'); const app = express(); app.use(express.json()); const BOT_TOKEN = process.env.BOT_TOKEN; const DB_PRODUCTS = { p1: { title: 'YubiKey 5 NFC', priceCents: 5500 }, p2: { title: 'Hardware Wallet', priceCents: 14900 }, p3: { title: 'Encrypted Drive 1TB', priceCents: 21000 } }; function verifyInitData(initData) { if (!initData) return false; const urlParams = new URLSearchParams(initData); const hash = urlParams.get('hash'); urlParams.delete('hash'); const params = Array.from(urlParams.entries()) .map(([key, val]) => `${key}=${val}`) .sort() .join('\n'); const secretKey = crypto.createHmac('sha256', 'WebAppData').update(BOT_TOKEN).digest(); const calculatedHash = crypto.createHmac('sha256', secretKey).update(params).digest('hex'); return calculatedHash === hash; } app.post('/api/checkout', async (req, res) => { const { initData, items } = req.body; if (!verifyInitData(initData)) { return res.status(401).json({ error: 'Invalid or spoofed Telegram session.' }); } if (!Array.isArray(items) || items.length === 0) { return res.status(400).json({ error: 'Cart is empty.' }); } const prices = []; for (const item of items) { const dbProduct = DB_PRODUCTS[item.id]; if (!dbProduct) { return res.status(400).json({ error: `Invalid product ID: ${item.id}` }); } prices.push({ label: `${dbProduct.title} x${item.quantity}`, amount: dbProduct.priceCents * item.quantity }); } try { const tgRes = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/createInvoiceLink`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Store Checkout', description: 'Payment for hardware catalog order', payload: JSON.stringify({ orderId: `ord_${Date.now()}` }), provider_token: process.env.PAYMENT_PROVIDER_TOKEN || '', currency: 'USD', prices: prices }) }); const tgData = await tgRes.json(); if (!tgData.ok) { return res.status(500).Source:https://dev.to/serhii_a9c08345ac360cf5c8/prevent-abandoned-payments-and-cart-state-loss-in-vue-3-telegram-mini-apps-2mkm

Related posts