Many developers, when sending leads from a website to Telegram, limit themselves to simply forwarding message text to a manager chat. However, as sales volume grows, this approach quickly leads to chaos: managers interrupt each other, take the same clients, or miss new requests. A native way to solve this problem is to send the request with an interactive Inline button "Take to work" directly in Telegram.
In this article, we will build a reliable PHP scenario: from generating a cryptographically secure request identifier and saving it to PostgreSQL/MySQL to correctly handling a Webhook taking into account race conditions and strict Telegram Bot API limits.
Workflow and Data Structure
The general interaction algorithm consists of two key phases:
- Phase 1 (Website → DB → Telegram): the user submits a form on the website. The PHP script generates a short unique
lead_id, saves the request to the database with the statusnew, and sends a message to the sales department chat with an Inline button attached. - Phase 2 (Telegram → Webhook → DB → Telegram): a manager clicks the button in the chat. Telegram sends a
callback_queryto your Webhook. The server atomically updates the lead status in the DB, responds to the click viaanswerCallbackQuery, and edits the original message text in the chat viaeditMessageText.
Generating lead_id and Sending the Request to Chat
To create short and unique lead identifiers, you should not use auto-increment IDs from the DB (this reveals sales volume to competitors) or cumbersome UUIDv4s (they are too long for the strict callback_data limit). 7 random bytes converted to a 14-character hex string are ideal:
$leadId = bin2hex(random_bytes(7)); // Ровно 14 символов, например "a3f81c9b20e4d1"Below is a working form processing script, process_lead.php. It receives form data, creates a record in the DB, and executes a secure request to the Telegram API via cURL.
<?php
declare(strict_types=1);
// 1. Чтение конфигурации из окружения
$botToken = getenv('TELEGRAM_BOT_TOKEN') ?: '';
$chatId = getenv('TELEGRAM_MANAGERS_CHAT_ID') ?: '';
if (!$botToken || !$chatId) {
http_response_code(500);
exit(json_encode(['error' => 'Server configuration error']));
}
// 2. Валидация входных данных формы
$name = trim($_POST['name'] ?? '');
$phone = trim($_POST['phone'] ?? '');
if ($name === '' || $phone === '') {
http_response_code(400);
exit(json_encode(['error' => 'Не заполнены обязательные поля']));
}
// 3. Подключение к БД и генерация lead_id
$pdo = new PDO('mysql:host=localhost;dbname=crm;charset=utf8mb4', 'db_user', 'db_password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$leadId = bin2hex(random_bytes(7));
$stmt = $pdo->prepare("
INSERT INTO leads (id, name, phone, status, created_at)
VALUES (:id, :name, :phone, 'new', NOW())
");
$stmt->execute([
':id' => $leadId,
':name' => $name,
':phone' => $phone,
]);
// 4. Формирование сообщения и Inline-клавиатуры
// callback_data: "take:a3f81c9b20e4d1" (19 байт из 64 допустимых)
$messageText = sprintf(
"<b>Новая заявка с сайта!</b>
<b>ID:</b> %s
<b>Имя:</b> %s
<b>Телефон:</b> %s",
htmlspecialchars($leadId, ENT_QUOTES, 'UTF-8'),
htmlspecialchars($name, ENT_QUOTES, 'UTF-8'),
htmlspecialchars($phone, ENT_QUOTES, 'UTF-8')
);
$payload = [
'chat_id' => $chatId,
'text' => $messageText,
'parse_mode' => 'HTML',
'reply_markup' => [
'inline_keyboard' => [
[
[
'text' => '🔒 Взять в работу',
'callback_data' => 'take:' . $leadId,
]
]
]
]
];
// 5. Отправка cURL запроса к Telegram API
$ch = curl_init('https://api.telegram.org/bot' . $botToken . '/sendMessage');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_TIMEOUT => 5,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($response === false) {
error_log("cURL Error while sending lead {$leadId}: " . $curlError);
http_response_code(500);
exit(json_encode(['error' => ' Ошибка отправки сообщения']));
}
$result = json_decode($response, true);
if ($httpCode !== 200 || json_last_error() !== JSON_ERROR_NONE || empty($result['ok'])) {
error_log("Telegram API Error for lead {$leadId}: " . $response);
http_response_code(502);
exit(json_encode(['error' => 'Ошибка взаимодействия с Telegram']));
}
echo json_encode(['success' => true, 'lead_id' => $leadId]);
Processing Callback Query on Webhook
When a manager clicks a button in the chat, Telegram sends a request to your Webhook handler. At this stage, you need to implement three mandatory security mechanisms:
- Secret Token Verification: confirmation that the request actually came from Telegram (header
X-Telegram-Bot-Api-Secret-Token). - Deduplication (Idempotency): protection against processing the same
update_idmultiple times during retries from Telegram. - Atomic UPDATE in the DB: eliminating the race condition where two managers simultaneously click the button on different devices.
Below is the code for the handler telegram_webhook.php:
<?php
declare(strict_types=1);
$botToken = getenv('TELEGRAM_BOT_TOKEN') ?: '';
$secretToken = getenv('TELEGRAM_SECRET_TOKEN') ?: '';
// 1. Проверка Secret Token
$receivedToken = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
if ($secretToken === '' || !hash_equals($secretToken, $receivedToken)) {
http_response_code(403);
exit('Unauthorized');
}
// 2. Парсинг сырого JSON
$rawInput = file_get_contents('php://input');
$update = json_decode($rawInput, true);
if (json_last_error() !== JSON_ERROR_NONE || !isset($update['update_id'])) {
http_response_code(400);
exit('Invalid payload');
}
$pdo = new PDO('mysql:host=localhost;dbname=crm;charset=utf8mb4', 'db_user', 'db_password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
// 3. Проверка идемпотентности по update_id
$updateId = (int)$update['update_id'];
$stmt = $pdo->prepare("INSERT IGNORE INTO processed_updates (update_id, created_at) VALUES (?, NOW())");
$stmt->execute([$updateId]);
if ($stmt->rowCount() === 0) {
// Данный update_id уже был успешно обработан ранее
http_response_code(200);
exit('Already processed');
}
// 4. Обработка callback_query
if (isset($update['callback_query'])) {
$cb = $update['callback_query'];
$callbackId = $cb['id'];
$chatId = $cb['message']['chat']['id'] ?? null;
$messageId = $cb['message']['message_id'] ?? null;
$managerData = $cb['from'];
$data = $cb['data'] ?? '';
if (str_istartswith($data, 'take:')) {
$leadId = substr($data, 5);
$managerName = trim(($managerData['first_name'] ?? '') . ' ' . ($managerData['last_name'] ?? ''));
$managerText = $managerName !== '' ? $managerName : ('ID: ' . $managerData['id']);
// Атомарный UPDATE для защиты от гонки условий
$updateStmt = $pdo->prepare("
UPDATE leads
SET status = 'taken', manager_id = :manager_id, taken_at = NOW()
WHERE id = :id AND status = 'new'
");
$updateStmt->execute([
':manager_id' => $managerData['id'],
':id' => $leadId,
]);
$isSuccess = $updateStmt->rowCount() > 0;
// Вспомогательная функция для вызова Telegram API через cURL
$telegramApi = function (string $method, array $params) use ($botToken) {
$ch = curl_init("https://api.telegram.org/bot{$botToken}/{$method}");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($params),
CURLOPT_TIMEOUT => 5,
]);
$res = curl_exec($ch);
curl_close($ch);
return $res;
};
if ($isSuccess) {
// Вплывающее уведомление пользователю
$telegramApi('answerCallbackQuery', [
'callback_query_id' => $callbackId,
'text' => 'Заявка успешно закреплена за вами!',
'show_alert' => false,
]);
// Обновляем текст сообщения, меняем кнопку
$oldText = $cb['message']['text'] ?? '';
$newText = $oldText . "
✅ <b>Взял в работу:</b> " . htmlspecialchars($managerText, ENT_QUOTES, 'UTF-8');
$telegramApi('editMessageText', [
'chat_id' => $chatId,
'message_id' => $messageId,
'text' => $newText,
'parse_mode' => 'HTML',
'reply_markup' => ['inline_keyboard' => []] // Удаляем кнопку
]);
} else {
// Заявка уже была взята кем-то другим
$telegramApi('answerCallbackQuery', [
'callback_query_id' => $callbackId,
'text' => '⚠️ Заявку уже взял другой менеджер!',
'show_alert' => true,
]);
}
}
}
// Всегда возвращаем HTTP 200 OK для Telegram
http_response_code(200);
echo 'OK';
callback_data Limits and Payload Compression
The Telegram Bot API imposes a strict limitation: the callback_data parameter in an Inline button cannot exceed 64 bytes. Attempting to pass a long JSON or large string into it will result in a 400 Bad Request: BUTTON_DATA_INVALID error.
Let's calculate the size of our string:
- Action prefix:
take:— 5 bytes. - The
lead_idvalue (14 hex characters frombin2hex(random_bytes(7))) — 14 bytes. - Total: 19 bytes.
This leaves a buffer of 45 bytes, allowing you to pass an additional argument if needed (e.g., take:a3f81c9b20e4d1:fast) without the risk of exceeding the API limit.
Never store sensitive data (customer phone numbers, tokens) inside callback_data. Inline buttons should only contain identifiers that reference records in your database.Common Integration Pitfalls
- Using file_get_contents to call the API: the
file_get_contentsfunction does not allow for flexible timeout configuration, reading HTTP response codes, or properly handling Telegram's 4xx/5xx errors. Use cURL. - Missing answerCallbackQuery call: if you do not call this method in response to a
callback_query, the user's button will show a continuous loading spinner, and Telegram may consider your webhook unstable. - Ignoring Race Conditions: checking the status via
SELECTfollowed by anUPDATEin two separate SQL queries will allow two managers to take the same lead simultaneously. Use an atomicUPDATE ... WHERE status = 'new'.
If you need professional development of complex bots or integration of a website with Telegram Mini Apps, the BotCreator team will help you implement a turnkey solution.