BaseService.php 17 KB

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