TelegramWebHook.php 12 KB

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