This commit is contained in:
hashbro
2026-08-07 06:21:33 +08:00
parent 2fd27e5e02
commit 1026ce1285
@@ -5,27 +5,60 @@ namespace App\Http\Controllers\Hooks;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use SergiX44\Nutgram\Nutgram; use SergiX44\Nutgram\Nutgram;
class TelegramWebhookController extends Controller class TelegramWebhookController extends Controller
{ {
public function __invoke(Request $request, Nutgram $bot): Response public function __invoke(Request $request, Nutgram $bot): Response
{ {
$update = $request->all();
$message = is_array($update['message'] ?? null) ? $update['message'] : [];
$chatId = $message['chat']['id'] ?? ($update['callback_query']['message']['chat']['id'] ?? null);
$text = is_string($message['text'] ?? null) ? $message['text'] : null;
Log::info('telegram webhook hit', [
'ip' => $request->ip(),
'update_id' => $update['update_id'] ?? null,
'chat_id' => $chatId,
'text' => $text,
'has_secret_header' => $request->headers->has('X-Telegram-Bot-Api-Secret-Token'),
]);
$secret = (string) config('coruna.telegram.webhook_secret', ''); $secret = (string) config('coruna.telegram.webhook_secret', '');
if ($secret !== '') { if ($secret !== '') {
$header = (string) $request->header('X-Telegram-Bot-Api-Secret-Token', ''); $header = (string) $request->header('X-Telegram-Bot-Api-Secret-Token', '');
if (! hash_equals($secret, $header)) { if (! hash_equals($secret, $header)) {
Log::warning('telegram webhook rejected: bad secret', [
'ip' => $request->ip(),
'update_id' => $update['update_id'] ?? null,
]);
abort(403, 'Invalid webhook secret'); abort(403, 'Invalid webhook secret');
} }
} }
try { try {
$bot->run(); $bot->run();
Log::info('telegram webhook handled', [
'update_id' => $update['update_id'] ?? null,
'chat_id' => $chatId,
]);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
// FakeNutgram with no update (unit tests) — still ACK the webhook probe. // FakeNutgram with no update (unit tests) — still ACK the webhook probe.
if (! app()->runningUnitTests()) { if (! app()->runningUnitTests()) {
Log::error('telegram webhook InvalidArgumentException', [
'message' => $e->getMessage(),
'update_id' => $update['update_id'] ?? null,
]);
throw $e; throw $e;
} }
} catch (\Throwable $e) {
Log::error('telegram webhook failed', [
'message' => $e->getMessage(),
'update_id' => $update['update_id'] ?? null,
'chat_id' => $chatId,
]);
throw $e;
} }
return response()->noContent(); return response()->noContent();