TelegramWebHook.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. namespace App\Http\Controllers\api;
  3. use App\Constants\StepStatus;
  4. use App\Constants\Util;
  5. use App\Exceptions\MessageException;
  6. use App\Models\Message;
  7. use App\Models\User;
  8. use App\Services\PublicService;
  9. use App\Services\QianBaoWithdrawService;
  10. use App\Services\SanJinRechargeService;
  11. use App\Services\SecretService;
  12. use App\Services\SettlementService;
  13. use App\Services\TopUpService;
  14. use App\Services\UserService;
  15. use App\Services\WalletService;
  16. use App\Services\WithdrawService;
  17. use App\Services\BalanceLogService;
  18. use Exception;
  19. use Illuminate\Http\JsonResponse;
  20. use Illuminate\Http\Request;
  21. use Illuminate\Support\Facades\App;
  22. use Illuminate\Support\Facades\Cache;
  23. use Illuminate\Support\Facades\DB;
  24. use Telegram\Bot\Api;
  25. use Telegram\Bot\Exceptions\TelegramSDKException;
  26. use Illuminate\Support\Facades\Log;
  27. use App\Services\BetService;
  28. use App\Services\IssueService;
  29. use App\Services\KeyboardService;
  30. use Telegram\Bot\FileUpload\InputFile;
  31. class TelegramWebHook extends BaseController
  32. {
  33. protected Api $telegram;
  34. public function __construct(Api $telegram)
  35. {
  36. $this->telegram = $telegram;
  37. parent::__construct();
  38. }
  39. public function handle(Request $request): JsonResponse
  40. {
  41. Log::error('Telegram 日志写入测试: ' . json_encode([$request->ip()], JSON_UNESCAPED_UNICODE));
  42. try {
  43. $telegram = new Api(config('services.telegram.token'));
  44. } catch (TelegramSDKException $e) {
  45. return response()->json(['status' => 'ok']);
  46. }
  47. try {
  48. $update = $telegram->getWebhookUpdate(); // 获取更新数据
  49. $update->callbackQuery;
  50. if ($update->has('callback_query')) {
  51. $callbackQuery = $update->callbackQuery;
  52. $message = $callbackQuery->message;
  53. $from = $callbackQuery->from;
  54. $data = $callbackQuery->data; // 获取 callback_data
  55. $callbackId = $callbackQuery->id; // 获取 callback_query 的 ID
  56. Util::delCache($message->chat->id);
  57. // Log::error('Telegram 回调数据(JSON): ' . json_encode($update, JSON_UNESCAPED_UNICODE));
  58. DB::beginTransaction();
  59. try {
  60. $messageId = $message->messageId;
  61. list($chatId, $firstName, $username) = PublicService::getChatInfo($message, $from);
  62. //用户注册和初始化用户钱包
  63. $user = PublicService::index($chatId, $username, $firstName);
  64. App::setLocale($user->language);
  65. PublicService::init($telegram, $data, $chatId, $firstName, $messageId);
  66. WalletService::init($telegram, $data, $chatId, $firstName, $messageId, $callbackId);
  67. TopUpService::init($telegram, $data, $chatId, $firstName, $messageId);
  68. QianBaoWithdrawService::init($telegram, $data, $chatId, $firstName, $messageId);
  69. SanJinRechargeService::init($telegram, $data, $chatId, $firstName, $messageId);
  70. SecretService::init($telegram, $data, $chatId, $firstName, $messageId);
  71. UserService::init($telegram, $data, $chatId, $firstName, $messageId);
  72. WithdrawService::init($telegram, $data, $chatId, $firstName, $messageId);
  73. BetService::init($telegram, $data, $chatId, $firstName, $messageId, $callbackId);
  74. BalanceLogService::init($telegram, $data, $chatId, $firstName, $messageId, $callbackId);
  75. IssueService::init($telegram, $data, $chatId, $firstName, $messageId);
  76. DB::commit();
  77. } //
  78. catch (TelegramSDKException $e) {
  79. DB::rollBack();
  80. $telegram->sendMessage(['chat_id' => $chatId, 'text' => '‼️‼️系统发生了错误,请联系客服']);
  81. }//
  82. catch (Exception $e) {
  83. DB::rollBack();
  84. $json = json_encode(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  85. Log::error('Telegram 处理消息异常: ');
  86. Log::error($json);
  87. $telegram->sendMessage(['chat_id' => $chatId, 'text' => '‼️‼️系统发生了错误,请联系客服']);
  88. }
  89. } //
  90. else {
  91. $update = $request->all();
  92. Log::error('Telegram 文字消息回复: ' . json_encode($update, JSON_UNESCAPED_UNICODE));
  93. if (isset($update['message'])) {
  94. $message = $update['message'];
  95. $chatId = $message['chat']['id'];
  96. $messageId = $message['message_id'];
  97. DB::beginTransaction();
  98. try {
  99. $returnMsg = $this->processChatMessage($chatId, $messageId, $message, $message['from']);
  100. if ($returnMsg) {
  101. if (isset($returnMsg['image']) && $returnMsg['image'] != '') {
  102. KeyboardService::sendMessage($returnMsg['chat_id'], $returnMsg['text'] ?? '', $returnMsg['keyboard'] ?? [], $returnMsg['image'] ?? '');
  103. } else if (isset($returnMsg['photo']) && $returnMsg['photo'] != '') {
  104. $this->telegram->sendPhoto($returnMsg);
  105. } else {
  106. $this->telegram->sendMessage($returnMsg);
  107. }
  108. }
  109. DB::commit();
  110. } catch (TelegramSDKException $e) {
  111. DB::rollBack();
  112. $telegram->sendMessage(['chat_id' => $chatId, 'text' => '‼️‼️系统发生了错误,请联系客服']);
  113. }//
  114. catch (Exception $e) {
  115. DB::rollBack();
  116. $json = json_encode(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  117. Log::error('Telegram 处理消息异常: ');
  118. Log::error($json);
  119. $telegram->sendMessage(['chat_id' => $chatId, 'text' => '‼️‼️系统发生了错误,请联系客服']);
  120. }
  121. }
  122. }
  123. } //
  124. catch (Exception $e) {
  125. if (!empty($chatId)) {
  126. try {
  127. $telegram->sendMessage(['chat_id' => $chatId, 'text' => '‼️‼️系统发生了错误,请联系客服']);
  128. } catch (TelegramSDKException $e) {
  129. }
  130. }
  131. }
  132. return response()->json(['status' => 'ok']);
  133. }
  134. /**
  135. * @description: 处理聊天消息
  136. * @param {*} $chatId
  137. * @param {*} $messageId
  138. * @param {*} $message
  139. * @param {*} $from
  140. * @throws TelegramSDKException
  141. */
  142. public function processChatMessage($chatId, $messageId, $message, $from)
  143. {
  144. //用户发送图片,结算截图
  145. if (isset($message['photo'])) {
  146. $stepStatus = Cache::get(get_step_key($chatId), -1);
  147. $stepStatus = intval($stepStatus);
  148. // //结算截图
  149. if ($stepStatus === StepStatus::INPUT_IMAGE) {
  150. $photo = $message['photo'][count($message['photo']) - 1];
  151. return (new SettlementService())->photo($photo, $chatId);
  152. }//
  153. //充值截图
  154. else if ($stepStatus === StepStatus::INPUT_TOP_UP_IMAGE) {
  155. $photo = $message['photo'][count($message['photo']) - 1];
  156. return TopUpService::photo($chatId, $photo);
  157. } else {
  158. return [];
  159. }
  160. } //用户发送了消息
  161. else if (isset($message['text'])) {
  162. $text = $message['text'];
  163. $user = PublicService::index($chatId, $message['chat']['username'], $message['chat']['first_name']);
  164. App::setLocale($user->language);
  165. if ($message['chat']['type'] === 'private') {
  166. // 校验开始菜单事件
  167. $returnMsg = KeyboardService::checkStart($chatId, $text);
  168. if ($returnMsg) return $returnMsg;
  169. switch ($text) {
  170. case "/start":
  171. Util::delCache($chatId);
  172. self::setReplyKeyboard($chatId, $user->language);
  173. break;
  174. default:
  175. //关键字回复
  176. $res = KeyboardService::getKeyWordReply($chatId, $text);
  177. if (!empty($res)) return $res;
  178. $stepStatus = intval(Cache::get(get_step_key($chatId), -1));
  179. $res = QianBaoWithdrawService::onMessage($chatId, $text, $messageId, $stepStatus);
  180. if (empty($res)) $res = SanJinRechargeService::onMessage($chatId, $text, $messageId, $stepStatus);
  181. if (empty($res)) $res = SecretService::onMessage($chatId, $text, $messageId, $stepStatus);
  182. if (empty($res)) $res = WithdrawService::onMessage($chatId, $text, $messageId, $stepStatus);
  183. if (empty($res)) $res = TopUpService::onMessage($chatId, $text, $messageId, $stepStatus);
  184. if (empty($res)) $res = BetService::onMessage($chatId, $text, $messageId, $stepStatus);
  185. if (!empty($res)) return $res;
  186. return BetService::bet($chatId, $text, $messageId);
  187. }
  188. return $returnMsg;
  189. }
  190. }
  191. return [];
  192. }
  193. /**
  194. * @description: 设置 start 回复菜单
  195. * @param {*} $chatId
  196. * @throws TelegramSDKException
  197. */
  198. public static function setReplyKeyboard($chatId, $language = 'en'): void
  199. {
  200. $replyInfo = KeyboardService::findOne(['button' => '开始使用', 'language' => $language]);
  201. if (empty($replyInfo)) {
  202. $replyInfo = KeyboardService::findOne(['button' => '开始使用', 'language' => 'en']);
  203. }
  204. $telegram = new Api(config('services.telegram.token'));
  205. $keyboard = [
  206. [lang('近期注单'), lang('今日流水'), lang('联系客服')], // 第一排按钮
  207. [lang('开奖历史'), lang('当期下注'), lang('查看余额')], // 第二排按钮
  208. [lang('投注大群')]
  209. ];
  210. if ($replyInfo && $replyInfo->buttons) {
  211. $keyboard = [];
  212. $buttons = json_decode($replyInfo->buttons, true);
  213. foreach ($buttons as $rowIndex => $row) {
  214. if (!empty($row)) {
  215. foreach ($row as $buttonIndex => $button) {
  216. // $keyboard[$rowIndex][$buttonIndex] = lang($button['text']);
  217. $keyboard[$rowIndex][$buttonIndex] = $button['text'];
  218. }
  219. }
  220. }
  221. $keyboard = array_values($keyboard); // 重新索引数组
  222. Log::error('自定义开始使用按钮: ' . json_encode($keyboard));
  223. }
  224. $botMsg = [];
  225. $botMsg['chat_id'] = $chatId;
  226. $replyMarkup = [
  227. 'keyboard' => $keyboard,
  228. 'resize_keyboard' => true, // 自适应大小
  229. 'one_time_keyboard' => false, // 保持显示,不会点击后收起
  230. ];
  231. $botMsg['reply_markup'] = json_encode($replyMarkup);
  232. if ($replyInfo) {
  233. $image = '';
  234. if ($replyInfo->image) {
  235. $image = url($replyInfo->image);
  236. }
  237. if ($image != '') {
  238. $botMsg['photo'] = InputFile::create($image);
  239. $botMsg['caption'] = lang($replyInfo->reply);
  240. $botMsg['protect_content'] = true; // 防止转发
  241. KeyboardService::telegram()->sendPhoto($botMsg);
  242. } else {
  243. $botMsg['text'] = lang($replyInfo->reply);
  244. KeyboardService::telegram()->sendMessage($botMsg);
  245. }
  246. } else {
  247. $telegram->sendMessage([
  248. 'chat_id' => $chatId,
  249. 'text' => lang('你好,请选择功能菜单'),
  250. 'reply_markup' => json_encode($replyMarkup),
  251. ]);
  252. }
  253. }
  254. }