Website Leads to Telegram via PHP: lead_id, Inline Buttons, and Race Condition Protection

Instant notification of managers about new website leads via Telegram is a modern sales standard. However, simply sending plain text with contact details quickly turns into chaos: employees claim the same leads, argue over who grabbed a lead first, or miss messages entirely. A native solution is sending a message with an Inline button "Claim lead".

In this article, we will implement a lead processing architecture in PHP: from generating a unique lead_id based on random_bytes() to a secure callback_query Webhook handler protected against race conditions and strictly within the constraints of Telegram Bot API.

System Architecture and Telegram Bot API Limits

The integration consists of two isolated parts:

  1. Website form handler script: receives a POST request, generates a cryptographically secure lead_id, records an entry in the MySQL/PostgreSQL database with the status new, and sends the lead card to the general sales team chat via cURL.
  2. Bot response Webhook handler: receives callback_data button clicks from managers, verifies security headers, guarantees idempotency, and atomically updates the lead status in the database.
The main technical limitation when working with Inline buttons is that the callback_data field in InlineKeyboardButton is strictly limited to 64 bytes in length. Attempting to pass a long JSON string or a UUIDv4 with additional metadata will trigger a Telegram API error.

Using bin2hex(random_bytes(7)) yields exactly 14 hexadecimal characters (7 bytes of entropy). Combined with a command prefix (for example, take:), the prefix + ID takes up only 19 bytes, staying well within the strict API limit.

Step 1. Website Form Processing and Lead Saving

To prevent forgery and duplicates, let's create a leads table with the following minimal structure:

CREATE TABLE leads (
id INT AUTO_INCREMENT PRIMARY KEY,
lead_id VARCHAR(14) NOT NULL UNIQUE,
name VARCHAR(255) NOT NULL,
phone VARCHAR(50) NOT NULL,
status ENUM('new', 'in_progress', 'done') NOT NULL DEFAULT 'new',
manager_tg_id BIGINT NULL,
created_at DATETIME NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Below is a working PHP script that processes a POST request from a website form. It uses cURL to interact with the Telegram Bot API, including HTTP response code checks and JSON validation.

<?php
declare(strict_types=1);

$botToken = getenv('TELEGRAM_BOT_TOKEN') ?: 'YOUR_BOT_TOKEN';
$chatId = getenv('TELEGRAM_MANAGER_CHAT_ID') ?: '-1001234567890';

$name = trim($_POST['name'] ?? '');
$phone = trim($_POST['phone'] ?? '');

if ($name === '' || $phone === '') {
http_response_code(400);
echo json_encode(['error' => 'Заполните обязательные поля']);
exit;
}

// Генерация 14-символьного идентификатора (7 байт = 14 hex-символов)
$leadId = bin2hex(random_bytes(7));

// Подключение к БД через PDO
$pdo = new PDO('mysql:host=127.0.0.1;dbname=app_db;charset=utf8mb4', 'dbuser', 'dbpass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

// 1. Вставка лида в БД
$stmt = $pdo->prepare("
INSERT INTO leads (lead_id, name, phone, status, created_at)
VALUES (:lead_id, :name, :phone, 'new', NOW())
");
$stmt->execute([
'lead_id' => $leadId,
'name' => $name,
'phone' => $phone,
]);

// 2. Формирование карточки для Telegram
$text = "<b>📥 Новая заявка с сайта!</b>

"
. "<b>ID:</b> <code>" . htmlspecialchars($leadId, ENT_QUOTES, 'UTF-8') . "</code>
"
. "<b>Имя:</b> " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "
"
. "<b>Телефон:</b> " . htmlspecialchars($phone, ENT_QUOTES, 'UTF-8');

$keyboard = [
'inline_keyboard' => [
[
['text' => '🙋 Взять в работу', 'callback_data' => 'take:' . $leadId]
]
]
];

// 3. Отправка сообщения в чат через cURL
$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([
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'HTML',
'reply_markup' => $keyboard,
]),
CURLOPT_TIMEOUT => 5,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($response === false || $httpCode !== 200) {
error_log("Telegram API Error: Code {$httpCode}, cURL: {$curlError}, Resp: {$response}");
// Сообщение сохранено в БД, менеджеры обработают вручную
}

echo json_encode(['success' => true, 'lead_id' => $leadId]);

Step 2. Secure Webhook Handler and Duplicate Protection

When a manager clicks the "Claim lead" button, Telegram sends an HTTP POST request containing an Update object with a callback_query to your Webhook URL.

It is critically important to implement three levels of protection on the Webhook endpoint:

  • Secret Token: Verifying the X-Telegram-Bot-Api-Secret-Token header set during webhook installation via setWebhook.
  • Idempotency by update_id: Telegram may resend the same update in case of network glitches. We save the update_id to the database (or Redis) and discard duplicates.
  • Быстрый ответ 200 OK: The script must execute quickly so Telegram does not consider the request timed out.

Let's create an auxiliary table for Webhook event deduplication:

CREATE TABLE processed_updates (
update_id BIGINT PRIMARY KEY,
created_at DATETIME NOT NULL
) ENGINE=InnoDB;

Step 3. Processing callback_query and Race Condition Protection

A common issue in group chats is when two managers click the button under the same lead simultaneously. If status checking and updating are performed in two separate SQL queries (a SELECT followed by an UPDATE), a race condition occurs — both employees receive confirmation that they got the lead.

The solution is an atomic SQL UPDATE conditioned on the current status status = 'new', coupled with checking the affected row count via rowCount().

<?php
declare(strict_types=1);

$botToken = getenv('TELEGRAM_BOT_TOKEN') ?: 'YOUR_BOT_TOKEN';
$secretToken = getenv('TELEGRAM_SECRET_TOKEN') ?: 'MY_SECRET_WEBHOOK_TOKEN';

// 1. Валидация Secret Token
$receivedToken = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
if (!hash_equals($secretToken, $receivedToken)) {
http_response_code(403);
exit('Access Denied');
}

$rawBody = file_get_contents('php://input');
$update = json_decode($rawBody, true);

if (json_last_error() !== JSON_ERROR_NONE || !isset($update['update_id'])) {
http_response_code(400);
exit('Invalid JSON');
}

$pdo = new PDO('mysql:host=127.0.0.1;dbname=app_db;charset=utf8mb4', 'dbuser', 'dbpass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

// 2. Идемпотентность по update_id
$updateId = (int)$update['update_id'];
$stmt = $pdo->prepare("INSERT IGNORE INTO processed_updates (update_id, created_at) VALUES (:id, NOW())");
$stmt->execute(['id' => $updateId]);

if ($stmt->rowCount() === 0) {
// Данный update_id уже был успешно обработан ранее
http_response_code(200);
exit('OK');
}

// 3. Обработка Callback Query
if (isset($update['callback_query'])) {
$cq = $update['callback_query'];
$cqId = $cq['id'];
$callbackData = $cq['data'] ?? '';
$fromUser = $cq['from'];
$managerTgId = (int)$fromUser['id'];
$managerName = trim(($fromUser['first_name'] ?? '') . ' ' . ($fromUser['last_name'] ?? ''));
if ($managerName === '') {
$managerName = 'ID ' . $managerTgId;
}

$message = $cq['message'] ?? null;

if ($message && str_starts_with($callbackData, 'take:')) {
$leadId = substr($callbackData, 5);
$chatId = $message['chat']['id'];
$messageId = $message['message_id'];

// Атомарное взятие лида в работу
$stmt = $pdo->prepare("
UPDATE leads
SET status = 'in_progress', manager_tg_id = :manager_id
WHERE lead_id = :lead_id AND status = 'new'
");
$stmt->execute([
'manager_id' => $managerTgId,
'lead_id' => $leadId,
]);

if ($stmt->rowCount() > 0) {
// Лид успешно достался этому менеджеру
answerCallbackQuery($botToken, $cqId, "✅ Заявка #{$leadId} закреплена за вами!");

// Обновляем текст сообщения и снимаем кнопку
$originalText = $message['text'] ?? '';
$newText = $originalText . "

🟢 Взято в работу: " . htmlspecialchars($managerName, ENT_QUOTES, 'UTF-8');

editMessageText($botToken, $chatId, $messageId, $newText);
} else {
// Заявка уже была перехвачена другим сотрудником
answerCallbackQuery($botToken, $cqId, "⚠️ Заявка уже обработана другим менеджером!", true);
}
}
}

http_response_code(200);
exit('OK');

/**
* Вспомогательная функция ответа на CallbackQuery (закрывает лоадер на кнопке)
*/
function answerCallbackQuery(string $token, string $cqId, string $text, bool $showAlert = false): void {
$ch = curl_init("https://api.telegram.org/bot{$token}/answerCallbackQuery");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'callback_query_id' => $cqId,
'text' => $text,
'show_alert' => $showAlert,
]),
CURLOPT_TIMEOUT => 3,
]);
curl_exec($ch);
curl_close($ch);
}

/**
* Редактирование карточки заявки в чате
*/
function editMessageText(string $token, $chatId, int $messageId, string $text): void {
$ch = curl_init("https://api.telegram.org/bot{$token}/editMessageText

New articles on Telegram

We explain what to automate in your business and how it works in practice. No spam.