ThirdGameBalanceService.php 27 KB

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