BaseService.php 18 KB

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