ThirdGameBalanceService.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. <?php
  2. namespace App\Services;
  3. use App\Models\User;
  4. use Carbon\Carbon;
  5. use Illuminate\Http\Client\Pool;
  6. use Illuminate\Http\Client\Response;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\Http;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Facades\RateLimiter;
  11. class ThirdGameBalanceService
  12. {
  13. private const CODE_SUCCESS = 10000;
  14. private const HISTORY_QUERY_INTERVAL_SECONDS = 60;
  15. private const HISTORY_PAGE_INTERVAL_SECONDS = 10;
  16. private const HISTORY_HOURLY_LIMIT = 5;
  17. private const REALTIME_QUERY_INTERVAL_SECONDS = 60;
  18. private const GAME_TYPE_NAMES = [
  19. 1 => '视讯',
  20. 2 => '老虎机',
  21. 3 => '彩票',
  22. 4 => '体育',
  23. 5 => '电竞',
  24. 6 => '捕猎',
  25. 7 => '棋牌',
  26. ];
  27. private const ORDER_STATUS_NAMES = [
  28. 0 => '未完成',
  29. 1 => '已完成',
  30. 2 => '已取消',
  31. 3 => '已撤单',
  32. ];
  33. /**
  34. * 批量查询用户的三方游戏总余额,三方与主钱包金额按 1:1 处理。
  35. *
  36. * @param array<int, string|int> $memberIds
  37. * @return array<string, float|null>
  38. */
  39. public function totals(array $memberIds): array
  40. {
  41. $memberIds = array_values(array_unique(array_map('strval', $memberIds)));
  42. $totals = [];
  43. $pending = [];
  44. foreach ($memberIds as $memberId) {
  45. $cached = Cache::get($this->cacheKey($memberId));
  46. if ($cached !== null) {
  47. $totals[$memberId] = (float) $cached;
  48. } else {
  49. $pending[] = $memberId;
  50. }
  51. }
  52. if ($pending === []) {
  53. return $totals;
  54. }
  55. if (!$this->configured()) {
  56. Log::warning('third_game_balance_config_missing');
  57. foreach ($pending as $memberId) {
  58. $totals[$memberId] = null;
  59. }
  60. return $totals;
  61. }
  62. try {
  63. $responses = Http::pool(function (Pool $pool) use ($pending) {
  64. $requests = [];
  65. foreach ($pending as $memberId) {
  66. $random = $this->random();
  67. $requests[] = $pool->as($memberId)
  68. ->asJson()
  69. ->withHeaders([
  70. 'sign' => md5($random . config('third_game.sn') . config('third_game.key')),
  71. 'random' => $random,
  72. 'sn' => config('third_game.sn'),
  73. ])
  74. ->timeout(max(1, (int) config('third_game.timeout', 10)))
  75. ->connectTimeout(5)
  76. ->withOptions($this->httpOptions())
  77. ->post(config('third_game.api_url') . '/api/server/balanceAll', [
  78. 'playerId' => $this->playerId($memberId),
  79. 'currency' => config('third_game.currency', 'CNY'),
  80. ]);
  81. }
  82. return $requests;
  83. });
  84. } catch (\Throwable $e) {
  85. Log::warning('third_game_balance_pool_failed', ['message' => $e->getMessage()]);
  86. foreach ($pending as $memberId) {
  87. $totals[$memberId] = null;
  88. }
  89. return $totals;
  90. }
  91. foreach ($pending as $memberId) {
  92. $response = $responses[$memberId] ?? null;
  93. $balances = $this->balancesFromResponse($response);
  94. $total = $balances === null ? null : $this->totalFromBalances($balances);
  95. $totals[$memberId] = $total;
  96. if ($total !== null) {
  97. Cache::put(
  98. $this->cacheKey($memberId),
  99. $total,
  100. max(1, (int) config('third_game.cache_seconds', 30))
  101. );
  102. Cache::put(
  103. $this->detailCacheKey($memberId),
  104. $balances,
  105. max(1, (int) config('third_game.cache_seconds', 30))
  106. );
  107. }
  108. }
  109. return $totals;
  110. }
  111. /**
  112. * member_id 仅用于找到用户,三方唯一 ID 只取 users.id。
  113. */
  114. public function playerId(string $memberId): string
  115. {
  116. $memberId = trim($memberId);
  117. if ($memberId === '') {
  118. throw new \InvalidArgumentException('member_id 不能为空');
  119. }
  120. $userId = (int) User::query()->where('member_id', $memberId)->value('id');
  121. if ($userId <= 0) {
  122. throw new \InvalidArgumentException('用户不存在,无法生成三方玩家 ID');
  123. }
  124. return $this->playerIdFromUserId($userId);
  125. }
  126. /**
  127. * 新规则:直接 u + users.id,不补零、不做哈希。
  128. */
  129. public function playerIdFromUserId(int $userId): string
  130. {
  131. if ($userId <= 0) {
  132. throw new \InvalidArgumentException('users.id 必须是正整数');
  133. }
  134. return 'u' . $userId;
  135. }
  136. /**
  137. * 查询单个用户在 ag、pg 等各游戏平台的余额。
  138. */
  139. public function detail(string $memberId, bool $forceRefresh = false): array
  140. {
  141. if (!$forceRefresh) {
  142. $cached = Cache::get($this->detailCacheKey($memberId));
  143. if (is_array($cached)) {
  144. return $this->detailResult($memberId, $cached);
  145. }
  146. }
  147. $response = $this->request('/api/server/balanceAll', [
  148. 'playerId' => $this->playerId($memberId),
  149. 'currency' => config('third_game.currency', 'CNY'),
  150. ]);
  151. $balances = $this->balancesFromResponse($response);
  152. if ($balances === null) {
  153. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  154. }
  155. $ttl = max(1, (int) config('third_game.cache_seconds', 30));
  156. Cache::put($this->detailCacheKey($memberId), $balances, $ttl);
  157. Cache::put($this->cacheKey($memberId), $this->totalFromBalances($balances), $ttl);
  158. return $this->detailResult($memberId, $balances);
  159. }
  160. /**
  161. * 查询三方游戏历史订单,按订单更新时间正序返回。
  162. */
  163. public function historyOrders(
  164. string $startTime,
  165. string $endTime,
  166. int $page = 1,
  167. int $limit = 200
  168. ): array
  169. {
  170. if (!$this->configured()) {
  171. return ['ok' => false, 'msg' => '三方游戏配置缺失'];
  172. }
  173. $rangeError = $this->historyRangeError($startTime, $endTime);
  174. if ($rangeError !== null) {
  175. return ['ok' => false, 'msg' => $rangeError];
  176. }
  177. $rateError = $this->acquireHistoryQuota($startTime, $endTime, $page, $limit);
  178. if ($rateError !== null) {
  179. return ['ok' => false, 'msg' => $rateError];
  180. }
  181. $response = $this->request('/api/server/recordHistory', [
  182. 'currency' => (string) config('third_game.currency', 'CNY'),
  183. 'startTime' => $startTime,
  184. 'endTime' => $endTime,
  185. 'pageNo' => (string) $page,
  186. 'pageSize' => (string) $limit,
  187. ]);
  188. if (!$response instanceof Response) {
  189. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  190. }
  191. $body = $response->json();
  192. if (!is_array($body) || (int) ($body['code'] ?? 0) !== self::CODE_SUCCESS) {
  193. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  194. }
  195. $this->rememberHistorySession($startTime, $endTime, $limit);
  196. $providerData = is_array($body['data'] ?? null) ? $body['data'] : [];
  197. $providerList = is_array($providerData['list'] ?? null) ? $providerData['list'] : [];
  198. $list = [];
  199. foreach ($providerList as $row) {
  200. if (is_array($row)) {
  201. $list[] = $this->formatOrder($row);
  202. }
  203. }
  204. $result = [
  205. 'ok' => true,
  206. 'currency' => (string) config('third_game.currency', 'CNY'),
  207. 'start_time' => $startTime,
  208. 'end_time' => $endTime,
  209. 'total' => (int) ($providerData['total'] ?? count($list)),
  210. 'page_no' => (int) ($providerData['pageNo'] ?? $page),
  211. 'page_size' => (int) ($providerData['pageSize'] ?? $limit),
  212. 'list' => $list,
  213. ];
  214. return $result;
  215. }
  216. /**
  217. * 获取最近10分钟(不含当前分钟)的实时游戏订单。
  218. */
  219. public function realtimeOrders(int $page = 1, int $limit = 2000): array
  220. {
  221. if (!$this->configured()) {
  222. return ['ok' => false, 'msg' => '三方游戏配置缺失'];
  223. }
  224. $rateError = $this->acquireRealtimeQuota($page, $limit);
  225. if ($rateError !== null) {
  226. return ['ok' => false, 'msg' => $rateError];
  227. }
  228. $response = $this->request('/api/server/recordAll', [
  229. 'currency' => (string) config('third_game.currency', 'CNY'),
  230. 'pageNo' => (string) $page,
  231. 'pageSize' => (string) $limit,
  232. ]);
  233. if (!$response instanceof Response) {
  234. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  235. }
  236. $body = $response->json();
  237. if (!is_array($body) || (int) ($body['code'] ?? 0) !== self::CODE_SUCCESS) {
  238. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  239. }
  240. $this->rememberRealtimeSession($limit);
  241. $providerData = is_array($body['data'] ?? null) ? $body['data'] : [];
  242. $providerList = is_array($providerData['list'] ?? null) ? $providerData['list'] : [];
  243. $list = [];
  244. foreach ($providerList as $row) {
  245. if (is_array($row)) {
  246. $list[] = $this->formatOrder($row);
  247. }
  248. }
  249. return [
  250. 'ok' => true,
  251. 'currency' => (string) config('third_game.currency', 'CNY'),
  252. 'total' => (int) ($providerData['total'] ?? count($list)),
  253. 'page_no' => (int) ($providerData['pageNo'] ?? $page),
  254. 'page_size' => (int) ($providerData['pageSize'] ?? $limit),
  255. 'list' => $list,
  256. ];
  257. }
  258. /**
  259. * 一键把用户在所有三方游戏平台的余额转出。
  260. */
  261. public function recycle(string $memberId): array
  262. {
  263. // 必须在调用 transferAll 前校验,避免三方已转出后才因本地配置错误中断。
  264. $this->recycleRate();
  265. $response = $this->request('/api/server/transferAll', [
  266. 'playerId' => $this->playerId($memberId),
  267. 'currency' => config('third_game.currency', 'CNY'),
  268. ], true);
  269. $body = $response instanceof Response ? $response->json() : null;
  270. if (!is_array($body)) {
  271. return [
  272. 'ok' => false,
  273. 'uncertain' => true,
  274. 'msg' => $response instanceof Response
  275. ? '三方游戏接口返回异常,回收结果待核对'
  276. : '三方游戏接口请求失败,回收结果待核对',
  277. ];
  278. }
  279. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  280. $data = $body['data'] ?? null;
  281. if (!is_array($data)
  282. || !array_key_exists('balanceAll', $data)
  283. || !is_numeric($data['balanceAll'])
  284. || (float) $data['balanceAll'] < 0) {
  285. return [
  286. 'ok' => false,
  287. 'uncertain' => true,
  288. 'msg' => '三方游戏回收成功响应缺少有效 balanceAll,回收结果待核对',
  289. ];
  290. }
  291. $gameBalance = $this->decimalAmount($data['balanceAll']);
  292. if ($gameBalance === null) {
  293. return [
  294. 'ok' => false,
  295. 'uncertain' => true,
  296. 'msg' => '三方游戏回收金额格式异常,回收结果待核对',
  297. ];
  298. }
  299. $this->clearCache($memberId);
  300. return [
  301. 'ok' => true,
  302. 'game_balance' => $gameBalance,
  303. 'wallet_balance' => $this->toWalletBalance($gameBalance),
  304. ];
  305. }
  306. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  307. $this->clearCache($memberId);
  308. return ['ok' => true, 'game_balance' => '0.0000000000', 'wallet_balance' => '0.0000000000'];
  309. }
  310. return [
  311. 'ok' => false,
  312. 'uncertain' => false,
  313. 'msg' => $this->responseMessage($response),
  314. ];
  315. }
  316. public function toWalletBalance($gameBalance): string
  317. {
  318. $balance = $this->decimalAmount($gameBalance);
  319. if ($balance === null) {
  320. throw new \InvalidArgumentException('三方游戏余额格式异常');
  321. }
  322. return bcdiv($balance, $this->recycleRate(), 10);
  323. }
  324. private function recycleRate(): string
  325. {
  326. $rate = trim((string) config('third_game.recycle_rate', '1'));
  327. if (!preg_match('/^\d+(?:\.\d+)?$/D', $rate) || bccomp($rate, '0', 10) <= 0) {
  328. throw new \RuntimeException('GAME_RECYCLE_RATE 必须是大于 0 的数字');
  329. }
  330. return $rate;
  331. }
  332. private function balancesFromResponse($response): ?array
  333. {
  334. if (!$response instanceof Response) {
  335. return null;
  336. }
  337. $body = $response->json();
  338. if (!is_array($body)) {
  339. return null;
  340. }
  341. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  342. return is_array($body['data'] ?? null) ? $body['data'] : [];
  343. }
  344. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  345. return [];
  346. }
  347. Log::warning('third_game_balance_query_failed', [
  348. 'code' => $body['code'] ?? null,
  349. 'msg' => $body['msg'] ?? null,
  350. ]);
  351. return null;
  352. }
  353. private function detailResult(string $memberId, array $balances): array
  354. {
  355. $gameBalance = $this->sumBalances($balances);
  356. $walletBalances = [];
  357. $gameBalances = [];
  358. foreach ($balances as $platform => $balance) {
  359. if (is_numeric($balance)) {
  360. $walletBalances[] = [
  361. 'platform' => (string) $platform,
  362. 'balance' => (float) $balance,
  363. ];
  364. $gameBalances[] = [
  365. 'platform' => (string) $platform,
  366. 'balance' => (float) $balance,
  367. ];
  368. }
  369. }
  370. return [
  371. 'ok' => true,
  372. 'member_id' => $memberId,
  373. 'player_id' => $this->playerId($memberId),
  374. 'currency' => (string) config('third_game.currency', 'CNY'),
  375. 'rate' => 1,
  376. 'list' => $walletBalances,
  377. 'game_list' => $gameBalances,
  378. 'total_game_balance' => (float) $gameBalance,
  379. 'total_balance' => $this->totalFromBalances($balances),
  380. ];
  381. }
  382. private function totalFromBalances(array $balances): float
  383. {
  384. return (float) $this->sumBalances($balances);
  385. }
  386. private function sumBalances(array $balances): string
  387. {
  388. $total = '0.0000000000';
  389. foreach ($balances as $balance) {
  390. $amount = $this->decimalAmount($balance);
  391. if ($amount !== null) {
  392. $total = bcadd($total, $amount, 10);
  393. }
  394. }
  395. return $total;
  396. }
  397. private function decimalAmount($value): ?string
  398. {
  399. if (!is_int($value) && !is_float($value) && !is_string($value)) {
  400. return null;
  401. }
  402. $value = trim((string) $value);
  403. if (!preg_match('/^\d+(?:\.\d+)?$/D', $value)) {
  404. return null;
  405. }
  406. return bcadd($value, '0', 10);
  407. }
  408. private function request(string $path, array $data, bool $transfer = false)
  409. {
  410. if (!$this->configured()) {
  411. return null;
  412. }
  413. $random = $this->random();
  414. try {
  415. return Http::asJson()
  416. ->withHeaders([
  417. 'sign' => md5($random . config('third_game.sn') . config('third_game.key')),
  418. 'random' => $random,
  419. 'sn' => config('third_game.sn'),
  420. ])
  421. ->timeout(max(1, (int) config(
  422. $transfer ? 'third_game.transfer_timeout' : 'third_game.timeout',
  423. $transfer ? 65 : 10
  424. )))
  425. ->connectTimeout(5)
  426. ->withOptions($this->httpOptions())
  427. ->post(config('third_game.api_url') . $path, $data);
  428. } catch (\Throwable $e) {
  429. Log::warning('third_game_request_failed', [
  430. 'path' => $path,
  431. 'message' => $e->getMessage(),
  432. ]);
  433. return null;
  434. }
  435. }
  436. private function responseMessage($response): string
  437. {
  438. if (!$response instanceof Response) {
  439. return $this->configured() ? '三方游戏接口请求失败' : '三方游戏配置缺失';
  440. }
  441. return (string) ($response->json('msg') ?: '三方游戏接口异常');
  442. }
  443. private function formatOrder(array $row): array
  444. {
  445. $gameType = (int) ($row['gameType'] ?? 0);
  446. $status = (int) ($row['status'] ?? -1);
  447. return [
  448. 'player_id' => (string) ($row['playerId'] ?? ''),
  449. 'platform' => (string) ($row['platType'] ?? ''),
  450. 'currency' => (string) ($row['currency'] ?? ''),
  451. 'game_type' => $gameType,
  452. 'game_type_text' => self::GAME_TYPE_NAMES[$gameType] ?? '未知',
  453. 'game_name' => (string) ($row['gameName'] ?? ''),
  454. 'round' => (string) ($row['round'] ?? ''),
  455. 'table' => (string) ($row['table'] ?? ''),
  456. 'seat' => (string) ($row['seat'] ?? ''),
  457. 'bet_amount' => $this->numericValue($row['betAmount'] ?? null),
  458. 'valid_amount' => $this->numericValue($row['validAmount'] ?? null),
  459. 'settled_amount' => $this->numericValue($row['settledAmount'] ?? null),
  460. 'bet_content' => $row['betContent'] ?? '',
  461. 'status' => $status,
  462. 'status_text' => self::ORDER_STATUS_NAMES[$status] ?? '未知',
  463. 'game_order_id' => (string) ($row['gameOrderId'] ?? ''),
  464. 'bet_time' => (string) ($row['betTime'] ?? ''),
  465. 'last_update_time' => (string) ($row['lastUpdateTime'] ?? ''),
  466. ];
  467. }
  468. private function numericValue($value)
  469. {
  470. return is_numeric($value) ? $value + 0 : null;
  471. }
  472. private function historyRangeError(string $startTime, string $endTime): ?string
  473. {
  474. $timezone = config('app.timezone', 'Asia/Shanghai');
  475. $start = Carbon::createFromFormat('Y-m-d H:i:s', $startTime, $timezone);
  476. $end = Carbon::createFromFormat('Y-m-d H:i:s', $endTime, $timezone);
  477. if ($start->gt($end)) {
  478. return '开始时间不能大于结束时间';
  479. }
  480. if ($start->diffInSeconds($end) > 6 * 60 * 60) {
  481. return '查询时间范围不能超过6小时';
  482. }
  483. if ($start->lt(Carbon::now($timezone)->subDays(15))) {
  484. return '只能查询最近15天内的订单';
  485. }
  486. return null;
  487. }
  488. private function acquireHistoryQuota(
  489. string $startTime,
  490. string $endTime,
  491. int $page,
  492. int $limit
  493. ): ?string
  494. {
  495. $prefix = $this->historyRatePrefix();
  496. $sessionKey = $this->historySessionKey($startTime, $endTime, $limit);
  497. $lock = Cache::lock($prefix . ':lock', 5);
  498. if (!$lock->get()) {
  499. return '订单查询正在处理中,请稍后重试';
  500. }
  501. try {
  502. $now = time();
  503. $lastRequestAt = (int) Cache::get($prefix . ':last_request', 0);
  504. if ($lastRequestAt > 0 && $now - $lastRequestAt < self::HISTORY_PAGE_INTERVAL_SECONDS) {
  505. $retryAfter = self::HISTORY_PAGE_INTERVAL_SECONDS - ($now - $lastRequestAt);
  506. return "订单请求至少间隔10秒,请在{$retryAfter}秒后重试";
  507. }
  508. $isPagination = $page > 1 && Cache::has($sessionKey);
  509. if (!$isPagination) {
  510. $lastQueryAt = (int) Cache::get($prefix . ':last_query', 0);
  511. if ($lastQueryAt > 0 && $now - $lastQueryAt < self::HISTORY_QUERY_INTERVAL_SECONDS) {
  512. $retryAfter = self::HISTORY_QUERY_INTERVAL_SECONDS - ($now - $lastQueryAt);
  513. return "订单查询至少间隔1分钟,请在{$retryAfter}秒后重试";
  514. }
  515. $hourlyKey = $prefix . ':hourly';
  516. if (RateLimiter::tooManyAttempts($hourlyKey, self::HISTORY_HOURLY_LIMIT)) {
  517. $retryAfter = max(1, RateLimiter::availableIn($hourlyKey));
  518. return "订单查询每小时最多5次,请在{$retryAfter}秒后重试";
  519. }
  520. RateLimiter::hit($hourlyKey, 3600);
  521. Cache::put($prefix . ':last_query', $now, self::HISTORY_QUERY_INTERVAL_SECONDS);
  522. }
  523. Cache::put($prefix . ':last_request', $now, self::HISTORY_PAGE_INTERVAL_SECONDS);
  524. return null;
  525. } finally {
  526. $lock->release();
  527. }
  528. }
  529. private function acquireRealtimeQuota(int $page, int $limit): ?string
  530. {
  531. $sessionKey = $this->realtimeSessionKey($limit);
  532. if ($page > 1 && Cache::has($sessionKey)) {
  533. return null;
  534. }
  535. $prefix = $this->realtimeRatePrefix();
  536. $lock = Cache::lock($prefix . ':lock', 5);
  537. if (!$lock->get()) {
  538. return '实时订单同步正在处理中,请稍后重试';
  539. }
  540. try {
  541. if ($page > 1 && Cache::has($sessionKey)) {
  542. return null;
  543. }
  544. $now = time();
  545. $lastQueryAt = (int) Cache::get($prefix . ':last_query', 0);
  546. if ($lastQueryAt > 0 && $now - $lastQueryAt < self::REALTIME_QUERY_INTERVAL_SECONDS) {
  547. $retryAfter = self::REALTIME_QUERY_INTERVAL_SECONDS - ($now - $lastQueryAt);
  548. return "实时订单同步每分钟最多请求1次,请在{$retryAfter}秒后重试";
  549. }
  550. Cache::put($prefix . ':last_query', $now, self::REALTIME_QUERY_INTERVAL_SECONDS);
  551. return null;
  552. } finally {
  553. $lock->release();
  554. }
  555. }
  556. private function configured(): bool
  557. {
  558. return config('third_game.api_url') !== ''
  559. && config('third_game.sn') !== ''
  560. && config('third_game.key') !== '';
  561. }
  562. private function isPlayerNotFound(string $message): bool
  563. {
  564. $message = strtolower($message);
  565. return str_contains($message, 'playerid')
  566. && (str_contains($message, '不存在')
  567. || str_contains($message, 'not exist')
  568. || str_contains($message, 'not found'));
  569. }
  570. private function httpOptions(): array
  571. {
  572. $options = [];
  573. $proxy = (string) config('third_game.proxy', '');
  574. if ($proxy !== '') {
  575. $options['proxy'] = $proxy;
  576. }
  577. $caBundle = (string) config('third_game.ca_bundle', '');
  578. if ($caBundle !== '') {
  579. $options['verify'] = $caBundle;
  580. }
  581. return $options;
  582. }
  583. private function cacheKey(string $memberId): string
  584. {
  585. return 'third_game_total_balance:' . $memberId;
  586. }
  587. private function detailCacheKey(string $memberId): string
  588. {
  589. return 'third_game_balance_detail:' . $memberId;
  590. }
  591. private function historyRatePrefix(): string
  592. {
  593. return 'third_game_order_history:' . md5((string) config('third_game.sn'));
  594. }
  595. private function realtimeRatePrefix(): string
  596. {
  597. return 'third_game_order_realtime:' . md5((string) config('third_game.sn'));
  598. }
  599. private function historySessionKey(string $startTime, string $endTime, int $limit): string
  600. {
  601. return $this->historyRatePrefix() . ':session:' . md5($startTime . '|' . $endTime . '|' . $limit);
  602. }
  603. private function rememberHistorySession(string $startTime, string $endTime, int $limit): void
  604. {
  605. Cache::put($this->historySessionKey($startTime, $endTime, $limit), true, 3600);
  606. }
  607. private function realtimeSessionKey(int $limit): string
  608. {
  609. return $this->realtimeRatePrefix() . ':session:' . $limit;
  610. }
  611. private function rememberRealtimeSession(int $limit): void
  612. {
  613. Cache::put($this->realtimeSessionKey($limit), true, 600);
  614. }
  615. private function clearCache(string $memberId): void
  616. {
  617. Cache::forget($this->cacheKey($memberId));
  618. Cache::forget($this->detailCacheKey($memberId));
  619. }
  620. private function random(): string
  621. {
  622. $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
  623. $value = '';
  624. for ($i = 0; $i < 32; $i++) {
  625. $value .= $characters[random_int(0, strlen($characters) - 1)];
  626. }
  627. return $value;
  628. }
  629. }