ThirdGameBalanceService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. <?php
  2. namespace App\Services;
  3. use Carbon\Carbon;
  4. use Illuminate\Http\Client\Pool;
  5. use Illuminate\Http\Client\Response;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Http;
  8. use Illuminate\Support\Facades\Log;
  9. use Illuminate\Support\Facades\RateLimiter;
  10. class ThirdGameBalanceService
  11. {
  12. private const CODE_SUCCESS = 10000;
  13. private const HISTORY_QUERY_INTERVAL_SECONDS = 60;
  14. private const HISTORY_PAGE_INTERVAL_SECONDS = 10;
  15. private const HISTORY_HOURLY_LIMIT = 5;
  16. private const GAME_TYPE_NAMES = [
  17. 1 => '视讯',
  18. 2 => '老虎机',
  19. 3 => '彩票',
  20. 4 => '体育',
  21. 5 => '电竞',
  22. 6 => '捕猎',
  23. 7 => '棋牌',
  24. ];
  25. private const ORDER_STATUS_NAMES = [
  26. 0 => '未完成',
  27. 1 => '已完成',
  28. 2 => '已取消',
  29. 3 => '已撤单',
  30. ];
  31. /**
  32. * 批量查询用户的三方游戏总余额,三方与主钱包金额按 1:1 处理。
  33. *
  34. * @param array<int, string|int> $memberIds
  35. * @return array<string, float|null>
  36. */
  37. public function totals(array $memberIds): array
  38. {
  39. $memberIds = array_values(array_unique(array_map('strval', $memberIds)));
  40. $totals = [];
  41. $pending = [];
  42. foreach ($memberIds as $memberId) {
  43. $cached = Cache::get($this->cacheKey($memberId));
  44. if ($cached !== null) {
  45. $totals[$memberId] = (float) $cached;
  46. } else {
  47. $pending[] = $memberId;
  48. }
  49. }
  50. if ($pending === []) {
  51. return $totals;
  52. }
  53. if (!$this->configured()) {
  54. Log::warning('third_game_balance_config_missing');
  55. foreach ($pending as $memberId) {
  56. $totals[$memberId] = null;
  57. }
  58. return $totals;
  59. }
  60. try {
  61. $responses = Http::pool(function (Pool $pool) use ($pending) {
  62. $requests = [];
  63. foreach ($pending as $memberId) {
  64. $random = $this->random();
  65. $requests[] = $pool->as($memberId)
  66. ->asJson()
  67. ->withHeaders([
  68. 'sign' => md5($random . config('third_game.sn') . config('third_game.key')),
  69. 'random' => $random,
  70. 'sn' => config('third_game.sn'),
  71. ])
  72. ->timeout(max(1, (int) config('third_game.timeout', 10)))
  73. ->connectTimeout(5)
  74. ->withOptions($this->httpOptions())
  75. ->post(config('third_game.api_url') . '/api/server/balanceAll', [
  76. 'playerId' => $this->playerId($memberId),
  77. 'currency' => config('third_game.currency', 'CNY'),
  78. ]);
  79. }
  80. return $requests;
  81. });
  82. } catch (\Throwable $e) {
  83. Log::warning('third_game_balance_pool_failed', ['message' => $e->getMessage()]);
  84. foreach ($pending as $memberId) {
  85. $totals[$memberId] = null;
  86. }
  87. return $totals;
  88. }
  89. foreach ($pending as $memberId) {
  90. $response = $responses[$memberId] ?? null;
  91. $balances = $this->balancesFromResponse($response);
  92. $total = $balances === null ? null : $this->totalFromBalances($balances);
  93. $totals[$memberId] = $total;
  94. if ($total !== null) {
  95. Cache::put(
  96. $this->cacheKey($memberId),
  97. $total,
  98. max(1, (int) config('third_game.cache_seconds', 30))
  99. );
  100. Cache::put(
  101. $this->detailCacheKey($memberId),
  102. $balances,
  103. max(1, (int) config('third_game.cache_seconds', 30))
  104. );
  105. }
  106. }
  107. return $totals;
  108. }
  109. public function playerId(string $memberId): string
  110. {
  111. return 'p' . substr(md5(config('third_game.sn') . '_' . $memberId), 0, 10);
  112. }
  113. /**
  114. * 查询单个用户在 ag、pg 等各游戏平台的余额。
  115. */
  116. public function detail(string $memberId, bool $forceRefresh = false): array
  117. {
  118. if (!$forceRefresh) {
  119. $cached = Cache::get($this->detailCacheKey($memberId));
  120. if (is_array($cached)) {
  121. return $this->detailResult($memberId, $cached);
  122. }
  123. }
  124. $response = $this->request('/api/server/balanceAll', [
  125. 'playerId' => $this->playerId($memberId),
  126. 'currency' => config('third_game.currency', 'CNY'),
  127. ]);
  128. $balances = $this->balancesFromResponse($response);
  129. if ($balances === null) {
  130. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  131. }
  132. $ttl = max(1, (int) config('third_game.cache_seconds', 30));
  133. Cache::put($this->detailCacheKey($memberId), $balances, $ttl);
  134. Cache::put($this->cacheKey($memberId), $this->totalFromBalances($balances), $ttl);
  135. return $this->detailResult($memberId, $balances);
  136. }
  137. /**
  138. * 查询三方游戏历史订单,按订单更新时间正序返回。
  139. */
  140. public function historyOrders(
  141. string $startTime,
  142. string $endTime,
  143. int $page = 1,
  144. int $limit = 200
  145. ): array
  146. {
  147. if (!$this->configured()) {
  148. return ['ok' => false, 'msg' => '三方游戏配置缺失'];
  149. }
  150. $rangeError = $this->historyRangeError($startTime, $endTime);
  151. if ($rangeError !== null) {
  152. return ['ok' => false, 'msg' => $rangeError];
  153. }
  154. $rateError = $this->acquireHistoryQuota($startTime, $endTime, $page, $limit);
  155. if ($rateError !== null) {
  156. return ['ok' => false, 'msg' => $rateError];
  157. }
  158. $response = $this->request('/api/server/recordHistory', [
  159. 'currency' => (string) config('third_game.currency', 'CNY'),
  160. 'startTime' => $startTime,
  161. 'endTime' => $endTime,
  162. 'pageNo' => (string) $page,
  163. 'pageSize' => (string) $limit,
  164. ]);
  165. if (!$response instanceof Response) {
  166. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  167. }
  168. $body = $response->json();
  169. if (!is_array($body) || (int) ($body['code'] ?? 0) !== self::CODE_SUCCESS) {
  170. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  171. }
  172. $providerData = is_array($body['data'] ?? null) ? $body['data'] : [];
  173. $providerList = is_array($providerData['list'] ?? null) ? $providerData['list'] : [];
  174. $list = [];
  175. foreach ($providerList as $row) {
  176. if (is_array($row)) {
  177. $list[] = $this->formatOrder($row);
  178. }
  179. }
  180. $result = [
  181. 'ok' => true,
  182. 'currency' => (string) config('third_game.currency', 'CNY'),
  183. 'start_time' => $startTime,
  184. 'end_time' => $endTime,
  185. 'total' => (int) ($providerData['total'] ?? count($list)),
  186. 'page_no' => (int) ($providerData['pageNo'] ?? $page),
  187. 'page_size' => (int) ($providerData['pageSize'] ?? $limit),
  188. 'list' => $list,
  189. ];
  190. return $result;
  191. }
  192. /**
  193. * 一键把用户在所有三方游戏平台的余额转出。
  194. */
  195. public function recycle(string $memberId): array
  196. {
  197. // 必须在调用 transferAll 前校验,避免三方已转出后才因本地配置错误中断。
  198. $this->recycleRate();
  199. $response = $this->request('/api/server/transferAll', [
  200. 'playerId' => $this->playerId($memberId),
  201. 'currency' => config('third_game.currency', 'CNY'),
  202. ], true);
  203. $body = $response instanceof Response ? $response->json() : null;
  204. if (!is_array($body)) {
  205. return [
  206. 'ok' => false,
  207. 'uncertain' => true,
  208. 'msg' => $response instanceof Response
  209. ? '三方游戏接口返回异常,回收结果待核对'
  210. : '三方游戏接口请求失败,回收结果待核对',
  211. ];
  212. }
  213. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  214. $data = $body['data'] ?? null;
  215. if (!is_array($data)
  216. || !array_key_exists('balanceAll', $data)
  217. || !is_numeric($data['balanceAll'])
  218. || (float) $data['balanceAll'] < 0) {
  219. return [
  220. 'ok' => false,
  221. 'uncertain' => true,
  222. 'msg' => '三方游戏回收成功响应缺少有效 balanceAll,回收结果待核对',
  223. ];
  224. }
  225. $gameBalance = $this->decimalAmount($data['balanceAll']);
  226. if ($gameBalance === null) {
  227. return [
  228. 'ok' => false,
  229. 'uncertain' => true,
  230. 'msg' => '三方游戏回收金额格式异常,回收结果待核对',
  231. ];
  232. }
  233. $this->clearCache($memberId);
  234. return [
  235. 'ok' => true,
  236. 'game_balance' => $gameBalance,
  237. 'wallet_balance' => $this->toWalletBalance($gameBalance),
  238. ];
  239. }
  240. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  241. $this->clearCache($memberId);
  242. return ['ok' => true, 'game_balance' => '0.0000000000', 'wallet_balance' => '0.0000000000'];
  243. }
  244. return [
  245. 'ok' => false,
  246. 'uncertain' => false,
  247. 'msg' => $this->responseMessage($response),
  248. ];
  249. }
  250. public function toWalletBalance($gameBalance): string
  251. {
  252. $balance = $this->decimalAmount($gameBalance);
  253. if ($balance === null) {
  254. throw new \InvalidArgumentException('三方游戏余额格式异常');
  255. }
  256. return bcdiv($balance, $this->recycleRate(), 10);
  257. }
  258. private function recycleRate(): string
  259. {
  260. $rate = trim((string) config('third_game.recycle_rate', '1'));
  261. if (!preg_match('/^\d+(?:\.\d+)?$/D', $rate) || bccomp($rate, '0', 10) <= 0) {
  262. throw new \RuntimeException('GAME_RECYCLE_RATE 必须是大于 0 的数字');
  263. }
  264. return $rate;
  265. }
  266. private function balancesFromResponse($response): ?array
  267. {
  268. if (!$response instanceof Response) {
  269. return null;
  270. }
  271. $body = $response->json();
  272. if (!is_array($body)) {
  273. return null;
  274. }
  275. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  276. return is_array($body['data'] ?? null) ? $body['data'] : [];
  277. }
  278. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  279. return [];
  280. }
  281. Log::warning('third_game_balance_query_failed', [
  282. 'code' => $body['code'] ?? null,
  283. 'msg' => $body['msg'] ?? null,
  284. ]);
  285. return null;
  286. }
  287. private function detailResult(string $memberId, array $balances): array
  288. {
  289. $gameBalance = $this->sumBalances($balances);
  290. $walletBalances = [];
  291. $gameBalances = [];
  292. foreach ($balances as $platform => $balance) {
  293. if (is_numeric($balance)) {
  294. $walletBalances[] = [
  295. 'platform' => (string) $platform,
  296. 'balance' => (float) $balance,
  297. ];
  298. $gameBalances[] = [
  299. 'platform' => (string) $platform,
  300. 'balance' => (float) $balance,
  301. ];
  302. }
  303. }
  304. return [
  305. 'ok' => true,
  306. 'member_id' => $memberId,
  307. 'player_id' => $this->playerId($memberId),
  308. 'currency' => (string) config('third_game.currency', 'CNY'),
  309. 'rate' => 1,
  310. 'list' => $walletBalances,
  311. 'game_list' => $gameBalances,
  312. 'total_game_balance' => (float) $gameBalance,
  313. 'total_balance' => $this->totalFromBalances($balances),
  314. ];
  315. }
  316. private function totalFromBalances(array $balances): float
  317. {
  318. return (float) $this->sumBalances($balances);
  319. }
  320. private function sumBalances(array $balances): string
  321. {
  322. $total = '0.0000000000';
  323. foreach ($balances as $balance) {
  324. $amount = $this->decimalAmount($balance);
  325. if ($amount !== null) {
  326. $total = bcadd($total, $amount, 10);
  327. }
  328. }
  329. return $total;
  330. }
  331. private function decimalAmount($value): ?string
  332. {
  333. if (!is_int($value) && !is_float($value) && !is_string($value)) {
  334. return null;
  335. }
  336. $value = trim((string) $value);
  337. if (!preg_match('/^\d+(?:\.\d+)?$/D', $value)) {
  338. return null;
  339. }
  340. return bcadd($value, '0', 10);
  341. }
  342. private function request(string $path, array $data, bool $transfer = false)
  343. {
  344. if (!$this->configured()) {
  345. return null;
  346. }
  347. $random = $this->random();
  348. try {
  349. return Http::asJson()
  350. ->withHeaders([
  351. 'sign' => md5($random . config('third_game.sn') . config('third_game.key')),
  352. 'random' => $random,
  353. 'sn' => config('third_game.sn'),
  354. ])
  355. ->timeout(max(1, (int) config(
  356. $transfer ? 'third_game.transfer_timeout' : 'third_game.timeout',
  357. $transfer ? 65 : 10
  358. )))
  359. ->connectTimeout(5)
  360. ->withOptions($this->httpOptions())
  361. ->post(config('third_game.api_url') . $path, $data);
  362. } catch (\Throwable $e) {
  363. Log::warning('third_game_request_failed', [
  364. 'path' => $path,
  365. 'message' => $e->getMessage(),
  366. ]);
  367. return null;
  368. }
  369. }
  370. private function responseMessage($response): string
  371. {
  372. if (!$response instanceof Response) {
  373. return $this->configured() ? '三方游戏接口请求失败' : '三方游戏配置缺失';
  374. }
  375. return (string) ($response->json('msg') ?: '三方游戏接口异常');
  376. }
  377. private function formatOrder(array $row): array
  378. {
  379. $gameType = (int) ($row['gameType'] ?? 0);
  380. $status = (int) ($row['status'] ?? -1);
  381. return [
  382. 'player_id' => (string) ($row['playerId'] ?? ''),
  383. 'platform' => (string) ($row['platType'] ?? ''),
  384. 'currency' => (string) ($row['currency'] ?? ''),
  385. 'game_type' => $gameType,
  386. 'game_type_text' => self::GAME_TYPE_NAMES[$gameType] ?? '未知',
  387. 'game_name' => (string) ($row['gameName'] ?? ''),
  388. 'round' => (string) ($row['round'] ?? ''),
  389. 'table' => (string) ($row['table'] ?? ''),
  390. 'seat' => (string) ($row['seat'] ?? ''),
  391. 'bet_amount' => $this->numericValue($row['betAmount'] ?? null),
  392. 'valid_amount' => $this->numericValue($row['validAmount'] ?? null),
  393. 'settled_amount' => $this->numericValue($row['settledAmount'] ?? null),
  394. 'bet_content' => $row['betContent'] ?? '',
  395. 'status' => $status,
  396. 'status_text' => self::ORDER_STATUS_NAMES[$status] ?? '未知',
  397. 'game_order_id' => (string) ($row['gameOrderId'] ?? ''),
  398. 'bet_time' => (string) ($row['betTime'] ?? ''),
  399. 'last_update_time' => (string) ($row['lastUpdateTime'] ?? ''),
  400. ];
  401. }
  402. private function numericValue($value)
  403. {
  404. return is_numeric($value) ? $value + 0 : null;
  405. }
  406. private function historyRangeError(string $startTime, string $endTime): ?string
  407. {
  408. $timezone = config('app.timezone', 'Asia/Shanghai');
  409. $start = Carbon::createFromFormat('Y-m-d H:i:s', $startTime, $timezone);
  410. $end = Carbon::createFromFormat('Y-m-d H:i:s', $endTime, $timezone);
  411. if ($start->gt($end)) {
  412. return '开始时间不能大于结束时间';
  413. }
  414. if ($start->diffInSeconds($end) > 6 * 60 * 60) {
  415. return '查询时间范围不能超过6小时';
  416. }
  417. if ($start->lt(Carbon::now($timezone)->subDays(15))) {
  418. return '只能查询最近15天内的订单';
  419. }
  420. return null;
  421. }
  422. private function acquireHistoryQuota(
  423. string $startTime,
  424. string $endTime,
  425. int $page,
  426. int $limit
  427. ): ?string
  428. {
  429. $prefix = $this->historyRatePrefix();
  430. $sessionKey = $this->historySessionKey($startTime, $endTime, $limit);
  431. $lock = Cache::lock($prefix . ':lock', 5);
  432. if (!$lock->get()) {
  433. return '订单查询正在处理中,请稍后重试';
  434. }
  435. try {
  436. $now = time();
  437. $lastRequestAt = (int) Cache::get($prefix . ':last_request', 0);
  438. if ($lastRequestAt > 0 && $now - $lastRequestAt < self::HISTORY_PAGE_INTERVAL_SECONDS) {
  439. $retryAfter = self::HISTORY_PAGE_INTERVAL_SECONDS - ($now - $lastRequestAt);
  440. return "订单请求至少间隔10秒,请在{$retryAfter}秒后重试";
  441. }
  442. $isPagination = $page > 1 && Cache::has($sessionKey);
  443. if (!$isPagination) {
  444. $lastQueryAt = (int) Cache::get($prefix . ':last_query', 0);
  445. if ($lastQueryAt > 0 && $now - $lastQueryAt < self::HISTORY_QUERY_INTERVAL_SECONDS) {
  446. $retryAfter = self::HISTORY_QUERY_INTERVAL_SECONDS - ($now - $lastQueryAt);
  447. return "订单查询至少间隔1分钟,请在{$retryAfter}秒后重试";
  448. }
  449. $hourlyKey = $prefix . ':hourly';
  450. if (RateLimiter::tooManyAttempts($hourlyKey, self::HISTORY_HOURLY_LIMIT)) {
  451. $retryAfter = max(1, RateLimiter::availableIn($hourlyKey));
  452. return "订单查询每小时最多5次,请在{$retryAfter}秒后重试";
  453. }
  454. RateLimiter::hit($hourlyKey, 3600);
  455. Cache::put($prefix . ':last_query', $now, self::HISTORY_QUERY_INTERVAL_SECONDS);
  456. Cache::put($sessionKey, true, 3600);
  457. }
  458. Cache::put($prefix . ':last_request', $now, self::HISTORY_PAGE_INTERVAL_SECONDS);
  459. return null;
  460. } finally {
  461. $lock->release();
  462. }
  463. }
  464. private function configured(): bool
  465. {
  466. return config('third_game.api_url') !== ''
  467. && config('third_game.sn') !== ''
  468. && config('third_game.key') !== '';
  469. }
  470. private function isPlayerNotFound(string $message): bool
  471. {
  472. $message = strtolower($message);
  473. return str_contains($message, 'playerid')
  474. && (str_contains($message, '不存在')
  475. || str_contains($message, 'not exist')
  476. || str_contains($message, 'not found'));
  477. }
  478. private function httpOptions(): array
  479. {
  480. $options = [];
  481. $proxy = (string) config('third_game.proxy', '');
  482. if ($proxy !== '') {
  483. $options['proxy'] = $proxy;
  484. }
  485. $caBundle = (string) config('third_game.ca_bundle', '');
  486. if ($caBundle !== '') {
  487. $options['verify'] = $caBundle;
  488. }
  489. return $options;
  490. }
  491. private function cacheKey(string $memberId): string
  492. {
  493. return 'third_game_total_balance:' . $memberId;
  494. }
  495. private function detailCacheKey(string $memberId): string
  496. {
  497. return 'third_game_balance_detail:' . $memberId;
  498. }
  499. private function historyRatePrefix(): string
  500. {
  501. return 'third_game_order_history:' . md5((string) config('third_game.sn'));
  502. }
  503. private function historySessionKey(string $startTime, string $endTime, int $limit): string
  504. {
  505. return $this->historyRatePrefix() . ':session:' . md5($startTime . '|' . $endTime . '|' . $limit);
  506. }
  507. private function clearCache(string $memberId): void
  508. {
  509. Cache::forget($this->cacheKey($memberId));
  510. Cache::forget($this->detailCacheKey($memberId));
  511. }
  512. private function random(): string
  513. {
  514. $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
  515. $value = '';
  516. for ($i = 0; $i < 32; $i++) {
  517. $value .= $characters[random_int(0, strlen($characters) - 1)];
  518. }
  519. return $value;
  520. }
  521. }