BaseService.php 18 KB

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