ThirdGameBalanceService.php 29 KB

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