BaseService.php 18 KB

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