Handling Telegram start-payload in PHP: DB Mapping, Security, and Limits

Deep Linking technology in Telegram Bot API allows passing contextual parameters when launching or restarting a bot for the first time via a link of the form t.me/BotUsername?start=payload. This is a basic tool for tracking traffic sources, linking CRM entities, activating promo codes, or starting offers. However, in practice, developers often encounter technical limitations of the format, incorrect mixing of the payload with the current state of the conversation (FSM), and vulnerabilities to user data tampering.

In this article, we will analyze in detail how to design the start-payload processing architecture in PHP, protect parameters from tampering, and correctly link them to records in your database.

Strict Telegram API limits on start-payload

Telegram imposes strict technical limitations on the value of the start parameter in the URL:

  • Maximum length: 64 bytes (characters).
  • Allowed characters: Latin letters A-Z, a-z, digits 0-9, as well as underscores _ and hyphens -.
  • Special characters: spaces, dots, slashes, equals signs, and Cyrillic are forbidden. Passing Base64 strings directly is difficult due to the +, /, and = characters, so standard Base64 requires replacement with a URL-safe variant (base64url) or prior packaging.

If a user follows the link t.me/my_bot?start=ref_12345, Telegram sends an Update object of type Message to your Webhook, where the text content of the message becomes a string command:

/start ref_12345

If the parameter does not comply with the API rules (for example, contains forbidden characters or is longer than 64 bytes), Telegram will either simply ignore the parameter or strip it, turning the command into a simple /start.

Payload vs FSM: the difference between a deep link and conversation continuation

A typical mistake when designing a bot is confusing the incoming start-payload with the current state of a step-by-step conversation (Finite State Machine).

A deep link is a stateless entry point (stateless trigger). It informs the bot of the user's intent to enter with a specific context. In turn, FSM (Finite State Machine) is a dynamic state stored on the server (in Redis or DB) to track conversation steps (e.g., WAITING_FOR_PHONE, WAITING_FOR_EMAIL).

Important: receiving an incoming /start payload should safely reset the user's current incomplete FSM state or correctly redirect them to a new scenario. If the user was in the process of filling out a form and clicked on a promotional link ?start=promo_autumn, the bot should not attempt to parse promo_autumn as an answer to the previous question about a name or phone number.

Protection against spoofing: HMAC signature vs opaque tokens in the DB

Since the text input field in Telegram is accessible to every user, nothing prevents a client from manually typing the command /start discount_90 or /start role_admin into the chat. If your logic trusts the incoming string without validation, the system becomes vulnerable to enumeration and business data spoofing.

There are two secure approaches to constructing a payload:

  1. Opaque tokens (UUID / random hash): The link contains a random 16–32 character hex identifier (for example, lead_id = bin2hex(random_bytes(16))), which is saved in advance in the pending_payloads DB table along with a time-to-live (TTL), a single-use flag (is_used), and target parameters.
  2. HMAC signature (Stateless payload): If creating a DB record prior to clicking the link is impossible or inefficient, a short entity ID is signed with a cryptographic hash using the server's private key.

Example 1: Generating a secure deep link with HMAC

Below is a PHP script for generating a compact signed payload that fits within the 64-character Telegram API limit:

<?php

declare(strict_types=1);

function generateSecureStartLink(string $botUsername, string $entityType, int $entityId, string $secretKey): string
{
// Формируем полезную нагрузку: e.g. "order_1042"
$rawPayload = sprintf('%s_%d', $entityType, $entityId);

// Генерируем короткую подпись (8 символов sha256)
$hash = substr(hash_hmac('sha256', $rawPayload, $secretKey), 0, 8);

// Итоговый payload: "order_1042_a3f8c9e1" (гарантированно < 64 байт и удовлетворяет regex [A-Za-z0-9_-])
$payload = sprintf('%s_%s', $rawPayload, $hash);

if (strlen($payload) > 64) {
throw new InvalidArgumentException('Start payload exceeds Telegram 64 bytes limit');
}

return sprintf('https://t.me/%s?start=%s', $botUsername, $payload);
}

// Пример использования:
$appSecret = getenv('APP_SECRET_KEY') ?: 'fallback-secret-key-32-chars-len';
$link = generateSecureStartLink('MyServiceBot', 'lead', 8592, $appSecret);
echo $link;
// Вывод: https://t.me/MyServiceBot?start=lead_8592_9f2a71b4

Webhook processing, protection, and DB mapping in PHP

When receiving an update from Telegram via Webhook, security discipline must be observed:

Example 2: Receiving a Webhook, validating the payload signature, and entity mapping

The following code demonstrates the complete pipeline: Webhook validation, duplicate protection for update_id, payload parsing, HMAC validation, and sending a response to the Telegram API.

<?php

declare(strict_types=1);

header('Content-Type: application/json');

$botToken = getenv('TELEGRAM_BOT_TOKEN');
$secretToken = getenv('TELEGRAM_SECRET_TOKEN');
$appSecret = getenv('APP_SECRET_KEY');

if (!$botToken || !$secretToken || !$appSecret) {
http_response_code(500);
echo json_encode(['error' => 'Server configuration missing']);
exit;
}

// 1. Проверка Secret Token от Telegram
$headers = getallheaders();
$incomingSecret = $headers['X-Telegram-Bot-Api-Secret-Token'] ?? $headers['x-telegram-bot-api-secret-token'] ?? '';

if (!hash_equals($secretToken, $incomingSecret)) {
http_response_code(403);
echo json_encode(['error' => 'Invalid secret token']);
exit;
}

// 2. Чтение и парсинг Webhook Body
$rawInput = file_get_contents('php://input');
$update = json_decode($rawInput, true);

if (json_last_error() !== JSON_ERROR_NONE || !is_array($update)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON']);
exit;
}

$updateId = $update['update_id'] ?? null;
$message = $update['message'] ?? null;

if (!$updateId || !$message) {
echo json_encode(['status' => 'ignored']);
exit;
}

// 3. Идемпотентность (эмуляция проверки update_id в БД)
if (!isUpdateIdUnique((int)$updateId)) {
echo json_encode(['status' => 'already_processed']);
exit;
}

$chatId = $message['chat']['id'] ?? null;
$text = trim($message['text'] ?? '');

// 4. Анализ команды /start с payload
if (strpos($text, '/start') === 0 && $chatId) {
$parts = explode(' ', $text, 2);
$payload = $parts[1] ?? null;

if ($payload) {
processStartPayload((int)$chatId, $payload, $botToken, $appSecret);
} else {
sendTelegramMessage((int)$chatId, 'Добро пожаловать без контекста!', $botToken);
}
}

echo json_encode(['status' => 'ok']);

/**
* Валидация подписи payload и связывание с БД
*/
function processStartPayload(int $chatId, string $payload, string $botToken, string $appSecret): void
{
// Ожидаемый формат: type_id_hash (например: lead_8592_9f2a71b4)
$payloadParts = explode('_', $payload);

if (count($payloadParts) !== 3) {
sendTelegramMessage($chatId, 'Неверный формат ссылки.', $botToken);
return;
}

[$type, $idStr, $providedHash] = $payloadParts;
$entityId = (int)$idStr;

$rawPayload = sprintf('%s_%d', $type, $entityId);
$expectedHash = substr(hash_hmac('sha256', $rawPayload, $appSecret), 0, 8);

// Timing-safe проверка HMAC для предотвращения утечек по времени
if (!hash_equals($expectedHash, $providedHash)) {
sendTelegramMessage($chatId, 'Ошибка: Ссылка недействительна или была подделана.', $botToken);
return;
}

// В этой точке payload доказан и легитимен
// Выполняем маппинг на сущность БД и сброс прошлого FSM состояния
resetUserFsmState($chatId);
linkUserToEntity($chatId, $type, $entityId);

$responseText = sprintf('Успешно! Вы привязаны к заявке #%d (тип: %s).', $entityId, htmlspecialchars($type));
sendTelegramMessage($chatId, $responseText, $botToken);
}

/**
* Безопасный вызов Telegram API через cURL
*/
function sendTelegramMessage(int $chatId, string $text, string $botToken): bool
{
$url = sprintf('https://api.telegram.org/bot%s/sendMessage', $botToken);

$data = [
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'HTML',
];

$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 3,
]);

$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(sprintf('Telegram API error: HTTP %d, CurlErr: %s', $httpCode, $curlError));
return false;
}

$decoded = json_decode($response, true);
return isset($decoded['ok']) && $decoded['ok'] === true;
}

function isUpdateIdUnique(int $updateId): bool
{
// Реальный метод проверяет `SELECT id FROM processed_updates WHERE update_id = :id`
return true;
}

function resetUserFsmState(int $chatId): void
{
// Очистка сессии в Redis/DB для перевода диалога в начальное состояние
}

function linkUserToEntity(int $chatId, string $type, int $entityId): void
{
// Сохранение связи сущности с Telegram user_id / chat_id в MySQL/PostgreSQL
}

Production checklist for working with Deep Links

  1. Data format: Strictly validate the incoming payload against the 64-byte limit and the regular expression /^[A-Za-z0-9_-]+$/.
  2. Cryptographic verification: Never pass access rights or discounts in plain text (?start=discount100). Use single-use tokens from the DB or an HMAC signature.
  3. Separation of FSM and Deep Links: When receiving a /start command with a parameter, reset incomplete user input steps so that the old context does not distort the processing of the new link.
  4. Idempotency and timeouts: Accept webhooks instantly (returning 200 OK), and move entity mapping tasks to asynchronous queues if necessary (Laravel Queue, Yii Queue).

If you need professional development of complex bots and Mini Apps, contact the experts at BotCreator.

New articles on Telegram

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