BaseService.php 17 KB

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