TelegramWebHook.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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\QianBaoWithdrawService;
  9. use App\Services\SanJinRechargeService;
  10. use App\Services\SecretService;
  11. use App\Services\SettlementService;
  12. use App\Services\TopUpService;
  13. use App\Services\UserService;
  14. use App\Services\WalletService;
  15. use App\Services\WithdrawService;
  16. use App\Services\BalanceLogService;
  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)
  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. $chatId = $message->chat->id;
  58. $firstName = $message->chat->firstName;
  59. $username = '';
  60. $messageId = $message->messageId;
  61. if (!$from->isBot) {
  62. $chatId = $from->id;
  63. $firstName = $from->firstName;
  64. $username = $from->username;
  65. }
  66. $user = User::where('member_id', $chatId)->first();
  67. if (!$user) {
  68. $user = new User();
  69. $user->member_id = $chatId;
  70. }
  71. if ($username) $user->username = $username;
  72. $user->first_name = $firstName;
  73. $user->save();
  74. App::setLocale($user->language);
  75. //给每个用户生成一个专属的USDT钱包
  76. WalletService::getUserWallet($chatId);
  77. QianBaoWithdrawService::init($telegram, $data, $chatId, $firstName, $messageId);
  78. SanJinRechargeService::init($telegram, $data, $chatId, $firstName, $messageId);
  79. SecretService::init($telegram, $data, $chatId, $firstName, $messageId);
  80. UserService::init($telegram, $data, $chatId, $firstName, $messageId);
  81. // 查看余额弹窗
  82. if ($data === 'balanceAlert') {
  83. $alertText = WalletService::getBalance($chatId)['text'];
  84. WalletService::alertNotice($callbackId, $alertText);
  85. }
  86. // 今日流水弹窗
  87. if ($data === 'todayFlowAlert') {
  88. $alertText = BalanceLogService::getTodayFlowing($chatId)['text'];
  89. BalanceLogService::alertNotice($callbackId, $alertText);
  90. }
  91. // 近期注单弹窗
  92. if ($data === 'betsAlert') {
  93. Cache::put('message_id_bet_record_' . $chatId, 0, 600);
  94. $alertText = BetService::recentlyRecord($chatId);
  95. BetService::alertNotice($callbackId, $alertText);
  96. }
  97. //选择充值地址
  98. if ($data === "topUp@@TRC20" || $data === "topUp@@ERC20") {
  99. $type = preg_replace('/^topUp@@/', '', $data);
  100. $topService = new TopUpService();
  101. $res = $topService->scan($chatId, $messageId, $type);
  102. $telegram->deleteMessage([
  103. 'chat_id' => $chatId,
  104. 'message_id' => $messageId,
  105. ]);
  106. $telegram->sendPhoto($res);
  107. }
  108. //点击充值按钮
  109. if ($data === 'topup@@topup') {
  110. $res = TopUpService::chooseAddress($chatId, $messageId);
  111. $telegram->editMessageText($res);
  112. }
  113. //点击充值的账单按钮
  114. if ($data === 'topup@@bill') {
  115. $res = (new TopUpService())->bill($chatId, $firstName, $messageId);
  116. $telegram->editMessageText($res);
  117. }
  118. //点击我已付款按钮
  119. //手动充值(后台审核后到账)
  120. if ($data === 'topUp@@pay2') {
  121. $telegram->deleteMessage([
  122. 'chat_id' => $chatId,
  123. 'message_id' => $messageId
  124. ]);
  125. $res = TopUpService::pay2($chatId);
  126. $telegram->sendMessage($res);
  127. } //
  128. //自动充值
  129. elseif ($data === 'topUp@@pay') {
  130. $telegram->deleteMessage([
  131. 'chat_id' => $chatId,
  132. 'message_id' => $messageId
  133. ]);
  134. $topService = new TopUpService();
  135. $res = $topService->done($chatId);
  136. $telegram->sendMessage($res);
  137. }
  138. //充值首页
  139. if ($data === "topUp@@home" || $data === "topUp@@home1") {
  140. $returnMsg = WalletService::getBalance($chatId);
  141. if ($returnMsg) {
  142. if ($data === "topUp@@home1") {
  143. $telegram->deleteMessage([
  144. 'chat_id' => $chatId,
  145. 'message_id' => $messageId
  146. ]);
  147. $this->telegram->sendMessage($returnMsg);
  148. } else {
  149. $returnMsg['message_id'] = $messageId;
  150. $telegram->editMessageText($returnMsg);
  151. }
  152. }
  153. // $res = (new TopUpService())->index($chatId, $firstName, $messageId);
  154. // if ($data === "topUp@@home1") {
  155. // $telegram->deleteMessage([
  156. // 'chat_id' => $chatId,
  157. // 'message_id' => $messageId
  158. // ]);
  159. // $telegram->sendMessage($res);
  160. // } else {
  161. // $telegram->editMessageText($res);
  162. // }
  163. }
  164. //点击提现按钮
  165. if ($data === "withdraw@@apply") {
  166. $res = (new WithdrawService())->apply($chatId, $messageId);
  167. $telegram->editMessageText($res);
  168. }
  169. //地址管理
  170. if ($data === 'withdraw@@address') {
  171. $res = WithdrawService::getAddress($chatId, $messageId);
  172. $telegram->editMessageText($res);
  173. }
  174. //关闭本条消息
  175. if ($data === 'message@@close') {
  176. $telegram->deleteMessage([
  177. 'chat_id' => $chatId,
  178. 'message_id' => $messageId
  179. ]);
  180. }
  181. if ($data === 'withdrawAddress@@add') {
  182. $res = WithdrawService::addAddress($chatId, $messageId);
  183. $telegram->editMessageText($res);
  184. }
  185. //提现管理
  186. if ($data === "withdraw@@home") {
  187. // $res = WithdrawService::index($chatId, $firstName, $messageId);
  188. // $telegram->editMessageText($res);
  189. $telegram->deleteMessage([
  190. 'chat_id' => $chatId,
  191. 'message_id' => $messageId
  192. ]);
  193. $returnMsg = WalletService::getBalance($chatId);
  194. if ($returnMsg) {
  195. $this->telegram->sendMessage($returnMsg);
  196. }
  197. }
  198. //点击提现的账单按钮
  199. if ($data === "withdraw@@bill") {
  200. $res = (new WithdrawService())->bill($chatId, $firstName, $messageId);
  201. $telegram->editMessageText($res);
  202. // $telegram->sendMessage($res);
  203. // $text = "📅 请输入查询日期\n";
  204. // $date = date('Y-m-d');
  205. // $text .= "例如您要查询的日期 {$date}\n";
  206. // $text .= "那么请发送:【提现账单】{$date}\n";
  207. // $telegram->sendMessage([
  208. // 'chat_id' => $chatId,
  209. // 'text' => $text
  210. // ]);
  211. }
  212. if ($data === 'withdrawAddress@@done') {
  213. $res = WithdrawService::done($chatId, $messageId, $firstName);
  214. $telegram->editMessageText($res);
  215. }
  216. // 今日汇率
  217. if ($data === 'todayExchangeRate@@rate') {
  218. BetService::todayExchangeRate($chatId);
  219. // $telegram->sendMessage($res);
  220. }
  221. //查看开奖历史图片
  222. $pattern = "/^showLotteryHistory@@\d+$/";
  223. if (preg_match($pattern, $data)) {
  224. $id = preg_replace('/^showLotteryHistory@@/', '', $data);
  225. IssueService::sendLotteryImage($chatId, $id);
  226. }
  227. //选择投注记录
  228. $pattern = "/^betRecordType@@\d+$/";
  229. if (preg_match($pattern, $data)) {
  230. $type = preg_replace('/^betRecordType@@/', '', $data);
  231. Cache::put('message_id_bet_record_' . $chatId, intval($type), 600);
  232. $telegram->deleteMessage([
  233. 'chat_id' => $chatId,
  234. 'message_id' => $messageId,
  235. ]);
  236. $returnMsg = BetService::record($chatId);
  237. $telegram->sendMessage($returnMsg);
  238. }
  239. //选择提现地址
  240. $pattern = "/^withdrawAddress@@choose\d+$/";
  241. if (preg_match($pattern, $data)) {
  242. $id = preg_replace('/^withdrawAddress@@choose/', '', $data);
  243. $res = WithdrawService::chooseAddress($chatId, $firstName, $messageId, $id);
  244. $telegram->editMessageText($res);
  245. }
  246. //删除地址
  247. $pattern = "/^withdrawAddress@@del\d+$/";
  248. if (preg_match($pattern, $data)) {
  249. $id = preg_replace('/^withdrawAddress@@del/', '', $data);
  250. $res = WithdrawService::delAddress($chatId, $id, $messageId);
  251. $telegram->editMessageText($res);
  252. }
  253. //地址详情
  254. $pattern = "/^withdrawAddress@@detail\d+$/";
  255. if (preg_match($pattern, $data)) {
  256. $id = preg_replace('/^withdrawAddress@@detail/', '', $data);
  257. $res = WithdrawService::addressDetails($chatId, $messageId, $id);
  258. $telegram->editMessageText($res);
  259. }
  260. //充值账单,下一页
  261. $pattern = "/^topUpBillNextPage@@\d+$/";
  262. if (preg_match($pattern, $data)) {
  263. $page = preg_replace('/^topUpBillNextPage@@/', '', $data);
  264. $page = intval($page);
  265. $res = (new TopUpService())->bill($chatId, $firstName, $messageId, $page);
  266. $telegram->editMessageText($res);
  267. }
  268. //流水列表,下一页
  269. $pattern = "/^FlowingHistoryPage@@\d+$/";
  270. if (preg_match($pattern, $data)) {
  271. $page = preg_replace('/^FlowingHistoryPage@@/', '', $data);
  272. $page = intval($page);
  273. $returnMsg = BalanceLogService::getFlowingHistory($chatId, $messageId, $page);
  274. $telegram->editMessageText($returnMsg);
  275. }
  276. //提现账单,下一页
  277. $pattern = "/^withdrawBillNextPage@@\d+$/";
  278. if (preg_match($pattern, $data)) {
  279. $page = preg_replace('/^withdrawBillNextPage@@/', '', $data);
  280. $page = intval($page);
  281. $res = (new WithdrawService())->bill($chatId, $firstName, $messageId, $page);
  282. $telegram->editMessageText($res);
  283. }
  284. //近期注单,下一页
  285. $pattern = "/^betRecordNextPage@@\d+$/";
  286. if (preg_match($pattern, $data)) {
  287. $page = preg_replace('/^betRecordNextPage@@/', '', $data);
  288. $page = intval($page);
  289. $res = BetService::record($chatId, $messageId, $page);
  290. $telegram->editMessageText($res);
  291. }
  292. DB::commit();
  293. } //
  294. catch (MessageException $e) {
  295. DB::rollBack();
  296. $msg = $e->getMessage();
  297. $msg = json_decode($msg, true);
  298. $telegram->sendMessage($msg);
  299. } //
  300. catch (TelegramSDKException $e) {
  301. DB::rollBack();
  302. $m = new Message();
  303. $m->json = $e->getMessage();
  304. $m->save();
  305. $telegram->sendMessage([
  306. 'chat_id' => $chatId,
  307. 'text' => '‼️‼️系统发生了错误,请联系客服'
  308. ]);
  309. }//
  310. catch (\Exception $e) {
  311. DB::rollBack();
  312. $m = new Message();
  313. $m->json = json_encode([
  314. 'line' => $e->getLine(),
  315. 'message' => $e->getMessage()
  316. ]);
  317. $m->save();
  318. $telegram->sendMessage([
  319. 'chat_id' => $chatId,
  320. 'text' => '‼️‼️系统发生了错误,请联系客服'
  321. ]);
  322. }
  323. } //
  324. else {
  325. $update = $request->all();
  326. Log::error('Telegram 文字消息回复: ' . json_encode($update, JSON_UNESCAPED_UNICODE));
  327. if (isset($update['message'])) {
  328. $message = $update['message'];
  329. $chatId = $message['chat']['id'];
  330. $messageId = $message['message_id'];
  331. DB::beginTransaction();
  332. try {
  333. $m = new Message();
  334. $m->json = json_encode($update);
  335. $m->save();
  336. $returnMsg = $this->processChatMessage($chatId, $messageId, $message, $message['from']);
  337. if ($returnMsg) {
  338. if (isset($returnMsg['image']) && $returnMsg['image'] != '') {
  339. KeyboardService::sendMessage($returnMsg['chat_id'], $returnMsg['text'] ?? '', $returnMsg['keyboard'] ?? [], $returnMsg['image'] ?? '');
  340. } else if (isset($returnMsg['photo']) && $returnMsg['photo'] != '') {
  341. $this->telegram->sendPhoto($returnMsg);
  342. } else {
  343. $this->telegram->sendMessage($returnMsg);
  344. }
  345. }
  346. DB::commit();
  347. } catch (MessageException $e) {
  348. DB::rollBack();
  349. $msg = $e->getMessage();
  350. $msg = json_decode($msg, true);
  351. $telegram->sendMessage($msg);
  352. } //
  353. catch (TelegramSDKException $e) {
  354. DB::rollBack();
  355. $m = new Message();
  356. $m->json = $e->getMessage();
  357. $m->save();
  358. $telegram->sendMessage([
  359. 'chat_id' => $chatId,
  360. 'text' => '‼️‼️系统发生了错误,请联系客服'
  361. ]);
  362. }//
  363. catch (\Exception $e) {
  364. DB::rollBack();
  365. $m = new Message();
  366. $m->json = json_encode([
  367. 'line' => $e->getLine(),
  368. 'message' => $e->getMessage()
  369. ]);
  370. $m->save();
  371. Log::error('Telegram 处理消息异常: ' . $e->getMessage());
  372. $telegram->sendMessage([
  373. 'chat_id' => $chatId,
  374. 'text' => '‼️‼️系统发生了错误,请联系客服'
  375. ]);
  376. }
  377. }
  378. }
  379. } //
  380. catch (\Exception $e) {
  381. $m = new Message();
  382. $m->json = $e->getMessage();
  383. $m->save();
  384. if (!empty($chatId)) {
  385. $telegram->sendMessage([
  386. 'chat_id' => $chatId,
  387. 'text' => '‼️‼️系统发生了错误,请联系客服'
  388. ]);
  389. }
  390. }
  391. return response()->json(['status' => 'ok']);
  392. }
  393. /**
  394. * @description: 处理聊天消息
  395. * @param {*} $chatId
  396. * @param {*} $messageId
  397. * @param {*} $message
  398. * @param {*} $from
  399. * @throws TelegramSDKException
  400. */
  401. public function processChatMessage($chatId, $messageId, $message, $from)
  402. {
  403. $returnMsg = [];
  404. //用户发送图片,结算截图
  405. if (isset($message['photo'])) {
  406. $stepStatus = Cache::get(get_step_key($chatId), -1);
  407. $stepStatus = intval($stepStatus);
  408. // //结算截图
  409. if ($stepStatus === StepStatus::INPUT_IMAGE) {
  410. $photo = $message['photo'][count($message['photo']) - 1];
  411. return (new SettlementService())->photo($photo, $chatId);
  412. }//
  413. //充值截图
  414. else if ($stepStatus === StepStatus::INPUT_TOP_UP_IMAGE) {
  415. $photo = $message['photo'][count($message['photo']) - 1];
  416. return TopUpService::photo($chatId, $photo);
  417. } else {
  418. return [];
  419. }
  420. } //用户发送了消息
  421. else if (isset($message['text'])) {
  422. $text = $message['text'];
  423. $user = User::where('member_id', $chatId)->first();
  424. if (!$user) {
  425. $user = new User();
  426. $user->member_id = $chatId;
  427. }
  428. $user->first_name = $message['chat']['first_name'];
  429. if (isset($message['chat']['username'])) {
  430. $user->username = $message['chat']['username'];
  431. }
  432. $user->save();
  433. App::setLocale($user->language);
  434. if ($message['chat']['type'] === 'private') {
  435. // 校验开始菜单事件
  436. $returnMsg = KeyboardService::checkStart($chatId, $text);
  437. if ($returnMsg) {
  438. return $returnMsg;
  439. }
  440. switch ($text) {
  441. case "/start":
  442. Util::delCache($chatId);
  443. //给每个用户生成一个专属的USDT钱包
  444. WalletService::getUserWallet($chatId);
  445. self::setReplyKeyboard($chatId, $user->language);
  446. break;
  447. default:
  448. // 关键字回复
  449. $keyboardText = KeyboardService::findOne(['button' => $text]);
  450. if ($keyboardText) {
  451. $keyboard = [];
  452. if ($keyboardText['buttons']) {
  453. $keyboard = json_decode($keyboardText['buttons'], true);
  454. }
  455. Util::delCache($chatId);
  456. $res = [
  457. 'chat_id' => $chatId,
  458. 'text' => $keyboardText['reply'],
  459. // 'reply_to_message_id' => $messageId
  460. ];
  461. if ($keyboard) {
  462. $res['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  463. }
  464. if ($keyboardText['image']) {
  465. $res['photo'] = InputFile::create(url($keyboardText['image']));
  466. unset($res['text']);
  467. $res['caption'] = $text;
  468. $res['protect_content'] = true; // 防止转发
  469. }
  470. return $res;
  471. }
  472. $stepStatus = Cache::get(get_step_key($chatId), -1);
  473. $stepStatus = intval($stepStatus);
  474. $res = QianBaoWithdrawService::onMessage($chatId, $text, $messageId, $stepStatus);
  475. if (empty($res)) $res = SanJinRechargeService::onMessage($chatId, $text, $messageId, $stepStatus);
  476. if (empty($res)) $res = SecretService::onMessage($chatId, $text, $messageId, $stepStatus);
  477. if (!empty($res)) return $res;
  478. switch ($stepStatus) {
  479. case StepStatus::INPUT_TOP_UP_MONEY:
  480. return TopUpService::inputAmount($chatId, $text, $messageId);
  481. case StepStatus::INPUT_WITHDRAW_MONEY:
  482. $res = (new WithdrawService())->inputAmount($chatId, $text, $messageId);
  483. return $res[0];
  484. case StepStatus::INPUT_ADDRESS_TRC20:
  485. return WithdrawService::inputAddress($chatId, $text, $messageId);
  486. case StepStatus::INPUT_ADDRESS_ALIAS:
  487. return WithdrawService::inputAlias($chatId, $text, $messageId);
  488. }
  489. $returnMsg = BetService::bet($chatId, $text, $messageId);
  490. }
  491. return $returnMsg;
  492. }
  493. }
  494. return [];
  495. }
  496. /**
  497. * @description: 设置 start 回复菜单
  498. * @param {*} $chatId
  499. * @throws TelegramSDKException
  500. */
  501. public static function setReplyKeyboard($chatId, $language = 'en'): void
  502. {
  503. $replyInfo = KeyboardService::findOne(['button' => '开始使用', 'language' => $language]);
  504. if (empty($replyInfo)) {
  505. $replyInfo = KeyboardService::findOne(['button' => '开始使用', 'language' => 'en']);
  506. }
  507. $telegram = new Api(config('services.telegram.token'));
  508. $keyboard = [
  509. [lang('近期注单'), lang('今日流水'), lang('联系客服')], // 第一排按钮
  510. [lang('开奖历史'), lang('当期下注'), lang('查看余额')], // 第二排按钮
  511. [lang('投注大群')]
  512. ];
  513. if ($replyInfo && $replyInfo->buttons) {
  514. $keyboard = [];
  515. $buttons = json_decode($replyInfo->buttons, true);
  516. foreach ($buttons as $rowIndex => $row) {
  517. if (!empty($row)) {
  518. foreach ($row as $buttonIndex => $button) {
  519. // $keyboard[$rowIndex][$buttonIndex] = lang($button['text']);
  520. $keyboard[$rowIndex][$buttonIndex] = $button['text'];
  521. }
  522. }
  523. }
  524. $keyboard = array_values($keyboard); // 重新索引数组
  525. Log::error('自定义开始使用按钮: ' . json_encode($keyboard));
  526. }
  527. $botMsg = [];
  528. $botMsg['chat_id'] = $chatId;
  529. $replyMarkup = [
  530. 'keyboard' => $keyboard,
  531. 'resize_keyboard' => true, // 自适应大小
  532. 'one_time_keyboard' => false, // 保持显示,不会点击后收起
  533. ];
  534. $botMsg['reply_markup'] = json_encode($replyMarkup);
  535. if ($replyInfo) {
  536. $image = '';
  537. if ($replyInfo->image) {
  538. $image = url($replyInfo->image);
  539. }
  540. if ($image != '') {
  541. $botMsg['photo'] = InputFile::create($image);
  542. $botMsg['caption'] = lang($replyInfo->reply);
  543. $botMsg['protect_content'] = true; // 防止转发
  544. KeyboardService::telegram()->sendPhoto($botMsg);
  545. } else {
  546. $botMsg['text'] = lang($replyInfo->reply);
  547. KeyboardService::telegram()->sendMessage($botMsg);
  548. }
  549. } else {
  550. $telegram->sendMessage([
  551. 'chat_id' => $chatId,
  552. 'text' => lang('你好,请选择功能菜单'),
  553. 'reply_markup' => json_encode($replyMarkup),
  554. ]);
  555. }
  556. }
  557. }