BaseService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. <?php
  2. namespace App\Services;
  3. use App\Models\ActivityReward;
  4. use Endroid\QrCode\Builder\Builder;
  5. use Endroid\QrCode\Writer\PngWriter;
  6. use Telegram\Bot\Api;
  7. use App\Models\Config;
  8. use Telegram\Bot\FileUpload\InputFile;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Jobs\SendTelegramMessageJob;
  11. use App\Jobs\SendTelegramGroupMessageJob;
  12. abstract class BaseService
  13. {
  14. const YES = 1;
  15. const NOT = 0;
  16. public static string $MODEL = "";
  17. /**
  18. * @description: 模型
  19. * @return string
  20. */
  21. public static function model(): string
  22. {
  23. return static::$MODEL;
  24. }
  25. /**
  26. * @description: 获取查询条件
  27. * @param array $search
  28. * @return array
  29. */
  30. abstract public static function getWhere(array $search = []): array;
  31. /**
  32. * @description: 枚举
  33. * @return {*}
  34. */
  35. public static function enum(): string
  36. {
  37. return '';
  38. }
  39. /**
  40. * @description: 生成充值二维码
  41. * @param {*} $address 充值地址
  42. * @return {*}
  43. */
  44. public static function createRechargeQrCode($address = '')
  45. {
  46. $content = $address;
  47. $qrSize = 300;
  48. $font = 4;
  49. $textHeight = 20;
  50. $padding = 10;
  51. // 生成二维码图像对象
  52. $result = Builder::create()
  53. ->writer(new PngWriter())
  54. ->data($content)
  55. ->size($qrSize)
  56. ->margin(0)
  57. ->build();
  58. $qrImage = imagecreatefromstring($result->getString());
  59. // 创建画布(加上下方文字区和边距)
  60. $canvasWidth = $qrSize + $padding * 2;
  61. $canvasHeight = $qrSize + $textHeight + $padding * 2;
  62. $image = imagecreatetruecolor($canvasWidth, $canvasHeight);
  63. // 背景白色
  64. $white = imagecolorallocate($image, 255, 255, 255);
  65. imagefill($image, 0, 0, $white);
  66. // 黑色字体
  67. $black = imagecolorallocate($image, 0, 0, 0);
  68. // 合并二维码图像
  69. imagecopy($image, $qrImage, $padding, $padding, 0, 0, $qrSize, $qrSize);
  70. // 写文字
  71. $textWidth = imagefontwidth($font) * strlen($content);
  72. $x = ($canvasWidth - $textWidth) / 2;
  73. $y = $qrSize + $padding + 5;
  74. imagestring($image, $font, $x, $y, $content, $black);
  75. // 生成文件名
  76. $filename = $address . '.png';
  77. $relativePath = 'recharge/' . $filename;
  78. $storagePath = storage_path('app/public/' . $relativePath);
  79. // 确保目录存在
  80. @mkdir(dirname($storagePath), 0777, true);
  81. // 保存图片到文件
  82. imagepng($image, $storagePath);
  83. // 清理
  84. imagedestroy($qrImage);
  85. imagedestroy($image);
  86. // 返回 public 存储路径(可用于 URL)
  87. return 'storage/' . $relativePath; // 或返回 Storage::url($relativePath);
  88. }
  89. /**
  90. * 判断指定地址的二维码是否已生成(已存在文件)
  91. *
  92. * @param string $address 充值地址
  93. * @return
  94. */
  95. public static function rechargeQrCodeExists(string $address)
  96. {
  97. $filename = $address . '.png';
  98. $relativePath = 'recharge/' . $filename;
  99. $storagePath = storage_path('app/public/' . $relativePath);
  100. $path = '';
  101. if (file_exists($storagePath)) {
  102. $path = 'storage/' . $relativePath;
  103. }
  104. return $path;
  105. }
  106. /**
  107. * @description: 转成树形数据
  108. * @param {*} $list 初始数据
  109. * @param {*} $pid 父id
  110. * @param {*} $level 层级
  111. * @param {*} $pid_name pid字段名称 默认pid
  112. * @param {*} $id_name 主键id 名称
  113. * @return {*}
  114. */
  115. public static function toTree($list, $pid = 0, $level = 0, $pid_name = 'pid', $id_name = 'id')
  116. {
  117. $arr = [];
  118. $level++;
  119. foreach ($list as $k => $v) {
  120. if ($pid == $v[$pid_name]) {
  121. $v['level'] = $level;
  122. $v['children'] = self::toTree($list, $v[$id_name], $level, $pid_name, $id_name);
  123. $arr[] = $v;
  124. }
  125. }
  126. return $arr;
  127. }
  128. public static function buildTree($list,$pid_name='pid',$id_name='id')
  129. {
  130. // 创建映射表
  131. $map = [];
  132. foreach ($list as $item) {
  133. $map[$item[$id_name]] = $item;
  134. }
  135. // 找到顶级节点
  136. $topLevelNodes = [];
  137. foreach ($map as $key => $value) {
  138. if (!isset($map[$value[$pid_name]])) {
  139. $topLevelNodes[$key] = &$map[$key];
  140. }
  141. }
  142. // 构建树形结构
  143. $tree = [];
  144. foreach ($map as &$item) {
  145. if (isset($item[$pid_name]) && isset($map[$item[$pid_name]])) {
  146. $parent = &$map[$item[$pid_name]];
  147. if (!isset($parent['children'])) {
  148. $parent['children'] = [];
  149. }
  150. $parent['children'][] = &$item;
  151. } else {
  152. $tree[] = &$item;
  153. }
  154. }
  155. return $tree;
  156. }
  157. /**
  158. * @description: 实例化TG
  159. * @return {*}
  160. */
  161. public static function telegram()
  162. {
  163. return app(Api::class);
  164. }
  165. protected static function sendTelegramRequest(callable $callback, string $action, array $context = [])
  166. {
  167. $maxAttempts = max(1, (int)config('services.telegram.retry_attempts', 3));
  168. $delaySeconds = max(1, (int)config('services.telegram.retry_delay_seconds', 3));
  169. for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
  170. try {
  171. return $callback();
  172. } catch (\Throwable $exception) {
  173. $safeMessage = self::sanitizeTelegramError($exception->getMessage());
  174. $logContext = array_merge($context, [
  175. 'action' => $action,
  176. 'attempt' => $attempt,
  177. 'max_attempts' => $maxAttempts,
  178. 'error' => $safeMessage,
  179. 'exception' => get_class($exception),
  180. ]);
  181. if ($attempt >= $maxAttempts || !self::isRetryableTelegramError($safeMessage)) {
  182. Log::channel('issue')->warning('Telegram请求失败', $logContext);
  183. throw new \RuntimeException($safeMessage);
  184. }
  185. $retryAfter = self::getTelegramRetryAfter($safeMessage, $attempt, $delaySeconds);
  186. Log::channel('issue')->warning('Telegram请求失败,准备重试', $logContext + [
  187. 'retry_after_seconds' => $retryAfter,
  188. ]);
  189. sleep($retryAfter);
  190. }
  191. }
  192. }
  193. protected static function sanitizeTelegramError(string $message): string
  194. {
  195. return preg_replace('/bot\d+:[A-Za-z0-9_-]+/', 'bot[redacted]', $message);
  196. }
  197. protected static function isRetryableTelegramError(string $message): bool
  198. {
  199. return str_contains($message, 'Too Many Requests')
  200. || str_contains($message, 'retry after')
  201. || str_contains($message, 'cURL error 7')
  202. || str_contains($message, 'cURL error 28')
  203. || str_contains($message, 'Failed to connect')
  204. || str_contains($message, 'Connection timed out')
  205. || str_contains($message, 'Operation timed out');
  206. }
  207. protected static function getTelegramRetryAfter(string $message, int $attempt, int $delaySeconds): int
  208. {
  209. $maxDelaySeconds = max(1, (int)config('services.telegram.retry_max_delay_seconds', 10));
  210. if (preg_match('/retry after (\d+)/i', $message, $matches)) {
  211. return min($maxDelaySeconds, (int)$matches[1] + 1);
  212. }
  213. return min($maxDelaySeconds, $delaySeconds * $attempt);
  214. }
  215. // /**
  216. // * @description: 群组通知(自动分段发送,支持中文与多字节字符)
  217. // * @param string $text 通知内容
  218. // * @param array $keyboard 操作按钮
  219. // * @param string $image 图片路径(可选)
  220. // * @param bool $isTop 是否置顶第一条消息
  221. // */
  222. // public static function bettingGroupNotice($text, $keyboard = [], $image = '', $isTop = false)
  223. // {
  224. // $bettingGroup = Config::where('field', 'betting_group')->first()->val;
  225. // $telegram = self::telegram();
  226. //
  227. // $maxLen = 1024; // Telegram 限制:最多 1024 个字符
  228. // $textParts = [];
  229. // $textLength = mb_strlen($text, 'UTF-8');
  230. // for ($i = 0; $i < $textLength; $i += $maxLen) {
  231. // $textParts[] = mb_substr($text, $i, $maxLen, 'UTF-8');
  232. // }
  233. //
  234. // $firstMessageId = null;
  235. //
  236. // foreach ($textParts as $index => $partText) {
  237. // $botMsg = [
  238. // 'chat_id' => "@{$bettingGroup}",
  239. // 'text' => $partText,
  240. // ];
  241. //
  242. // if (count($keyboard) > 0 && $index === 0) {
  243. // $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  244. // }
  245. //
  246. // if (!empty($image) && $index === 0) {
  247. // // 第一条带图片
  248. // $botMsg['photo'] = InputFile::create($image);
  249. // $botMsg['caption'] = $partText;
  250. // $botMsg['protect_content'] = true;
  251. // $response = $telegram->sendPhoto($botMsg);
  252. // } else {
  253. // $response = $telegram->sendMessage($botMsg);
  254. // }
  255. //
  256. // if ($isTop && $index === 0 && $response && $response->get('message_id')) {
  257. // $firstMessageId = $response->get('message_id');
  258. // }
  259. //
  260. // // 防止限流(可选)
  261. // usleep(300000);
  262. // }
  263. //
  264. // if ($isTop && $firstMessageId) {
  265. // $telegram->pinChatMessage([
  266. // 'chat_id' => "@{$bettingGroup}",
  267. // 'message_id' => $firstMessageId
  268. // ]);
  269. // }
  270. // }
  271. /**
  272. * @description: 群组通知
  273. * @apiParam string $text 通知内容
  274. * @apiParam array $keyboard 操作按钮
  275. * @apiParam string $separator 分隔符
  276. * @apiParam boolean $isTop 是否置顶
  277. */
  278. public static function bettingGroupNotice($text, $keyboard = [], $image = '', $isTop = false, $separator = "\n"): array
  279. {
  280. $bettingGroup = Config::where('field', 'betting_group')->first()->val;
  281. if (empty($separator)) $separator = "\n";
  282. $array = explode($separator, $text);
  283. $res = [];
  284. // 为空只发图片
  285. if (empty($text) && !empty($image)) {
  286. $botMsg = [
  287. 'chat_id' => "@{$bettingGroup}",
  288. ];
  289. $botMsg['photo'] = InputFile::create($image);
  290. $botMsg['caption'] = $text;
  291. $botMsg['protect_content'] = true; // 防止转发
  292. if (count($keyboard) > 0) {
  293. $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  294. }
  295. $response = self::sendTelegramRequest(fn() => self::telegram()->sendPhoto($botMsg), 'sendPhoto', [
  296. 'chat_id' => $botMsg['chat_id'],
  297. 'has_image' => true,
  298. ]);
  299. } else {
  300. foreach ($array as $key => $line) {
  301. if (empty(str_ireplace(" ", "", str_ireplace("\n", '', $line)))) {
  302. unset($array[$key]);
  303. } else {
  304. $array[$key] .= $separator;
  305. }
  306. }
  307. $texts = [];
  308. $len = !empty($image) ? 1024 : 4096;
  309. foreach ($array as $item) {
  310. if (count($texts) > 1) $len = 4096;
  311. if (count($texts) == 0 || strlen($texts[count($texts) - 1] . $item) > $len) {
  312. $texts[] = $item;
  313. } else {
  314. $texts[count($texts) - 1] .= $item;
  315. }
  316. }
  317. foreach ($texts as $index => $item) {
  318. $botMsg = [
  319. 'chat_id' => "@{$bettingGroup}",
  320. 'text' => $item,
  321. ];
  322. if ($index > 0) {
  323. $res[] = $botMsg;
  324. self::sendTelegramRequest(fn() => self::telegram()->sendMessage($botMsg), 'sendMessage', [
  325. 'chat_id' => $botMsg['chat_id'],
  326. 'chunk_index' => $index,
  327. 'has_image' => false,
  328. ]);
  329. } else {
  330. if (count($keyboard) > 0) {
  331. $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  332. }
  333. if (!empty($image)) {
  334. unset($botMsg['text']);
  335. $botMsg['photo'] = InputFile::create($image);
  336. $botMsg['caption'] = $item;
  337. $botMsg['protect_content'] = true;
  338. $res[] = $botMsg;
  339. $response = self::sendTelegramRequest(fn() => self::telegram()->sendPhoto($botMsg), 'sendPhoto', [
  340. 'chat_id' => $botMsg['chat_id'],
  341. 'chunk_index' => $index,
  342. 'has_image' => true,
  343. ]);
  344. } else {
  345. $res[] = $botMsg;
  346. $response = self::sendTelegramRequest(fn() => self::telegram()->sendMessage($botMsg), 'sendMessage', [
  347. 'chat_id' => $botMsg['chat_id'],
  348. 'chunk_index' => $index,
  349. 'has_image' => false,
  350. ]);
  351. }
  352. if ($isTop === true) {
  353. self::sendTelegramRequest(fn() => self::telegram()->pinChatMessage([
  354. 'chat_id' => "@{$bettingGroup}",
  355. 'message_id' => $response->get('message_id')
  356. ]), 'pinChatMessage', [
  357. 'chat_id' => "@{$bettingGroup}",
  358. 'message_id' => $response->get('message_id'),
  359. ]);
  360. }
  361. }
  362. }
  363. }
  364. return $res;
  365. }
  366. /**
  367. * @description: 异步群组通知
  368. * @param {string} $text 通知内容
  369. * @param {array} $keyboard 操作按钮
  370. * @param {*string} $image 图片
  371. * @return {*}
  372. */
  373. public static function asyncBettingGroupNotice($text, $keyboard = [], $image = '', $isTop = false): void
  374. {
  375. SendTelegramGroupMessageJob::dispatch($text, $keyboard, $image, $isTop);
  376. }
  377. /**
  378. * @description: 发送消息
  379. * @param {string} $chatId 聊天ID
  380. * @param {string} $text 消息内容
  381. * @param {array} $keyboard 操作按钮
  382. * @param {*string} $image 图片
  383. * @return {*}
  384. */
  385. public static function sendMessage($chatId, $text, $keyboard = [], $image = ''): void
  386. {
  387. $botMsg = [
  388. 'chat_id' => $chatId,
  389. ];
  390. if (count($keyboard) > 0) {
  391. $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  392. }
  393. if ($image != '') {
  394. $botMsg['photo'] = InputFile::create($image);
  395. $botMsg['caption'] = $text;
  396. $botMsg['protect_content'] = false; // 防止转发
  397. self::sendTelegramRequest(fn() => self::telegram()->sendPhoto($botMsg), 'sendPhoto', [
  398. 'chat_id' => $chatId,
  399. 'has_image' => true,
  400. ]);
  401. } else {
  402. $botMsg['text'] = $text;
  403. self::sendTelegramRequest(fn() => self::telegram()->sendMessage($botMsg), 'sendMessage', [
  404. 'chat_id' => $chatId,
  405. 'has_image' => false,
  406. ]);
  407. }
  408. }
  409. /**
  410. * @description: 异步发送消息
  411. * @param {string} $chatId 聊天ID
  412. * @param {string} $text 消息内容
  413. * @param {array} $keyboard 操作按钮
  414. * @param {*string} $image 图片
  415. * @return {*}
  416. */
  417. public static function asyncSendMessage($chatId, $text, $keyboard = [], $image = ''): void
  418. {
  419. SendTelegramMessageJob::dispatch($chatId, $text, $keyboard, $image);
  420. }
  421. /**
  422. * @description: 弹窗提示
  423. * @param {*} $memberId
  424. * @param {*} $address
  425. * @return {*}
  426. */
  427. public static function alertNotice($callbackId, $text): void
  428. {
  429. self::telegram()->answerCallbackQuery([
  430. 'callback_query_id' => $callbackId,
  431. 'text' => $text,
  432. 'show_alert' => true // 显示为弹窗
  433. ]);
  434. }
  435. public static function log($message, $context = [])
  436. {
  437. Log::error($message, $context);
  438. }
  439. /**
  440. * @description: 获取操作按钮
  441. * @return {*}
  442. */
  443. public static function getOperateButton()
  444. {
  445. $replyInfo = KeyboardService::findOne(['button' => '投注菜单']);
  446. if ($replyInfo && $replyInfo->buttons) {
  447. $buttons = json_decode($replyInfo->buttons, true);
  448. foreach ($buttons as $row) {
  449. $inlineButton[] = [];
  450. foreach ($row as $button) {
  451. $btn = ['text' => $button['text']];
  452. if (strpos($button['url'], 'http') === 0) {
  453. $btn['url'] = $button['url'];
  454. } else {
  455. $btn['callback_data'] = $button['url'];
  456. }
  457. $inlineButton[count($inlineButton) - 1][] = $btn;
  458. }
  459. }
  460. $inlineButton = array_values($inlineButton);
  461. return $inlineButton;
  462. }
  463. $inlineButton = [];
  464. return $inlineButton;
  465. }
  466. // 获取字符串最后几个字符
  467. public static function getLastChar($str, $num = 1)
  468. {
  469. $length = mb_strlen($str, 'UTF-8');
  470. $lastChar = mb_substr($str, $length - 1, $num, 'UTF-8');
  471. return $lastChar;
  472. }
  473. public static function generateRandomString($length = 8)
  474. {
  475. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  476. $randomString = '';
  477. for ($i = 0; $i < $length; $i++) {
  478. $randomString .= $characters[rand(0, strlen($characters) - 1)];
  479. }
  480. return $randomString;
  481. }
  482. public static function generateRandomNumber($length = 8)
  483. {
  484. $characters = '0123456789';
  485. $randomString = '';
  486. for ($i = 0; $i < $length; $i++) {
  487. $randomString .= rand(1, 9);
  488. }
  489. return $randomString;
  490. }
  491. public static function hideMiddleDigits($number, $hideCount = 4)
  492. {
  493. $length = strlen($number);
  494. if ($length <= $hideCount) {
  495. // 数字太短,全部隐藏
  496. return str_repeat("*", $length);
  497. }
  498. // 计算中间开始隐藏的位置
  499. $startLen = floor(($length - $hideCount) / 2);
  500. $endLen = $length - $hideCount - $startLen;
  501. $start = substr($number, 0, $startLen);
  502. $end = substr($number, -$endLen);
  503. return $start . str_repeat("*", $hideCount) . $end;
  504. }
  505. // 生成订单号
  506. public static function createOrderNo($prefix = 'pc28_', $memberId = null)
  507. {
  508. // 处理会员ID,获取后四位
  509. if ($memberId) {
  510. $memberSuffix = str_pad(substr($memberId, -4), 4, '0', STR_PAD_LEFT);
  511. } else {
  512. $memberSuffix = '0000'; // 默认值
  513. }
  514. // 时间部分
  515. $timePart = date('YmdHis');
  516. // 随机部分增加唯一性
  517. $randomPart = mt_rand(1000, 9999);
  518. return $prefix . $timePart . $randomPart . $memberSuffix;
  519. }
  520. /**
  521. * @description: 生成支付二维码
  522. * @param {*} $address 支付地址
  523. * @return {*}
  524. */
  525. public static function createPaymentQrCode($address = '')
  526. {
  527. // $content = $address;
  528. $content = '';
  529. $qrSize = 300;
  530. $font = 4;
  531. $textHeight = 20;
  532. $padding = 10;
  533. // 生成二维码图像对象
  534. $result = Builder::create()
  535. ->writer(new PngWriter())
  536. ->data($address)
  537. ->size($qrSize)
  538. ->margin(0)
  539. ->build();
  540. $qrImage = imagecreatefromstring($result->getString());
  541. // 创建画布(加上下方文字区和边距)
  542. $canvasWidth = $qrSize + $padding * 2;
  543. $canvasHeight = $qrSize + $textHeight + $padding * 2;
  544. $image = imagecreatetruecolor($canvasWidth, $canvasHeight);
  545. // 背景白色
  546. $white = imagecolorallocate($image, 255, 255, 255);
  547. imagefill($image, 0, 0, $white);
  548. // 黑色字体
  549. $black = imagecolorallocate($image, 0, 0, 0);
  550. // 合并二维码图像
  551. imagecopy($image, $qrImage, $padding, $padding, 0, 0, $qrSize, $qrSize);
  552. // 写文字
  553. $textWidth = imagefontwidth($font) * strlen($content);
  554. $x = ($canvasWidth - $textWidth) / 2;
  555. $y = $qrSize + $padding + 5;
  556. imagestring($image, $font, $x, $y, $content, $black);
  557. $address_name = self::generateRandomString(20) . time();
  558. // 生成文件名
  559. $filename = $address_name . '.png';
  560. $relativePath = 'payment/' . $filename;
  561. $storagePath = storage_path('app/public/' . $relativePath);
  562. // 确保目录存在
  563. @mkdir(dirname($storagePath), 0777, true);
  564. // 保存图片到文件
  565. imagepng($image, $storagePath);
  566. // 清理
  567. imagedestroy($qrImage);
  568. imagedestroy($image);
  569. // 返回 public 存储路径(可用于 URL)
  570. return 'storage/' . $relativePath; // 或返回 Storage::url($relativePath);
  571. }
  572. }