BaseService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. // /**
  166. // * @description: 群组通知(自动分段发送,支持中文与多字节字符)
  167. // * @param string $text 通知内容
  168. // * @param array $keyboard 操作按钮
  169. // * @param string $image 图片路径(可选)
  170. // * @param bool $isTop 是否置顶第一条消息
  171. // */
  172. // public static function bettingGroupNotice($text, $keyboard = [], $image = '', $isTop = false)
  173. // {
  174. // $bettingGroup = Config::where('field', 'betting_group')->first()->val;
  175. // $telegram = self::telegram();
  176. //
  177. // $maxLen = 1024; // Telegram 限制:最多 1024 个字符
  178. // $textParts = [];
  179. // $textLength = mb_strlen($text, 'UTF-8');
  180. // for ($i = 0; $i < $textLength; $i += $maxLen) {
  181. // $textParts[] = mb_substr($text, $i, $maxLen, 'UTF-8');
  182. // }
  183. //
  184. // $firstMessageId = null;
  185. //
  186. // foreach ($textParts as $index => $partText) {
  187. // $botMsg = [
  188. // 'chat_id' => "@{$bettingGroup}",
  189. // 'text' => $partText,
  190. // ];
  191. //
  192. // if (count($keyboard) > 0 && $index === 0) {
  193. // $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  194. // }
  195. //
  196. // if (!empty($image) && $index === 0) {
  197. // // 第一条带图片
  198. // $botMsg['photo'] = InputFile::create($image);
  199. // $botMsg['caption'] = $partText;
  200. // $botMsg['protect_content'] = true;
  201. // $response = $telegram->sendPhoto($botMsg);
  202. // } else {
  203. // $response = $telegram->sendMessage($botMsg);
  204. // }
  205. //
  206. // if ($isTop && $index === 0 && $response && $response->get('message_id')) {
  207. // $firstMessageId = $response->get('message_id');
  208. // }
  209. //
  210. // // 防止限流(可选)
  211. // usleep(300000);
  212. // }
  213. //
  214. // if ($isTop && $firstMessageId) {
  215. // $telegram->pinChatMessage([
  216. // 'chat_id' => "@{$bettingGroup}",
  217. // 'message_id' => $firstMessageId
  218. // ]);
  219. // }
  220. // }
  221. /**
  222. * @description: 群组通知
  223. * @apiParam string $text 通知内容
  224. * @apiParam array $keyboard 操作按钮
  225. * @apiParam string $separator 分隔符
  226. * @apiParam boolean $isTop 是否置顶
  227. */
  228. public static function bettingGroupNotice($text, $keyboard = [], $image = '', $isTop = false, $separator = "\n"): array
  229. {
  230. $bettingGroup = Config::where('field', 'betting_group')->first()->val;
  231. if (empty($separator)) $separator = "\n";
  232. $array = explode($separator, $text);
  233. $res = [];
  234. // 为空只发图片
  235. if (empty($text) && !empty($image)) {
  236. $botMsg = [
  237. 'chat_id' => "@{$bettingGroup}",
  238. ];
  239. $botMsg['photo'] = InputFile::create($image);
  240. $botMsg['caption'] = $text;
  241. $botMsg['protect_content'] = true; // 防止转发
  242. if (count($keyboard) > 0) {
  243. $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  244. }
  245. $response = self::telegram()->sendPhoto($botMsg);
  246. } else {
  247. foreach ($array as $key => $line) {
  248. if (empty(str_ireplace(" ", "", str_ireplace("\n", '', $line)))) {
  249. unset($array[$key]);
  250. } else {
  251. $array[$key] .= $separator;
  252. }
  253. }
  254. $texts = [];
  255. $len = !empty($image) ? 1024 : 4096;
  256. foreach ($array as $item) {
  257. if (count($texts) > 1) $len = 4096;
  258. if (count($texts) == 0 || strlen($texts[count($texts) - 1] . $item) > $len) {
  259. $texts[] = $item;
  260. } else {
  261. $texts[count($texts) - 1] .= $item;
  262. }
  263. }
  264. foreach ($texts as $index => $item) {
  265. $botMsg = [
  266. 'chat_id' => "@{$bettingGroup}",
  267. 'text' => $item,
  268. ];
  269. if ($index > 0) {
  270. $res[] = $botMsg;
  271. self::telegram()->sendMessage($botMsg);
  272. } else {
  273. if (count($keyboard) > 0) {
  274. $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  275. }
  276. if (!empty($image)) {
  277. unset($botMsg['text']);
  278. $botMsg['photo'] = InputFile::create($image);
  279. $botMsg['caption'] = $item;
  280. $botMsg['protect_content'] = true;
  281. $res[] = $botMsg;
  282. $response = self::telegram()->sendPhoto($botMsg);
  283. } else {
  284. $res[] = $botMsg;
  285. $response = self::telegram()->sendMessage($botMsg);
  286. }
  287. if ($isTop === true) {
  288. self::telegram()->pinChatMessage([
  289. 'chat_id' => "@{$bettingGroup}",
  290. 'message_id' => $response->get('message_id')
  291. ]);
  292. }
  293. }
  294. }
  295. }
  296. return $res;
  297. }
  298. /**
  299. * @description: 异步群组通知
  300. * @param {string} $text 通知内容
  301. * @param {array} $keyboard 操作按钮
  302. * @param {*string} $image 图片
  303. * @return {*}
  304. */
  305. public static function asyncBettingGroupNotice($text, $keyboard = [], $image = '', $isTop = false): void
  306. {
  307. SendTelegramGroupMessageJob::dispatch($text, $keyboard, $image, $isTop);
  308. }
  309. /**
  310. * @description: 发送消息
  311. * @param {string} $chatId 聊天ID
  312. * @param {string} $text 消息内容
  313. * @param {array} $keyboard 操作按钮
  314. * @param {*string} $image 图片
  315. * @return {*}
  316. */
  317. public static function sendMessage($chatId, $text, $keyboard = [], $image = ''): void
  318. {
  319. $botMsg = [
  320. 'chat_id' => $chatId,
  321. ];
  322. if (count($keyboard) > 0) {
  323. $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  324. }
  325. if ($image != '') {
  326. $botMsg['photo'] = InputFile::create($image);
  327. $botMsg['caption'] = $text;
  328. $botMsg['protect_content'] = false; // 防止转发
  329. self::telegram()->sendPhoto($botMsg);
  330. } else {
  331. $botMsg['text'] = $text;
  332. self::telegram()->sendMessage($botMsg);
  333. }
  334. }
  335. /**
  336. * @description: 异步发送消息
  337. * @param {string} $chatId 聊天ID
  338. * @param {string} $text 消息内容
  339. * @param {array} $keyboard 操作按钮
  340. * @param {*string} $image 图片
  341. * @return {*}
  342. */
  343. public static function asyncSendMessage($chatId, $text, $keyboard = [], $image = ''): void
  344. {
  345. SendTelegramMessageJob::dispatch($chatId, $text, $keyboard, $image);
  346. }
  347. /**
  348. * @description: 弹窗提示
  349. * @param {*} $memberId
  350. * @param {*} $address
  351. * @return {*}
  352. */
  353. public static function alertNotice($callbackId, $text): void
  354. {
  355. self::telegram()->answerCallbackQuery([
  356. 'callback_query_id' => $callbackId,
  357. 'text' => $text,
  358. 'show_alert' => true // 显示为弹窗
  359. ]);
  360. }
  361. public static function log($message, $context = [])
  362. {
  363. Log::error($message, $context);
  364. }
  365. /**
  366. * @description: 获取操作按钮
  367. * @return {*}
  368. */
  369. public static function getOperateButton()
  370. {
  371. $replyInfo = KeyboardService::findOne(['button' => '投注菜单']);
  372. if ($replyInfo && $replyInfo->buttons) {
  373. $buttons = json_decode($replyInfo->buttons, true);
  374. foreach ($buttons as $row) {
  375. $inlineButton[] = [];
  376. foreach ($row as $button) {
  377. $btn = ['text' => $button['text']];
  378. if (strpos($button['url'], 'http') === 0) {
  379. $btn['url'] = $button['url'];
  380. } else {
  381. $btn['callback_data'] = $button['url'];
  382. }
  383. $inlineButton[count($inlineButton) - 1][] = $btn;
  384. }
  385. }
  386. $inlineButton = array_values($inlineButton);
  387. return $inlineButton;
  388. }
  389. // $username = config('services.telegram.username');
  390. // $serviceAccount = Config::where('field', 'service_account')->first()->val??'';
  391. // $officialChannel = Config::where('field', 'official_channel')->first()->val??'';
  392. $inlineButton = [];
  393. // $inlineButton[] = [
  394. // ['text' => "查看余额", 'callback_data' => 'balanceAlert'],
  395. // ['text' => "✅唯一财务", 'url' => "https://t.me/{$serviceAccount}"]
  396. // ];
  397. // $inlineButton[] = [
  398. // ['text' => "近期注单", 'callback_data' => 'betsAlert'],
  399. // ['text' => "今日流水", 'callback_data' => 'todayFlowAlert']
  400. // ];
  401. // $inlineButton[] = [
  402. // ['text' => "私聊下注", 'url' => "https://t.me/{$username}"]
  403. // ];
  404. // $inlineButton[] = [
  405. // ['text' => "官方频道", 'url' => "https://t.me/{$officialChannel}"]
  406. // ];
  407. return $inlineButton;
  408. }
  409. // 获取字符串最后几个字符
  410. public static function getLastChar($str, $num = 1)
  411. {
  412. $length = mb_strlen($str, 'UTF-8');
  413. $lastChar = mb_substr($str, $length - 1, $num, 'UTF-8');
  414. return $lastChar;
  415. }
  416. public static function generateRandomString($length = 8)
  417. {
  418. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  419. $randomString = '';
  420. for ($i = 0; $i < $length; $i++) {
  421. $randomString .= $characters[rand(0, strlen($characters) - 1)];
  422. }
  423. return $randomString;
  424. }
  425. public static function generateRandomNumber($length = 8)
  426. {
  427. $characters = '0123456789';
  428. $randomString = '';
  429. for ($i = 0; $i < $length; $i++) {
  430. $randomString .= rand(1, 9);
  431. }
  432. return $randomString;
  433. }
  434. public static function hideMiddleDigits($number, $hideCount = 4)
  435. {
  436. $length = strlen($number);
  437. if ($length <= $hideCount) {
  438. // 数字太短,全部隐藏
  439. return str_repeat("*", $length);
  440. }
  441. // 计算中间开始隐藏的位置
  442. $startLen = floor(($length - $hideCount) / 2);
  443. $endLen = $length - $hideCount - $startLen;
  444. $start = substr($number, 0, $startLen);
  445. $end = substr($number, -$endLen);
  446. return $start . str_repeat("*", $hideCount) . $end;
  447. }
  448. // 生成订单号
  449. public static function createOrderNo($prefix = 'pc28_', $memberId = null)
  450. {
  451. // 处理会员ID,获取后四位
  452. if ($memberId) {
  453. $memberSuffix = str_pad(substr($memberId, -4), 4, '0', STR_PAD_LEFT);
  454. } else {
  455. $memberSuffix = '0000'; // 默认值
  456. }
  457. // 时间部分
  458. $timePart = date('YmdHis');
  459. // 随机部分增加唯一性
  460. $randomPart = mt_rand(1000, 9999);
  461. return $prefix . $timePart . $randomPart . $memberSuffix;
  462. }
  463. /**
  464. * @description: 生成支付二维码
  465. * @param {*} $address 支付地址
  466. * @return {*}
  467. */
  468. public static function createPaymentQrCode($address = '')
  469. {
  470. // $content = $address;
  471. $content = '';
  472. $qrSize = 300;
  473. $font = 4;
  474. $textHeight = 20;
  475. $padding = 10;
  476. // 生成二维码图像对象
  477. $result = Builder::create()
  478. ->writer(new PngWriter())
  479. ->data($address)
  480. ->size($qrSize)
  481. ->margin(0)
  482. ->build();
  483. $qrImage = imagecreatefromstring($result->getString());
  484. // 创建画布(加上下方文字区和边距)
  485. $canvasWidth = $qrSize + $padding * 2;
  486. $canvasHeight = $qrSize + $textHeight + $padding * 2;
  487. $image = imagecreatetruecolor($canvasWidth, $canvasHeight);
  488. // 背景白色
  489. $white = imagecolorallocate($image, 255, 255, 255);
  490. imagefill($image, 0, 0, $white);
  491. // 黑色字体
  492. $black = imagecolorallocate($image, 0, 0, 0);
  493. // 合并二维码图像
  494. imagecopy($image, $qrImage, $padding, $padding, 0, 0, $qrSize, $qrSize);
  495. // 写文字
  496. $textWidth = imagefontwidth($font) * strlen($content);
  497. $x = ($canvasWidth - $textWidth) / 2;
  498. $y = $qrSize + $padding + 5;
  499. imagestring($image, $font, $x, $y, $content, $black);
  500. $address_name = self::generateRandomString(20) . time();
  501. // 生成文件名
  502. $filename = $address_name . '.png';
  503. $relativePath = 'payment/' . $filename;
  504. $storagePath = storage_path('app/public/' . $relativePath);
  505. // 确保目录存在
  506. @mkdir(dirname($storagePath), 0777, true);
  507. // 保存图片到文件
  508. imagepng($image, $storagePath);
  509. // 清理
  510. imagedestroy($qrImage);
  511. imagedestroy($image);
  512. // 返回 public 存储路径(可用于 URL)
  513. return 'storage/' . $relativePath; // 或返回 Storage::url($relativePath);
  514. }
  515. }