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