first()); $adminId = (int) ($state['bound_admin_id'] ?? 0); return ['bound' => !empty($state['chat_id']) && self::eligibleAdmin($adminId), 'admin_id' => $adminId]; } public static function createBinding(int $adminId): array { if (!self::enabled() || !self::configured()) { throw new \RuntimeException('请先启用 Telegram,并配置 bot token 和有效的 webhook secret'); } if (!self::eligibleAdmin($adminId)) { throw new \RuntimeException('只有超级管理员可以绑定工单通知'); } $code = bin2hex(random_bytes(24)); Configurations::firstOrCreate(['name' => self::KEY], ['value' => '{}']); (new Configurations())->getConnection()->transaction(function () use ($adminId, $code) { $row = Configurations::where('name', self::KEY)->lockForUpdate()->firstOrFail(); $state = self::readState($row); $state['pending_hash'] = hash('sha256', $code); $state['pending_admin_id'] = $adminId; $state['pending_expires_at'] = time() + self::BINDING_TTL; $row->value = json_encode($state, JSON_THROW_ON_ERROR); $row->save(); }); return ['code' => $code, 'expires_in' => self::BINDING_TTL]; } public static function unbind(): void { Configurations::where('name', self::KEY)->delete(); } public static function bindingCommand(array $update): ?array { $message = $update['message'] ?? null; if (!is_array($message) || ($message['chat']['type'] ?? '') !== 'private' || !empty($message['from']['is_bot']) || !empty($message['forward_origin']) || !empty($message['forward_from']) || !empty($message['forward_date'])) { return null; } $chatId = (string) ($message['chat']['id'] ?? ''); $senderId = (string) ($message['from']['id'] ?? ''); if (!preg_match('/^[1-9][0-9]{0,18}$/D', $chatId) || $chatId !== $senderId || !preg_match('/^\/start\s+([a-f0-9]{48})$/D', (string) ($message['text'] ?? ''), $matches)) { return null; } return ['chat_id' => $chatId, 'code' => $matches[1]]; } public static function handleUpdate(array $update): bool { $command = self::bindingCommand($update); if ($command === null) { return false; } return (new Configurations())->getConnection()->transaction(function () use ($command) { $row = Configurations::where('name', self::KEY)->lockForUpdate()->first(); $state = self::readState($row); $adminId = (int) ($state['pending_admin_id'] ?? 0); if ($row === null || (int) ($state['pending_expires_at'] ?? 0) <= time() || !hash_equals((string) ($state['pending_hash'] ?? ''), hash('sha256', $command['code'])) || !self::eligibleAdmin($adminId)) { return false; } // One-time token consumed atomically; replay cannot change the recipient. $row->value = json_encode(['bound_admin_id' => $adminId, 'chat_id' => $command['chat_id']], JSON_THROW_ON_ERROR); $row->save(); return true; }); } public static function notify(string $event, int $ticketId, string $title, string $content): bool { if (!self::enabled() || !self::configured()) { return false; } try { $state = self::readState(Configurations::where('name', self::KEY)->first()); $chatId = $state['chat_id'] ?? null; if ((!is_string($chatId) && !is_int($chatId)) || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $chatId) !== 1 || !self::eligibleAdmin((int) ($state['bound_admin_id'] ?? 0))) { return false; } $label = in_array($event, ['created', '新工单'], true) ? '新工单' : '工单更新'; $plain = strip_tags($title . "\n" . $content); $text = $label . ' #' . $ticketId . "\n" . mb_substr($plain, 0, 3000, 'UTF-8'); (new BotApi((string) Config::get('telegram_token')))->call('sendMessage', [ 'chat_id' => (string) $chatId, 'text' => $text, 'disable_web_page_preview' => 'true', ], 10); return true; } catch (\Throwable $exception) { // SDK error URLs may contain bot secrets. Never log their messages. error_log('Administrator ticket Telegram delivery failed; ticket=' . $ticketId); return false; } } public static function registerWebhook(): bool { $baseUrl = rtrim((string) Config::get('baseUrl', ''), '/'); $parts = parse_url($baseUrl); if (!self::enabled() || !self::configured() || !is_array($parts) || ($parts['scheme'] ?? '') !== 'https' || empty($parts['host']) || isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])) { throw new \RuntimeException('请检查 Telegram 配置与网站 HTTPS baseUrl'); } try { $result = (new BotApi((string) Config::get('telegram_token')))->call('setWebhook', [ 'url' => $baseUrl . '/telegram_callback', 'secret_token' => (string) Config::get('telegram_request_token'), 'allowed_updates' => '["message"]', ], 10); if ($result !== true) { throw new \RuntimeException('Webhook registration rejected'); } return true; } catch (\Throwable $exception) { throw new \RuntimeException('Telegram webhook 注册失败,请检查 HTTPS、出站网络和 bot 配置'); } } private static function readState($row): array { $state = $row === null ? [] : json_decode((string) $row->value, true); return is_array($state) ? $state : []; } private static function eligibleAdmin(int $adminId): bool { $allowed = array_map('intval', explode(',', (string) Config::get('super_admin', ''))); if ($adminId <= 0 || !in_array($adminId, $allowed, true)) { return false; } $user = User::find($adminId); return $user !== null && (bool) $user->is_admin && (int) $user->enable === 1; } }