ThirdGameBalanceService.php 24 KB

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