ThirdGameBalanceService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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. $this->rememberHistorySession($startTime, $endTime, $limit);
  173. $providerData = is_array($body['data'] ?? null) ? $body['data'] : [];
  174. $providerList = is_array($providerData['list'] ?? null) ? $providerData['list'] : [];
  175. $list = [];
  176. foreach ($providerList as $row) {
  177. if (is_array($row)) {
  178. $list[] = $this->formatOrder($row);
  179. }
  180. }
  181. $result = [
  182. 'ok' => true,
  183. 'currency' => (string) config('third_game.currency', 'CNY'),
  184. 'start_time' => $startTime,
  185. 'end_time' => $endTime,
  186. 'total' => (int) ($providerData['total'] ?? count($list)),
  187. 'page_no' => (int) ($providerData['pageNo'] ?? $page),
  188. 'page_size' => (int) ($providerData['pageSize'] ?? $limit),
  189. 'list' => $list,
  190. ];
  191. return $result;
  192. }
  193. /**
  194. * 一键把用户在所有三方游戏平台的余额转出。
  195. */
  196. public function recycle(string $memberId): array
  197. {
  198. // 必须在调用 transferAll 前校验,避免三方已转出后才因本地配置错误中断。
  199. $this->recycleRate();
  200. $response = $this->request('/api/server/transferAll', [
  201. 'playerId' => $this->playerId($memberId),
  202. 'currency' => config('third_game.currency', 'CNY'),
  203. ], true);
  204. $body = $response instanceof Response ? $response->json() : null;
  205. if (!is_array($body)) {
  206. return [
  207. 'ok' => false,
  208. 'uncertain' => true,
  209. 'msg' => $response instanceof Response
  210. ? '三方游戏接口返回异常,回收结果待核对'
  211. : '三方游戏接口请求失败,回收结果待核对',
  212. ];
  213. }
  214. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  215. $data = $body['data'] ?? null;
  216. if (!is_array($data)
  217. || !array_key_exists('balanceAll', $data)
  218. || !is_numeric($data['balanceAll'])
  219. || (float) $data['balanceAll'] < 0) {
  220. return [
  221. 'ok' => false,
  222. 'uncertain' => true,
  223. 'msg' => '三方游戏回收成功响应缺少有效 balanceAll,回收结果待核对',
  224. ];
  225. }
  226. $gameBalance = $this->decimalAmount($data['balanceAll']);
  227. if ($gameBalance === null) {
  228. return [
  229. 'ok' => false,
  230. 'uncertain' => true,
  231. 'msg' => '三方游戏回收金额格式异常,回收结果待核对',
  232. ];
  233. }
  234. $this->clearCache($memberId);
  235. return [
  236. 'ok' => true,
  237. 'game_balance' => $gameBalance,
  238. 'wallet_balance' => $this->toWalletBalance($gameBalance),
  239. ];
  240. }
  241. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  242. $this->clearCache($memberId);
  243. return ['ok' => true, 'game_balance' => '0.0000000000', 'wallet_balance' => '0.0000000000'];
  244. }
  245. return [
  246. 'ok' => false,
  247. 'uncertain' => false,
  248. 'msg' => $this->responseMessage($response),
  249. ];
  250. }
  251. public function toWalletBalance($gameBalance): string
  252. {
  253. $balance = $this->decimalAmount($gameBalance);
  254. if ($balance === null) {
  255. throw new \InvalidArgumentException('三方游戏余额格式异常');
  256. }
  257. return bcdiv($balance, $this->recycleRate(), 10);
  258. }
  259. private function recycleRate(): string
  260. {
  261. $rate = trim((string) config('third_game.recycle_rate', '1'));
  262. if (!preg_match('/^\d+(?:\.\d+)?$/D', $rate) || bccomp($rate, '0', 10) <= 0) {
  263. throw new \RuntimeException('GAME_RECYCLE_RATE 必须是大于 0 的数字');
  264. }
  265. return $rate;
  266. }
  267. private function balancesFromResponse($response): ?array
  268. {
  269. if (!$response instanceof Response) {
  270. return null;
  271. }
  272. $body = $response->json();
  273. if (!is_array($body)) {
  274. return null;
  275. }
  276. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  277. return is_array($body['data'] ?? null) ? $body['data'] : [];
  278. }
  279. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  280. return [];
  281. }
  282. Log::warning('third_game_balance_query_failed', [
  283. 'code' => $body['code'] ?? null,
  284. 'msg' => $body['msg'] ?? null,
  285. ]);
  286. return null;
  287. }
  288. private function detailResult(string $memberId, array $balances): array
  289. {
  290. $gameBalance = $this->sumBalances($balances);
  291. $walletBalances = [];
  292. $gameBalances = [];
  293. foreach ($balances as $platform => $balance) {
  294. if (is_numeric($balance)) {
  295. $walletBalances[] = [
  296. 'platform' => (string) $platform,
  297. 'balance' => (float) $balance,
  298. ];
  299. $gameBalances[] = [
  300. 'platform' => (string) $platform,
  301. 'balance' => (float) $balance,
  302. ];
  303. }
  304. }
  305. return [
  306. 'ok' => true,
  307. 'member_id' => $memberId,
  308. 'player_id' => $this->playerId($memberId),
  309. 'currency' => (string) config('third_game.currency', 'CNY'),
  310. 'rate' => 1,
  311. 'list' => $walletBalances,
  312. 'game_list' => $gameBalances,
  313. 'total_game_balance' => (float) $gameBalance,
  314. 'total_balance' => $this->totalFromBalances($balances),
  315. ];
  316. }
  317. private function totalFromBalances(array $balances): float
  318. {
  319. return (float) $this->sumBalances($balances);
  320. }
  321. private function sumBalances(array $balances): string
  322. {
  323. $total = '0.0000000000';
  324. foreach ($balances as $balance) {
  325. $amount = $this->decimalAmount($balance);
  326. if ($amount !== null) {
  327. $total = bcadd($total, $amount, 10);
  328. }
  329. }
  330. return $total;
  331. }
  332. private function decimalAmount($value): ?string
  333. {
  334. if (!is_int($value) && !is_float($value) && !is_string($value)) {
  335. return null;
  336. }
  337. $value = trim((string) $value);
  338. if (!preg_match('/^\d+(?:\.\d+)?$/D', $value)) {
  339. return null;
  340. }
  341. return bcadd($value, '0', 10);
  342. }
  343. private function request(string $path, array $data, bool $transfer = false)
  344. {
  345. if (!$this->configured()) {
  346. return null;
  347. }
  348. $random = $this->random();
  349. try {
  350. return Http::asJson()
  351. ->withHeaders([
  352. 'sign' => md5($random . config('third_game.sn') . config('third_game.key')),
  353. 'random' => $random,
  354. 'sn' => config('third_game.sn'),
  355. ])
  356. ->timeout(max(1, (int) config(
  357. $transfer ? 'third_game.transfer_timeout' : 'third_game.timeout',
  358. $transfer ? 65 : 10
  359. )))
  360. ->connectTimeout(5)
  361. ->withOptions($this->httpOptions())
  362. ->post(config('third_game.api_url') . $path, $data);
  363. } catch (\Throwable $e) {
  364. Log::warning('third_game_request_failed', [
  365. 'path' => $path,
  366. 'message' => $e->getMessage(),
  367. ]);
  368. return null;
  369. }
  370. }
  371. private function responseMessage($response): string
  372. {
  373. if (!$response instanceof Response) {
  374. return $this->configured() ? '三方游戏接口请求失败' : '三方游戏配置缺失';
  375. }
  376. return (string) ($response->json('msg') ?: '三方游戏接口异常');
  377. }
  378. private function formatOrder(array $row): array
  379. {
  380. $gameType = (int) ($row['gameType'] ?? 0);
  381. $status = (int) ($row['status'] ?? -1);
  382. return [
  383. 'player_id' => (string) ($row['playerId'] ?? ''),
  384. 'platform' => (string) ($row['platType'] ?? ''),
  385. 'currency' => (string) ($row['currency'] ?? ''),
  386. 'game_type' => $gameType,
  387. 'game_type_text' => self::GAME_TYPE_NAMES[$gameType] ?? '未知',
  388. 'game_name' => (string) ($row['gameName'] ?? ''),
  389. 'round' => (string) ($row['round'] ?? ''),
  390. 'table' => (string) ($row['table'] ?? ''),
  391. 'seat' => (string) ($row['seat'] ?? ''),
  392. 'bet_amount' => $this->numericValue($row['betAmount'] ?? null),
  393. 'valid_amount' => $this->numericValue($row['validAmount'] ?? null),
  394. 'settled_amount' => $this->numericValue($row['settledAmount'] ?? null),
  395. 'bet_content' => $row['betContent'] ?? '',
  396. 'status' => $status,
  397. 'status_text' => self::ORDER_STATUS_NAMES[$status] ?? '未知',
  398. 'game_order_id' => (string) ($row['gameOrderId'] ?? ''),
  399. 'bet_time' => (string) ($row['betTime'] ?? ''),
  400. 'last_update_time' => (string) ($row['lastUpdateTime'] ?? ''),
  401. ];
  402. }
  403. private function numericValue($value)
  404. {
  405. return is_numeric($value) ? $value + 0 : null;
  406. }
  407. private function historyRangeError(string $startTime, string $endTime): ?string
  408. {
  409. $timezone = config('app.timezone', 'Asia/Shanghai');
  410. $start = Carbon::createFromFormat('Y-m-d H:i:s', $startTime, $timezone);
  411. $end = Carbon::createFromFormat('Y-m-d H:i:s', $endTime, $timezone);
  412. if ($start->gt($end)) {
  413. return '开始时间不能大于结束时间';
  414. }
  415. if ($start->diffInSeconds($end) > 6 * 60 * 60) {
  416. return '查询时间范围不能超过6小时';
  417. }
  418. if ($start->lt(Carbon::now($timezone)->subDays(15))) {
  419. return '只能查询最近15天内的订单';
  420. }
  421. return null;
  422. }
  423. private function acquireHistoryQuota(
  424. string $startTime,
  425. string $endTime,
  426. int $page,
  427. int $limit
  428. ): ?string
  429. {
  430. $prefix = $this->historyRatePrefix();
  431. $sessionKey = $this->historySessionKey($startTime, $endTime, $limit);
  432. $lock = Cache::lock($prefix . ':lock', 5);
  433. if (!$lock->get()) {
  434. return '订单查询正在处理中,请稍后重试';
  435. }
  436. try {
  437. $now = time();
  438. $lastRequestAt = (int) Cache::get($prefix . ':last_request', 0);
  439. if ($lastRequestAt > 0 && $now - $lastRequestAt < self::HISTORY_PAGE_INTERVAL_SECONDS) {
  440. $retryAfter = self::HISTORY_PAGE_INTERVAL_SECONDS - ($now - $lastRequestAt);
  441. return "订单请求至少间隔10秒,请在{$retryAfter}秒后重试";
  442. }
  443. $isPagination = $page > 1 && Cache::has($sessionKey);
  444. if (!$isPagination) {
  445. $lastQueryAt = (int) Cache::get($prefix . ':last_query', 0);
  446. if ($lastQueryAt > 0 && $now - $lastQueryAt < self::HISTORY_QUERY_INTERVAL_SECONDS) {
  447. $retryAfter = self::HISTORY_QUERY_INTERVAL_SECONDS - ($now - $lastQueryAt);
  448. return "订单查询至少间隔1分钟,请在{$retryAfter}秒后重试";
  449. }
  450. $hourlyKey = $prefix . ':hourly';
  451. if (RateLimiter::tooManyAttempts($hourlyKey, self::HISTORY_HOURLY_LIMIT)) {
  452. $retryAfter = max(1, RateLimiter::availableIn($hourlyKey));
  453. return "订单查询每小时最多5次,请在{$retryAfter}秒后重试";
  454. }
  455. RateLimiter::hit($hourlyKey, 3600);
  456. Cache::put($prefix . ':last_query', $now, self::HISTORY_QUERY_INTERVAL_SECONDS);
  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 rememberHistorySession(string $startTime, string $endTime, int $limit): void
  508. {
  509. Cache::put($this->historySessionKey($startTime, $endTime, $limit), true, 3600);
  510. }
  511. private function clearCache(string $memberId): void
  512. {
  513. Cache::forget($this->cacheKey($memberId));
  514. Cache::forget($this->detailCacheKey($memberId));
  515. }
  516. private function random(): string
  517. {
  518. $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
  519. $value = '';
  520. for ($i = 0; $i < 32; $i++) {
  521. $value .= $characters[random_int(0, strlen($characters) - 1)];
  522. }
  523. return $value;
  524. }
  525. }