ThirdGameBalanceService.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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. public function agentPlayerId(int $agentId): string
  137. {
  138. if ($agentId <= 0) {
  139. throw new \InvalidArgumentException('agents.id 必须是正整数');
  140. }
  141. return 'a' . $agentId;
  142. }
  143. /**
  144. * 查询代理自己在各三方游戏平台的余额。玩家不存在时返回空 balances,调用方按平台补 0。
  145. */
  146. public function agentBalances(int $agentId, bool $forceRefresh = false): array
  147. {
  148. $identity = 'agent:' . $agentId;
  149. $playerId = $this->agentPlayerId($agentId);
  150. if (!$forceRefresh) {
  151. $cached = Cache::get($this->detailCacheKey($identity));
  152. if (is_array($cached)) {
  153. return $this->agentBalanceResult($agentId, $playerId, $cached);
  154. }
  155. }
  156. $response = $this->request('/api/server/balanceAll', [
  157. 'playerId' => $playerId,
  158. 'currency' => config('third_game.currency', 'CNY'),
  159. ]);
  160. $balances = $this->balancesFromResponse($response);
  161. if ($balances === null) {
  162. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  163. }
  164. Cache::put(
  165. $this->detailCacheKey($identity),
  166. $balances,
  167. max(1, (int) config('third_game.cache_seconds', 30))
  168. );
  169. return $this->agentBalanceResult($agentId, $playerId, $balances);
  170. }
  171. /**
  172. * 查询单个用户在 ag、pg 等各游戏平台的余额。
  173. */
  174. public function detail(string $memberId, bool $forceRefresh = false): array
  175. {
  176. if (!$forceRefresh) {
  177. $cached = Cache::get($this->detailCacheKey($memberId));
  178. if (is_array($cached)) {
  179. return $this->detailResult($memberId, $cached);
  180. }
  181. }
  182. $response = $this->request('/api/server/balanceAll', [
  183. 'playerId' => $this->playerId($memberId),
  184. 'currency' => config('third_game.currency', 'CNY'),
  185. ]);
  186. $balances = $this->balancesFromResponse($response);
  187. if ($balances === null) {
  188. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  189. }
  190. $ttl = max(1, (int) config('third_game.cache_seconds', 30));
  191. Cache::put($this->detailCacheKey($memberId), $balances, $ttl);
  192. Cache::put($this->cacheKey($memberId), $this->totalFromBalances($balances), $ttl);
  193. return $this->detailResult($memberId, $balances);
  194. }
  195. /**
  196. * 查询三方游戏历史订单,按订单更新时间正序返回。
  197. */
  198. public function historyOrders(
  199. string $startTime,
  200. string $endTime,
  201. int $page = 1,
  202. int $limit = 200
  203. ): array
  204. {
  205. if (!$this->configured()) {
  206. return ['ok' => false, 'msg' => '三方游戏配置缺失'];
  207. }
  208. $rangeError = $this->historyRangeError($startTime, $endTime);
  209. if ($rangeError !== null) {
  210. return ['ok' => false, 'msg' => $rangeError];
  211. }
  212. $rateError = $this->acquireHistoryQuota($startTime, $endTime, $page, $limit);
  213. if ($rateError !== null) {
  214. return ['ok' => false, 'msg' => $rateError];
  215. }
  216. $response = $this->request('/api/server/recordHistory', [
  217. 'currency' => (string) config('third_game.currency', 'CNY'),
  218. 'startTime' => $startTime,
  219. 'endTime' => $endTime,
  220. 'pageNo' => (string) $page,
  221. 'pageSize' => (string) $limit,
  222. ]);
  223. if (!$response instanceof Response) {
  224. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  225. }
  226. $body = $response->json();
  227. if (!is_array($body) || (int) ($body['code'] ?? 0) !== self::CODE_SUCCESS) {
  228. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  229. }
  230. $this->rememberHistorySession($startTime, $endTime, $limit);
  231. $providerData = is_array($body['data'] ?? null) ? $body['data'] : [];
  232. $providerList = is_array($providerData['list'] ?? null) ? $providerData['list'] : [];
  233. $list = [];
  234. foreach ($providerList as $row) {
  235. if (is_array($row)) {
  236. $list[] = $this->formatOrder($row);
  237. }
  238. }
  239. $result = [
  240. 'ok' => true,
  241. 'currency' => (string) config('third_game.currency', 'CNY'),
  242. 'start_time' => $startTime,
  243. 'end_time' => $endTime,
  244. 'total' => (int) ($providerData['total'] ?? count($list)),
  245. 'page_no' => (int) ($providerData['pageNo'] ?? $page),
  246. 'page_size' => (int) ($providerData['pageSize'] ?? $limit),
  247. 'list' => $list,
  248. ];
  249. return $result;
  250. }
  251. /**
  252. * 获取最近10分钟(不含当前分钟)的实时游戏订单。
  253. */
  254. public function realtimeOrders(int $page = 1, int $limit = 2000): array
  255. {
  256. if (!$this->configured()) {
  257. return ['ok' => false, 'msg' => '三方游戏配置缺失'];
  258. }
  259. $rateError = $this->acquireRealtimeQuota($page, $limit);
  260. if ($rateError !== null) {
  261. return ['ok' => false, 'msg' => $rateError];
  262. }
  263. $response = $this->request('/api/server/recordAll', [
  264. 'currency' => (string) config('third_game.currency', 'CNY'),
  265. 'pageNo' => (string) $page,
  266. 'pageSize' => (string) $limit,
  267. ]);
  268. if (!$response instanceof Response) {
  269. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  270. }
  271. $body = $response->json();
  272. if (!is_array($body) || (int) ($body['code'] ?? 0) !== self::CODE_SUCCESS) {
  273. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  274. }
  275. $this->rememberRealtimeSession($limit);
  276. $providerData = is_array($body['data'] ?? null) ? $body['data'] : [];
  277. $providerList = is_array($providerData['list'] ?? null) ? $providerData['list'] : [];
  278. $list = [];
  279. foreach ($providerList as $row) {
  280. if (is_array($row)) {
  281. $list[] = $this->formatOrder($row);
  282. }
  283. }
  284. return [
  285. 'ok' => true,
  286. 'currency' => (string) config('third_game.currency', 'CNY'),
  287. 'total' => (int) ($providerData['total'] ?? count($list)),
  288. 'page_no' => (int) ($providerData['pageNo'] ?? $page),
  289. 'page_size' => (int) ($providerData['pageSize'] ?? $limit),
  290. 'list' => $list,
  291. ];
  292. }
  293. /**
  294. * 一键把用户在所有三方游戏平台的余额转出。
  295. */
  296. public function recycle(string $memberId): array
  297. {
  298. // 必须在调用 transferAll 前校验,避免三方已转出后才因本地配置错误中断。
  299. $this->recycleRate();
  300. $response = $this->request('/api/server/transferAll', [
  301. 'playerId' => $this->playerId($memberId),
  302. 'currency' => config('third_game.currency', 'CNY'),
  303. ], true);
  304. $body = $response instanceof Response ? $response->json() : null;
  305. if (!is_array($body)) {
  306. return [
  307. 'ok' => false,
  308. 'uncertain' => true,
  309. 'msg' => $response instanceof Response
  310. ? '三方游戏接口返回异常,回收结果待核对'
  311. : '三方游戏接口请求失败,回收结果待核对',
  312. ];
  313. }
  314. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  315. $data = $body['data'] ?? null;
  316. if (!is_array($data)
  317. || !array_key_exists('balanceAll', $data)
  318. || !is_numeric($data['balanceAll'])
  319. || (float) $data['balanceAll'] < 0) {
  320. return [
  321. 'ok' => false,
  322. 'uncertain' => true,
  323. 'msg' => '三方游戏回收成功响应缺少有效 balanceAll,回收结果待核对',
  324. ];
  325. }
  326. $gameBalance = $this->decimalAmount($data['balanceAll']);
  327. if ($gameBalance === null) {
  328. return [
  329. 'ok' => false,
  330. 'uncertain' => true,
  331. 'msg' => '三方游戏回收金额格式异常,回收结果待核对',
  332. ];
  333. }
  334. $this->clearCache($memberId);
  335. return [
  336. 'ok' => true,
  337. 'game_balance' => $gameBalance,
  338. 'wallet_balance' => $this->toWalletBalance($gameBalance),
  339. ];
  340. }
  341. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  342. $this->clearCache($memberId);
  343. return ['ok' => true, 'game_balance' => '0.0000000000', 'wallet_balance' => '0.0000000000'];
  344. }
  345. return [
  346. 'ok' => false,
  347. 'uncertain' => false,
  348. 'msg' => $this->responseMessage($response),
  349. ];
  350. }
  351. public function toWalletBalance($gameBalance): string
  352. {
  353. $balance = $this->decimalAmount($gameBalance);
  354. if ($balance === null) {
  355. throw new \InvalidArgumentException('三方游戏余额格式异常');
  356. }
  357. return bcdiv($balance, $this->recycleRate(), 10);
  358. }
  359. private function recycleRate(): string
  360. {
  361. $rate = trim((string) config('third_game.recycle_rate', '1'));
  362. if (!preg_match('/^\d+(?:\.\d+)?$/D', $rate) || bccomp($rate, '0', 10) <= 0) {
  363. throw new \RuntimeException('GAME_RECYCLE_RATE 必须是大于 0 的数字');
  364. }
  365. return $rate;
  366. }
  367. private function balancesFromResponse($response): ?array
  368. {
  369. if (!$response instanceof Response) {
  370. return null;
  371. }
  372. $body = $response->json();
  373. if (!is_array($body)) {
  374. return null;
  375. }
  376. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  377. return is_array($body['data'] ?? null) ? $body['data'] : [];
  378. }
  379. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  380. return [];
  381. }
  382. Log::warning('third_game_balance_query_failed', [
  383. 'code' => $body['code'] ?? null,
  384. 'msg' => $body['msg'] ?? null,
  385. ]);
  386. return null;
  387. }
  388. private function detailResult(string $memberId, array $balances): array
  389. {
  390. $gameBalance = $this->sumBalances($balances);
  391. $walletBalances = [];
  392. $gameBalances = [];
  393. foreach ($balances as $platform => $balance) {
  394. if (is_numeric($balance)) {
  395. $walletBalances[] = [
  396. 'platform' => (string) $platform,
  397. 'balance' => (float) $balance,
  398. ];
  399. $gameBalances[] = [
  400. 'platform' => (string) $platform,
  401. 'balance' => (float) $balance,
  402. ];
  403. }
  404. }
  405. return [
  406. 'ok' => true,
  407. 'member_id' => $memberId,
  408. 'player_id' => $this->playerId($memberId),
  409. 'currency' => (string) config('third_game.currency', 'CNY'),
  410. 'rate' => 1,
  411. 'list' => $walletBalances,
  412. 'game_list' => $gameBalances,
  413. 'total_game_balance' => (float) $gameBalance,
  414. 'total_balance' => $this->totalFromBalances($balances),
  415. ];
  416. }
  417. private function agentBalanceResult(int $agentId, string $playerId, array $balances): array
  418. {
  419. $normalized = [];
  420. foreach ($balances as $platform => $balance) {
  421. $amount = $this->decimalAmount($balance);
  422. if ($amount !== null) {
  423. $normalized[strtolower((string) $platform)] = $amount;
  424. }
  425. }
  426. return [
  427. 'ok' => true,
  428. 'agent_id' => $agentId,
  429. 'player_id' => $playerId,
  430. 'currency' => (string) config('third_game.currency', 'CNY'),
  431. 'balances' => $normalized,
  432. ];
  433. }
  434. private function totalFromBalances(array $balances): float
  435. {
  436. return (float) $this->sumBalances($balances);
  437. }
  438. private function sumBalances(array $balances): string
  439. {
  440. $total = '0.0000000000';
  441. foreach ($balances as $balance) {
  442. $amount = $this->decimalAmount($balance);
  443. if ($amount !== null) {
  444. $total = bcadd($total, $amount, 10);
  445. }
  446. }
  447. return $total;
  448. }
  449. private function decimalAmount($value): ?string
  450. {
  451. if (!is_int($value) && !is_float($value) && !is_string($value)) {
  452. return null;
  453. }
  454. $value = trim((string) $value);
  455. if (!preg_match('/^\d+(?:\.\d+)?$/D', $value)) {
  456. return null;
  457. }
  458. return bcadd($value, '0', 10);
  459. }
  460. private function request(string $path, array $data, bool $transfer = false)
  461. {
  462. if (!$this->configured()) {
  463. return null;
  464. }
  465. $random = $this->random();
  466. try {
  467. return Http::asJson()
  468. ->withHeaders([
  469. 'sign' => md5($random . config('third_game.sn') . config('third_game.key')),
  470. 'random' => $random,
  471. 'sn' => config('third_game.sn'),
  472. ])
  473. ->timeout(max(1, (int) config(
  474. $transfer ? 'third_game.transfer_timeout' : 'third_game.timeout',
  475. $transfer ? 65 : 10
  476. )))
  477. ->connectTimeout(5)
  478. ->withOptions($this->httpOptions())
  479. ->post(config('third_game.api_url') . $path, $data);
  480. } catch (\Throwable $e) {
  481. Log::warning('third_game_request_failed', [
  482. 'path' => $path,
  483. 'message' => $e->getMessage(),
  484. ]);
  485. return null;
  486. }
  487. }
  488. private function responseMessage($response): string
  489. {
  490. if (!$response instanceof Response) {
  491. return $this->configured() ? '三方游戏接口请求失败' : '三方游戏配置缺失';
  492. }
  493. return (string) ($response->json('msg') ?: '三方游戏接口异常');
  494. }
  495. private function formatOrder(array $row): array
  496. {
  497. $gameType = (int) ($row['gameType'] ?? 0);
  498. $status = (int) ($row['status'] ?? -1);
  499. return [
  500. 'player_id' => (string) ($row['playerId'] ?? ''),
  501. 'platform' => (string) ($row['platType'] ?? ''),
  502. 'currency' => (string) ($row['currency'] ?? ''),
  503. 'game_type' => $gameType,
  504. 'game_type_text' => self::GAME_TYPE_NAMES[$gameType] ?? '未知',
  505. 'game_name' => (string) ($row['gameName'] ?? ''),
  506. 'round' => (string) ($row['round'] ?? ''),
  507. 'table' => (string) ($row['table'] ?? ''),
  508. 'seat' => (string) ($row['seat'] ?? ''),
  509. 'bet_amount' => $this->numericValue($row['betAmount'] ?? null),
  510. 'valid_amount' => $this->numericValue($row['validAmount'] ?? null),
  511. 'settled_amount' => $this->numericValue($row['settledAmount'] ?? null),
  512. 'bet_content' => $row['betContent'] ?? '',
  513. 'status' => $status,
  514. 'status_text' => self::ORDER_STATUS_NAMES[$status] ?? '未知',
  515. 'game_order_id' => (string) ($row['gameOrderId'] ?? ''),
  516. 'bet_time' => (string) ($row['betTime'] ?? ''),
  517. 'last_update_time' => (string) ($row['lastUpdateTime'] ?? ''),
  518. ];
  519. }
  520. private function numericValue($value)
  521. {
  522. return is_numeric($value) ? $value + 0 : null;
  523. }
  524. private function historyRangeError(string $startTime, string $endTime): ?string
  525. {
  526. $timezone = config('app.timezone', 'Asia/Shanghai');
  527. $start = Carbon::createFromFormat('Y-m-d H:i:s', $startTime, $timezone);
  528. $end = Carbon::createFromFormat('Y-m-d H:i:s', $endTime, $timezone);
  529. if ($start->gt($end)) {
  530. return '开始时间不能大于结束时间';
  531. }
  532. if ($start->diffInSeconds($end) > 6 * 60 * 60) {
  533. return '查询时间范围不能超过6小时';
  534. }
  535. if ($start->lt(Carbon::now($timezone)->subDays(15))) {
  536. return '只能查询最近15天内的订单';
  537. }
  538. return null;
  539. }
  540. private function acquireHistoryQuota(
  541. string $startTime,
  542. string $endTime,
  543. int $page,
  544. int $limit
  545. ): ?string
  546. {
  547. $prefix = $this->historyRatePrefix();
  548. $sessionKey = $this->historySessionKey($startTime, $endTime, $limit);
  549. $lock = Cache::lock($prefix . ':lock', 5);
  550. if (!$lock->get()) {
  551. return '订单查询正在处理中,请稍后重试';
  552. }
  553. try {
  554. $now = time();
  555. $lastRequestAt = (int) Cache::get($prefix . ':last_request', 0);
  556. if ($lastRequestAt > 0 && $now - $lastRequestAt < self::HISTORY_PAGE_INTERVAL_SECONDS) {
  557. $retryAfter = self::HISTORY_PAGE_INTERVAL_SECONDS - ($now - $lastRequestAt);
  558. return "订单请求至少间隔10秒,请在{$retryAfter}秒后重试";
  559. }
  560. $isPagination = $page > 1 && Cache::has($sessionKey);
  561. if (!$isPagination) {
  562. $lastQueryAt = (int) Cache::get($prefix . ':last_query', 0);
  563. if ($lastQueryAt > 0 && $now - $lastQueryAt < self::HISTORY_QUERY_INTERVAL_SECONDS) {
  564. $retryAfter = self::HISTORY_QUERY_INTERVAL_SECONDS - ($now - $lastQueryAt);
  565. return "订单查询至少间隔1分钟,请在{$retryAfter}秒后重试";
  566. }
  567. $hourlyKey = $prefix . ':hourly';
  568. if (RateLimiter::tooManyAttempts($hourlyKey, self::HISTORY_HOURLY_LIMIT)) {
  569. $retryAfter = max(1, RateLimiter::availableIn($hourlyKey));
  570. return "订单查询每小时最多5次,请在{$retryAfter}秒后重试";
  571. }
  572. RateLimiter::hit($hourlyKey, 3600);
  573. Cache::put($prefix . ':last_query', $now, self::HISTORY_QUERY_INTERVAL_SECONDS);
  574. }
  575. Cache::put($prefix . ':last_request', $now, self::HISTORY_PAGE_INTERVAL_SECONDS);
  576. return null;
  577. } finally {
  578. $lock->release();
  579. }
  580. }
  581. private function acquireRealtimeQuota(int $page, int $limit): ?string
  582. {
  583. $sessionKey = $this->realtimeSessionKey($limit);
  584. if ($page > 1 && Cache::has($sessionKey)) {
  585. return null;
  586. }
  587. $prefix = $this->realtimeRatePrefix();
  588. $lock = Cache::lock($prefix . ':lock', 5);
  589. if (!$lock->get()) {
  590. return '实时订单同步正在处理中,请稍后重试';
  591. }
  592. try {
  593. if ($page > 1 && Cache::has($sessionKey)) {
  594. return null;
  595. }
  596. $now = time();
  597. $lastQueryAt = (int) Cache::get($prefix . ':last_query', 0);
  598. if ($lastQueryAt > 0 && $now - $lastQueryAt < self::REALTIME_QUERY_INTERVAL_SECONDS) {
  599. $retryAfter = self::REALTIME_QUERY_INTERVAL_SECONDS - ($now - $lastQueryAt);
  600. return "实时订单同步每分钟最多请求1次,请在{$retryAfter}秒后重试";
  601. }
  602. Cache::put($prefix . ':last_query', $now, self::REALTIME_QUERY_INTERVAL_SECONDS);
  603. return null;
  604. } finally {
  605. $lock->release();
  606. }
  607. }
  608. private function configured(): bool
  609. {
  610. return config('third_game.api_url') !== ''
  611. && config('third_game.sn') !== ''
  612. && config('third_game.key') !== '';
  613. }
  614. private function isPlayerNotFound(string $message): bool
  615. {
  616. $message = strtolower($message);
  617. return str_contains($message, 'playerid')
  618. && (str_contains($message, '不存在')
  619. || str_contains($message, 'not exist')
  620. || str_contains($message, 'not found'));
  621. }
  622. private function httpOptions(): array
  623. {
  624. $options = [];
  625. $proxy = (string) config('third_game.proxy', '');
  626. if ($proxy !== '') {
  627. $options['proxy'] = $proxy;
  628. }
  629. $caBundle = (string) config('third_game.ca_bundle', '');
  630. if ($caBundle !== '') {
  631. $options['verify'] = $caBundle;
  632. }
  633. return $options;
  634. }
  635. private function cacheKey(string $memberId): string
  636. {
  637. return 'third_game_total_balance:' . $memberId;
  638. }
  639. private function detailCacheKey(string $memberId): string
  640. {
  641. return 'third_game_balance_detail:' . $memberId;
  642. }
  643. private function historyRatePrefix(): string
  644. {
  645. return 'third_game_order_history:' . md5((string) config('third_game.sn'));
  646. }
  647. private function realtimeRatePrefix(): string
  648. {
  649. return 'third_game_order_realtime:' . md5((string) config('third_game.sn'));
  650. }
  651. private function historySessionKey(string $startTime, string $endTime, int $limit): string
  652. {
  653. return $this->historyRatePrefix() . ':session:' . md5($startTime . '|' . $endTime . '|' . $limit);
  654. }
  655. private function rememberHistorySession(string $startTime, string $endTime, int $limit): void
  656. {
  657. Cache::put($this->historySessionKey($startTime, $endTime, $limit), true, 3600);
  658. }
  659. private function realtimeSessionKey(int $limit): string
  660. {
  661. return $this->realtimeRatePrefix() . ':session:' . $limit;
  662. }
  663. private function rememberRealtimeSession(int $limit): void
  664. {
  665. Cache::put($this->realtimeSessionKey($limit), true, 600);
  666. }
  667. private function clearCache(string $memberId): void
  668. {
  669. Cache::forget($this->cacheKey($memberId));
  670. Cache::forget($this->detailCacheKey($memberId));
  671. }
  672. private function random(): string
  673. {
  674. $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
  675. $value = '';
  676. for ($i = 0; $i < 32; $i++) {
  677. $value .= $characters[random_int(0, strlen($characters) - 1)];
  678. }
  679. return $value;
  680. }
  681. }