BaseService.php 17 KB

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