BaseService.php 16 KB

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