TelegramWebHook.php 12 KB

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