TelegramWebHook.php 12 KB

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