BaseService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. namespace App\Services;
  3. use SimpleSoftwareIO\QrCode\Facades\QrCode;
  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. class BaseService
  13. {
  14. const YES = 1;
  15. const NOT = 0;
  16. /**
  17. * @description: 生成充值二维码
  18. * @param {*} $address 充值地址
  19. * @return {*}
  20. */
  21. public static function createRechargeQrCode($address = '')
  22. {
  23. $content = $address;
  24. $qrSize = 300;
  25. $font = 4;
  26. $textHeight = 20;
  27. $padding = 10;
  28. // 生成二维码图像对象
  29. $result = Builder::create()
  30. ->writer(new PngWriter())
  31. ->data($content)
  32. ->size($qrSize)
  33. ->margin(0)
  34. ->build();
  35. $qrImage = imagecreatefromstring($result->getString());
  36. // 创建画布(加上下方文字区和边距)
  37. $canvasWidth = $qrSize + $padding * 2;
  38. $canvasHeight = $qrSize + $textHeight + $padding * 2;
  39. $image = imagecreatetruecolor($canvasWidth, $canvasHeight);
  40. // 背景白色
  41. $white = imagecolorallocate($image, 255, 255, 255);
  42. imagefill($image, 0, 0, $white);
  43. // 黑色字体
  44. $black = imagecolorallocate($image, 0, 0, 0);
  45. // 合并二维码图像
  46. imagecopy($image, $qrImage, $padding, $padding, 0, 0, $qrSize, $qrSize);
  47. // 写文字
  48. $textWidth = imagefontwidth($font) * strlen($content);
  49. $x = ($canvasWidth - $textWidth) / 2;
  50. $y = $qrSize + $padding + 5;
  51. imagestring($image, $font, $x, $y, $content, $black);
  52. // 生成文件名
  53. $filename = $address. '.png';
  54. $relativePath = 'recharge/' . $filename;
  55. $storagePath = storage_path('app/public/' . $relativePath);
  56. // 确保目录存在
  57. @mkdir(dirname($storagePath), 0777, true);
  58. // 保存图片到文件
  59. imagepng($image, $storagePath);
  60. // 清理
  61. imagedestroy($qrImage);
  62. imagedestroy($image);
  63. // 返回 public 存储路径(可用于 URL)
  64. return 'storage/'.$relativePath; // 或返回 Storage::url($relativePath);
  65. }
  66. /**
  67. * 判断指定地址的二维码是否已生成(已存在文件)
  68. *
  69. * @param string $address 充值地址
  70. * @return
  71. */
  72. public static function rechargeQrCodeExists(string $address)
  73. {
  74. $filename = $address . '.png';
  75. $relativePath = 'recharge/' . $filename;
  76. $storagePath = storage_path('app/public/' . $relativePath);
  77. $path = '';
  78. if(file_exists($storagePath)){
  79. $path = 'storage/'.$relativePath;
  80. }
  81. return $path;
  82. }
  83. /**
  84. * @description: 转成树形数据
  85. * @param {*} $list 初始数据
  86. * @param {*} $pid 父id
  87. * @param {*} $level 层级
  88. * @param {*} $pid_name pid字段名称 默认pid
  89. * @param {*} $id_name 主键id 名称
  90. * @return {*}
  91. */
  92. public static function toTree($list,$pid=0,$level=0,$pid_name='pid',$id_name='id')
  93. {
  94. $arr=[];
  95. $level++;
  96. foreach($list as $k => $v){
  97. if($pid==$v[$pid_name]){
  98. $v['level']=$level;
  99. $v['children']=self::toTree($list,$v[$id_name],$level,$pid_name,$id_name);
  100. $arr[]=$v;
  101. }
  102. }
  103. return $arr;
  104. }
  105. /**
  106. * @description: 实例化TG
  107. * @return {*}
  108. */
  109. public static function telegram()
  110. {
  111. return app(Api::class);
  112. }
  113. /**
  114. * @description: 群组通知(自动分段发送,支持中文与多字节字符)
  115. * @param string $text 通知内容
  116. * @param array $keyboard 操作按钮
  117. * @param string $image 图片路径(可选)
  118. * @param bool $isTop 是否置顶第一条消息
  119. */
  120. public static function bettingGroupNotice($text, $keyboard = [], $image = '', $isTop = false)
  121. {
  122. $bettingGroup = Config::where('field', 'betting_group')->first()->val;
  123. $telegram = self::telegram();
  124. $maxLen = 1024; // 每条最多 1024 个字符(不是字节)
  125. $textParts = [];
  126. $textLength = mb_strlen($text, 'UTF-8');
  127. for ($i = 0; $i < $textLength; $i += $maxLen) {
  128. $textParts[] = mb_substr($text, $i, $maxLen, 'UTF-8');
  129. }
  130. $firstMessageId = null;
  131. foreach ($textParts as $index => $partText) {
  132. $botMsg = [
  133. 'chat_id' => "@{$bettingGroup}",
  134. 'text' => $partText,
  135. ];
  136. if (count($keyboard) > 0 && $index === 0) {
  137. $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  138. }
  139. if (!empty($image) && $index === 0) {
  140. // 第一条带图片
  141. $botMsg['photo'] = InputFile::create($image);
  142. $botMsg['caption'] = $partText;
  143. $botMsg['protect_content'] = true;
  144. $response = $telegram->sendPhoto($botMsg);
  145. } else {
  146. $response = $telegram->sendMessage($botMsg);
  147. }
  148. if ($isTop && $index === 0 && $response && $response->get('message_id')) {
  149. $firstMessageId = $response->get('message_id');
  150. }
  151. // 防止被限流
  152. usleep(300000); // 0.3 秒
  153. }
  154. if ($isTop && $firstMessageId) {
  155. $telegram->pinChatMessage([
  156. 'chat_id' => "@{$bettingGroup}",
  157. 'message_id' => $firstMessageId
  158. ]);
  159. }
  160. }
  161. /**
  162. * @description: 异步群组通知
  163. * @param {string} $text 通知内容
  164. * @param {array} $keyboard 操作按钮
  165. * @param {*string} $image 图片
  166. * @return {*}
  167. */
  168. public static function asyncBettingGroupNotice($text ,$keyboard = [], $image = '' ,$isTop = false)
  169. {
  170. SendTelegramGroupMessageJob::dispatch($text ,$keyboard ,$image ,$isTop);
  171. }
  172. /**
  173. * @description: 发送消息
  174. * @param {string} $chatId 聊天ID
  175. * @param {string} $text 消息内容
  176. * @param {array} $keyboard 操作按钮
  177. * @param {*string} $image 图片
  178. * @return {*}
  179. */
  180. public static function sendMessage($chatId ,$text ,$keyboard = [] ,$image = '')
  181. {
  182. $botMsg = [
  183. 'chat_id' => $chatId,
  184. ];
  185. if(count($keyboard)>0){
  186. $botMsg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  187. }
  188. if($image != ''){
  189. $botMsg['photo'] = InputFile::create($image);
  190. $botMsg['caption'] = $text;
  191. $botMsg['protect_content'] = true; // 防止转发
  192. self::telegram()->sendPhoto($botMsg);
  193. }else{
  194. $botMsg['text'] = $text;
  195. self::telegram()->sendMessage($botMsg);
  196. }
  197. }
  198. /**
  199. * @description: 异步发送消息
  200. * @param {string} $chatId 聊天ID
  201. * @param {string} $text 消息内容
  202. * @param {array} $keyboard 操作按钮
  203. * @param {*string} $image 图片
  204. * @return {*}
  205. */
  206. public static function asyncSendMessage($chatId ,$text ,$keyboard = [] ,$image = '')
  207. {
  208. SendTelegramMessageJob::dispatch($chatId ,$text ,$keyboard ,$image);
  209. }
  210. /**
  211. * @description: 弹窗提示
  212. * @param {*} $memberId
  213. * @param {*} $address
  214. * @return {*}
  215. */
  216. public static function alertNotice($callbackId ,$text)
  217. {
  218. self::telegram()->answerCallbackQuery([
  219. 'callback_query_id' => $callbackId,
  220. 'text' => $text,
  221. 'show_alert' => true // 显示为弹窗
  222. ]);
  223. }
  224. public static function log($message, $context = [])
  225. {
  226. Log::error($message, $context);
  227. }
  228. /**
  229. * @description: 获取操作按钮
  230. * @return {*}
  231. */
  232. public static function getOperateButton()
  233. {
  234. $replyInfo = KeyboardService::findOne(['button' => '投注菜单']);
  235. if($replyInfo && $replyInfo->buttons){
  236. $buttons = json_decode($replyInfo->buttons, true);
  237. foreach ($buttons as $row) {
  238. $inlineButton[] = [];
  239. foreach ($row as $button) {
  240. $btn = ['text' => $button['text']];
  241. if(strpos($button['url'], 'http') === 0){
  242. $btn['url'] = $button['url'];
  243. }else{
  244. $btn['callback_data'] = $button['url'];
  245. }
  246. $inlineButton[count($inlineButton) - 1][] = $btn;
  247. // if (isset($button['text'])) {
  248. // $btn = ['text' => $button['text']];
  249. // if (isset($button['callback_data'])) {
  250. // $btn['callback_data'] = $button['callback_data'];
  251. // }
  252. // if (isset($button['url'])) {
  253. // $btn['url'] = $button['url'];
  254. // }
  255. // $inlineButton[count($inlineButton) - 1][] = $btn;
  256. // }
  257. }
  258. }
  259. $inlineButton = array_values($inlineButton);
  260. return $inlineButton;
  261. }
  262. // $username = config('services.telegram.username');
  263. // $serviceAccount = Config::where('field', 'service_account')->first()->val??'';
  264. // $officialChannel = Config::where('field', 'official_channel')->first()->val??'';
  265. $inlineButton = [];
  266. // $inlineButton[] = [
  267. // ['text' => "查看余额", 'callback_data' => 'balanceAlert'],
  268. // ['text' => "✅唯一财务", 'url' => "https://t.me/{$serviceAccount}"]
  269. // ];
  270. // $inlineButton[] = [
  271. // ['text' => "近期注单", 'callback_data' => 'betsAlert'],
  272. // ['text' => "今日流水", 'callback_data' => 'todayFlowAlert']
  273. // ];
  274. // $inlineButton[] = [
  275. // ['text' => "私聊下注", 'url' => "https://t.me/{$username}"]
  276. // ];
  277. // $inlineButton[] = [
  278. // ['text' => "官方频道", 'url' => "https://t.me/{$officialChannel}"]
  279. // ];
  280. return $inlineButton;
  281. }
  282. // 获取字符串最后几个字符
  283. public static function getLastChar($str,$num = 1)
  284. {
  285. $length = mb_strlen($str, 'UTF-8');
  286. $lastChar = mb_substr($str, $length - 1, $num, 'UTF-8');
  287. return $lastChar;
  288. }
  289. public static function generateRandomString($length = 8) {
  290. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  291. $randomString = '';
  292. for ($i = 0; $i < $length; $i++) {
  293. $randomString .= $characters[rand(0, strlen($characters) - 1)];
  294. }
  295. return $randomString;
  296. }
  297. public static function generateRandomNumber($length = 8) {
  298. $characters = '0123456789';
  299. $randomString = '';
  300. for ($i = 0; $i < $length; $i++) {
  301. $randomString .= rand(1, 9);
  302. }
  303. return $randomString;
  304. }
  305. public static function hideMiddleDigits($number, $hideCount = 4) {
  306. $length = strlen($number);
  307. if ($length <= $hideCount) {
  308. // 数字太短,全部隐藏
  309. return str_repeat("*", $length);
  310. }
  311. // 计算中间开始隐藏的位置
  312. $startLen = floor(($length - $hideCount) / 2);
  313. $endLen = $length - $hideCount - $startLen;
  314. $start = substr($number, 0, $startLen);
  315. $end = substr($number, -$endLen);
  316. return $start . str_repeat("*", $hideCount) . $end;
  317. }
  318. // 生成订单号
  319. public static function createOrderNo($prefix = 'pc28_',$memberId = null)
  320. {
  321. // 处理会员ID,获取后四位
  322. if ($memberId) {
  323. $memberSuffix = str_pad(substr($memberId, -4), 4, '0', STR_PAD_LEFT);
  324. } else {
  325. $memberSuffix = '0000'; // 默认值
  326. }
  327. // 时间部分
  328. $timePart = date('YmdHis');
  329. // 随机部分增加唯一性
  330. $randomPart = mt_rand(1000, 9999);
  331. return $prefix . $timePart . $randomPart . $memberSuffix;
  332. }
  333. }