ThirdGameBalanceService.php 29 KB

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