ThirdGameBalanceService.php 32 KB

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