Developing a Telegram Mini App with Bitrix24 Integration
Integrating a Telegram Mini App with Bitrix24 differs from integrating with 1C-Bitrix in that the primary transport here is the Bitrix24 REST API rather than custom PHP endpoints. Bitrix24 provides a full-featured REST interface with OAuth, webhooks, and events. A typical scenario: a corporate mini-portal or CRM tool directly inside Telegram — an employee can accept a lead, change a deal stage, or review tasks without opening a browser.
Use Cases
The most in-demand scenarios:
- Mobile CRM dashboard — browse leads/deals, change status, add comments directly from Telegram
- Corporate ordering — employees of an external network (dealers, agents) submit requests via Mini App, which land in Bitrix24 CRM
- Self-service portal — the client views the status of their requests and interaction history
- Task manager — employee task list, status changes, file attachments
Authorization: Bitrix24 OAuth from the Mini App
The Bitrix24 REST API requires an OAuth 2.0 access_token. A direct OAuth flow from a Mini App is problematic (no browser redirects), so authorization is handled through a proxy server.
Flow:
Telegram → Mini App opens
→ Mini App sends initData to our proxy server
→ Server validates initData, identifies Telegram user_id
→ Looks up a linked Bitrix24 access_token for that user_id
→ If found → returns a JWT for the Mini App
→ If not found → returns a link to Bitrix24 OAuth authorization
Initial Telegram ↔ Bitrix24 account linking:
// OAuth callback controller
class Bx24OAuthController
{
public function callback(Request $request): Response
{
$code = $request->get('code');
$tgUserId = $request->session()->get('pending_tg_user_id');
// Exchange code for token
$tokenData = $this->exchangeCode($code);
// Save token linked to Telegram user_id
\Local\TgBx24\TokenStorage::save($tgUserId, [
'access_token' => $tokenData['access_token'],
'refresh_token' => $tokenData['refresh_token'],
'expires_at' => time() + $tokenData['expires_in'],
'domain' => $tokenData['domain'],
'user_id' => $tokenData['user_id'],
]);
// Notify the bot that authorization succeeded
$this->bot->sendMessage($tgUserId, 'Bitrix24 authorization completed successfully.');
return redirect('/auth/success');
}
private function exchangeCode(string $code): array
{
$response = Http::post('https://oauth.bitrix.info/oauth/token/', [
'grant_type' => 'authorization_code',
'client_id' => config('bx24.client_id'),
'client_secret' => config('bx24.client_secret'),
'code' => $code,
]);
return $response->json();
}
}
Token storage — in a dedicated table or Redis:
class TokenStorage
{
private const TABLE = 'tg_bx24_tokens';
public static function save(int $tgUserId, array $tokenData): void
{
// Encrypt tokens before writing to the database
$encrypted = \Local\Crypto::encrypt(json_encode($tokenData));
\Bitrix\Main\Application::getConnection()->queryExecute(
"INSERT INTO " . self::TABLE . " (tg_user_id, token_data, updated_at)
VALUES (?, ?, NOW())
ON DUPLICATE KEY UPDATE token_data = ?, updated_at = NOW()",
[$tgUserId, $encrypted, $encrypted]
);
}
public static function getValidToken(int $tgUserId): ?array
{
$result = \Bitrix\Main\Application::getConnection()->query(
"SELECT token_data FROM " . self::TABLE . " WHERE tg_user_id = ?",
[$tgUserId]
);
$row = $result->fetch();
if (!$row) return null;
$data = json_decode(\Local\Crypto::decrypt($row['token_data']), true);
// Refresh an expired token
if ($data['expires_at'] < time() + 300) {
$data = self::refreshToken($data);
}
return $data;
}
private static function refreshToken(array $data): array
{
$response = \Bitrix\Main\Web\HttpClient::post(
'https://oauth.bitrix.info/oauth/token/',
[
'grant_type' => 'refresh_token',
'client_id' => \Bitrix\Main\Config\Option::get('local.tg_bx24', 'client_id'),
'client_secret' => \Bitrix\Main\Config\Option::get('local.tg_bx24', 'client_secret'),
'refresh_token' => $data['refresh_token'],
]
);
// update data, save, return
return $newData;
}
}
Mini App: Employee CRM Dashboard
React frontend with the Telegram WebApp SDK:
import { useEffect, useState } from 'react';
const tg = window.Telegram.WebApp;
interface Deal {
ID: string;
TITLE: string;
OPPORTUNITY: string;
STAGE_ID: string;
CONTACT_NAME: string;
}
function CrmDashboard() {
const [deals, setDeals] = useState<Deal[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
tg.ready();
tg.expand();
loadDeals();
}, []);
async function loadDeals() {
const res = await fetch('/tg-api/crm/deals', {
headers: { 'X-Tg-Init-Data': tg.initData },
});
const data = await res.json();
setDeals(data.deals);
setLoading(false);
}
async function updateStage(dealId: string, stageId: string) {
await fetch(`/tg-api/crm/deals/${dealId}/stage`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-Tg-Init-Data': tg.initData,
},
body: JSON.stringify({ stage_id: stageId }),
});
tg.HapticFeedback.notificationOccurred('success');
loadDeals();
}
// ... render
}
Server-side proxy to the Bitrix24 REST API:
class CrmDealsProxy
{
public function getDeals(int $tgUserId): array
{
$tokenData = TokenStorage::getValidToken($tgUserId);
if (!$tokenData) {
throw new \RuntimeException('Not authorized', 401);
}
$bx24 = new \Local\TgBx24\Bx24Client($tokenData['access_token'], $tokenData['domain']);
$result = $bx24->call('crm.deal.list', [
'filter' => ['ASSIGNED_BY_ID' => $tokenData['user_id'], 'CLOSED' => 'N'],
'select' => ['ID', 'TITLE', 'OPPORTUNITY', 'STAGE_ID', 'CONTACT_ID'],
'order' => ['DATE_MODIFY' => 'DESC'],
'start' => 0,
]);
return $result['result'] ?? [];
}
public function updateDealStage(int $tgUserId, int $dealId, string $stageId): bool
{
$tokenData = TokenStorage::getValidToken($tgUserId);
$bx24 = new \Local\TgBx24\Bx24Client($tokenData['access_token'], $tokenData['domain']);
$result = $bx24->call('crm.deal.update', [
'id' => $dealId,
'fields' => ['STAGE_ID' => $stageId],
]);
return !empty($result['result']);
}
}
Bot Notifications on Bitrix24 Events
For notifications, we use Bitrix24 event webhooks. For example, when a lead status changes — a message is sent to the responsible employee:
// Handler for incoming Bitrix24 events
class EventHandler
{
public function handleLeadUpdate(array $event): void
{
$leadId = $event['data']['FIELDS_AFTER']['ID'];
$assignee = $event['data']['FIELDS_AFTER']['ASSIGNED_BY_ID'];
// Look up tg_user_id by bx24 user_id
$tgUserId = $this->findTelegramUser($assignee);
if (!$tgUserId) return;
$statusName = $this->getLeadStatusName($event['data']['FIELDS_AFTER']['STATUS_ID']);
$this->bot->sendMessage($tgUserId,
"Lead #{$leadId} updated\nNew status: {$statusName}\n" .
"[Open in Mini App](https://t.me/" . BOT_USERNAME . "/crm?start=lead_{$leadId})",
['parse_mode' => 'Markdown']
);
}
}
Scope of Work
- Register the Bitrix24 application (OAuth), configure the Mini App in @BotFather
- Proxy server: Telegram initData validation, OAuth token storage
- React Mini App: tailored to the specific scenario (CRM / tasks / requests)
- REST proxy to the Bitrix24 API with token refresh
- Bitrix24 event webhooks → Telegram notifications
- Initial setup: user onboarding, account linking
Timeline: MVP for a single scenario (e.g., deals dashboard) — 3–5 weeks. Full-featured tool with multiple sections — 8–14 weeks.







