Developing a Telegram Mini App with 1C-Bitrix Integration
A Telegram Mini App is a web application that opens inside Telegram via the WebApp API. Architecturally, it is a standard SPA (React/Vue/Vanilla JS) running in the Telegram context: the window.Telegram.WebApp object is available, through which the application receives user data, color scheme, and session information. For an online store built on 1C-Bitrix, this type of application lets you bring the catalog, shopping cart, and checkout directly into the messenger without requiring a separate mobile app installation.
Architecture: What Lives Where
Telegram Client
└─ Mini App (React SPA)
└─ HTTPS requests → Bitrix API (REST or custom endpoints)
└─ Telegram initData validation
└─ Business logic: catalog, cart, orders
The Mini App has no direct database access — everything goes through the API. Bitrix acts as the backend, providing JSON responses. User authentication is handled via initData from the Telegram WebApp (HMAC-SHA256 signature using the bot's secret token).
Initialization and initData Validation
When the Mini App opens, the window.Telegram.WebApp object contains initData — a string with user data and a hash. This string must be sent to the server with every request and validated.
On the Mini App side (React):
import { useEffect, useState } from 'react';
const tg = window.Telegram.WebApp;
export function useTelegramAuth() {
const [token, setToken] = useState<string | null>(null);
useEffect(() => {
tg.ready();
tg.expand();
const initData = tg.initData;
if (!initData) return;
// Send initData to server in exchange for a JWT token
fetch('/api/telegram/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ init_data: initData }),
})
.then(r => r.json())
.then(data => setToken(data.token));
}, []);
return { token, user: tg.initDataUnsafe?.user };
}
On the Bitrix side — signature validation:
// /local/api/telegram/auth.php
namespace Local\TelegramMiniApp;
class InitDataValidator
{
private string $botToken;
public function __construct(string $botToken)
{
$this->botToken = $botToken;
}
public function validate(string $initData): bool
{
parse_str($initData, $params);
$hash = $params['hash'] ?? '';
unset($params['hash']);
// Sort keys, build data-check-string
ksort($params);
$dataCheckString = implode("\n", array_map(
fn($k, $v) => "$k=$v",
array_keys($params),
array_values($params)
));
// Secret: HMAC-SHA256 of bot token with key "WebAppData"
$secretKey = hash_hmac('sha256', $this->botToken, 'WebAppData', true);
$expected = hash_hmac('sha256', $dataCheckString, $secretKey);
// Validate timestamp (not older than 24 hours)
$authDate = (int)($params['auth_date'] ?? 0);
if (time() - $authDate > 86400) {
return false;
}
return hash_equals($expected, $hash);
}
public function extractUser(string $initData): ?array
{
parse_str($initData, $params);
return json_decode($params['user'] ?? '{}', true);
}
}
Linking a Telegram User to Bitrix
On first login via the Mini App, the Telegram user_id must be mapped to a customer in Bitrix. The logic:
class TelegramUserResolver
{
public function resolveOrCreate(array $tgUser): int
{
$tgId = (int)$tgUser['id'];
// Search user by custom field
$result = \CUser::GetList(
($by = 'ID'),
($order = 'ASC'),
['UF_TELEGRAM_ID' => $tgId],
['FIELDS' => ['ID']]
);
if ($row = $result->Fetch()) {
return (int)$row['ID'];
}
// Create new user
$user = new \CUser();
$userId = $user->Add([
'LOGIN' => 'tg_' . $tgId,
'NAME' => $tgUser['first_name'] ?? '',
'LAST_NAME' => $tgUser['last_name'] ?? '',
'PASSWORD' => md5(uniqid('', true) . $tgId),
'CONFIRM_PASSWORD' => md5(uniqid('', true) . $tgId),
'ACTIVE' => 'Y',
'GROUP_ID' => [2], // "Customers" group
'UF_TELEGRAM_ID' => $tgId,
]);
return (int)$userId;
}
}
API Endpoints for the Mini App
Catalog, cart, and orders — via custom REST handlers in Bitrix. Register routes:
// /local/routes/telegram.php — included from init.php
\Bitrix\Main\Routing\Router::getInstance()
->get('/api/telegram/catalog', [\Local\TelegramMiniApp\CatalogController::class, 'index'])
->get('/api/telegram/catalog/{id}', [\Local\TelegramMiniApp\CatalogController::class, 'show'])
->post('/api/telegram/cart/add', [\Local\TelegramMiniApp\CartController::class, 'add'])
->get('/api/telegram/cart', [\Local\TelegramMiniApp\CartController::class, 'index'])
->post('/api/telegram/order', [\Local\TelegramMiniApp\OrderController::class, 'create']);
Catalog via Highload API or \CIBlockElement:
class CatalogController
{
public function index(Request $request): JsonResponse
{
$elements = \CIBlockElement::GetList(
['SORT' => 'ASC'],
['IBLOCK_ID' => CATALOG_IBLOCK_ID, 'ACTIVE' => 'Y'],
false,
['nPageSize' => 20, 'iNumPage' => (int)$request->get('page', 1)],
['ID', 'NAME', 'PREVIEW_TEXT', 'PREVIEW_PICTURE', 'PROPERTY_PRICE', 'PROPERTY_ARTICLE']
);
$items = [];
while ($row = $elements->GetNextElement()) {
$fields = $row->GetFields();
$props = $row->GetProperties();
$items[] = [
'id' => (int)$fields['ID'],
'name' => $fields['NAME'],
'text' => $fields['PREVIEW_TEXT'],
'image' => \CFile::GetPath($fields['PREVIEW_PICTURE']),
'price' => (float)($props['PRICE']['VALUE'] ?? 0),
];
}
return new JsonResponse(['items' => $items]);
}
}
Payment via Telegram Payments
Telegram supports built-in payments through providers (YooKassa, Stripe, etc.). To initiate a payment from the Mini App:
// In the Mini App after the order is formed
async function initiatePayment(orderId: number) {
// Request invoice_link from the server
const res = await fetch('/api/telegram/payment/invoice', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify({ order_id: orderId }),
});
const { invoice_url } = await res.json();
// Open the Telegram payment page
tg.openInvoice(invoice_url, (status) => {
if (status === 'paid') {
// Notify the server, update order status
confirmPayment(orderId);
}
});
}
On the Bitrix side — creating an invoice via the Bot API:
public function createInvoice(int $orderId, int $bitrixUserId): string
{
$order = \Bitrix\Sale\Order::load($orderId);
$response = $this->botApiPost('createInvoiceLink', [
'title' => 'Order #' . $orderId,
'description' => 'Payment for order ' . $order->getField('ACCOUNT_NUMBER'),
'payload' => json_encode(['order_id' => $orderId, 'user_id' => $bitrixUserId]),
'provider_token' => PAYMENT_PROVIDER_TOKEN, // YooKassa token in Telegram
'currency' => 'RUB',
'prices' => [['label' => 'Total', 'amount' => (int)($order->getPrice() * 100)]],
]);
return $response['result']; // invoice_link
}
Scope of Work
- Bot registration, Mini App setup via @BotFather
- React application: catalog, product card, cart, checkout
- initData validation on the Bitrix side
- Linking a Telegram user to a customer in Bitrix
- REST API: catalog, cart, orders, statuses
- (Optional) Telegram Payments integration for one-tap checkout
- Customer notifications via bot: order status updates
Timeline: MVP (catalog + cart + order) — 4–6 weeks. Full version with payments and notifications — 8–12 weeks.







