TelegramWebHook.php 11 KB

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