ThirdGameBalanceService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Http\Client\Pool;
  4. use Illuminate\Http\Client\Response;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\Http;
  7. use Illuminate\Support\Facades\Log;
  8. class ThirdGameBalanceService
  9. {
  10. private const CODE_SUCCESS = 10000;
  11. /**
  12. * 批量查询用户的三方游戏总余额,三方与主钱包金额按 1:1 处理。
  13. *
  14. * @param array<int, string|int> $memberIds
  15. * @return array<string, float|null>
  16. */
  17. public function totals(array $memberIds): array
  18. {
  19. $memberIds = array_values(array_unique(array_map('strval', $memberIds)));
  20. $totals = [];
  21. $pending = [];
  22. foreach ($memberIds as $memberId) {
  23. $cached = Cache::get($this->cacheKey($memberId));
  24. if ($cached !== null) {
  25. $totals[$memberId] = (float) $cached;
  26. } else {
  27. $pending[] = $memberId;
  28. }
  29. }
  30. if ($pending === []) {
  31. return $totals;
  32. }
  33. if (!$this->configured()) {
  34. Log::warning('third_game_balance_config_missing');
  35. foreach ($pending as $memberId) {
  36. $totals[$memberId] = null;
  37. }
  38. return $totals;
  39. }
  40. try {
  41. $responses = Http::pool(function (Pool $pool) use ($pending) {
  42. $requests = [];
  43. foreach ($pending as $memberId) {
  44. $random = $this->random();
  45. $requests[] = $pool->as($memberId)
  46. ->asJson()
  47. ->withHeaders([
  48. 'sign' => md5($random . config('third_game.sn') . config('third_game.key')),
  49. 'random' => $random,
  50. 'sn' => config('third_game.sn'),
  51. ])
  52. ->timeout(max(1, (int) config('third_game.timeout', 10)))
  53. ->connectTimeout(5)
  54. ->withOptions($this->httpOptions())
  55. ->post(config('third_game.api_url') . '/api/server/balanceAll', [
  56. 'playerId' => $this->playerId($memberId),
  57. 'currency' => config('third_game.currency', 'CNY'),
  58. ]);
  59. }
  60. return $requests;
  61. });
  62. } catch (\Throwable $e) {
  63. Log::warning('third_game_balance_pool_failed', ['message' => $e->getMessage()]);
  64. foreach ($pending as $memberId) {
  65. $totals[$memberId] = null;
  66. }
  67. return $totals;
  68. }
  69. foreach ($pending as $memberId) {
  70. $response = $responses[$memberId] ?? null;
  71. $balances = $this->balancesFromResponse($response);
  72. $total = $balances === null ? null : $this->totalFromBalances($balances);
  73. $totals[$memberId] = $total;
  74. if ($total !== null) {
  75. Cache::put(
  76. $this->cacheKey($memberId),
  77. $total,
  78. max(1, (int) config('third_game.cache_seconds', 30))
  79. );
  80. Cache::put(
  81. $this->detailCacheKey($memberId),
  82. $balances,
  83. max(1, (int) config('third_game.cache_seconds', 30))
  84. );
  85. }
  86. }
  87. return $totals;
  88. }
  89. public function playerId(string $memberId): string
  90. {
  91. return 'p' . substr(md5(config('third_game.sn') . '_' . $memberId), 0, 10);
  92. }
  93. /**
  94. * 查询单个用户在 ag、pg 等各游戏平台的余额。
  95. */
  96. public function detail(string $memberId): array
  97. {
  98. $cached = Cache::get($this->detailCacheKey($memberId));
  99. if (is_array($cached)) {
  100. return $this->detailResult($memberId, $cached);
  101. }
  102. $response = $this->request('/api/server/balanceAll', [
  103. 'playerId' => $this->playerId($memberId),
  104. 'currency' => config('third_game.currency', 'CNY'),
  105. ]);
  106. $balances = $this->balancesFromResponse($response);
  107. if ($balances === null) {
  108. return ['ok' => false, 'msg' => $this->responseMessage($response)];
  109. }
  110. $ttl = max(1, (int) config('third_game.cache_seconds', 30));
  111. Cache::put($this->detailCacheKey($memberId), $balances, $ttl);
  112. Cache::put($this->cacheKey($memberId), $this->totalFromBalances($balances), $ttl);
  113. return $this->detailResult($memberId, $balances);
  114. }
  115. /**
  116. * 一键把用户在所有三方游戏平台的余额转出。
  117. */
  118. public function recycle(string $memberId): array
  119. {
  120. // 必须在调用 transferAll 前校验,避免三方已转出后才因本地配置错误中断。
  121. $this->recycleRate();
  122. $response = $this->request('/api/server/transferAll', [
  123. 'playerId' => $this->playerId($memberId),
  124. 'currency' => config('third_game.currency', 'CNY'),
  125. ], true);
  126. $body = $response instanceof Response ? $response->json() : null;
  127. if (!is_array($body)) {
  128. return [
  129. 'ok' => false,
  130. 'uncertain' => true,
  131. 'msg' => $response instanceof Response
  132. ? '三方游戏接口返回异常,回收结果待核对'
  133. : '三方游戏接口请求失败,回收结果待核对',
  134. ];
  135. }
  136. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  137. $data = $body['data'] ?? null;
  138. if (!is_array($data)
  139. || !array_key_exists('balanceAll', $data)
  140. || !is_numeric($data['balanceAll'])
  141. || (float) $data['balanceAll'] < 0) {
  142. return [
  143. 'ok' => false,
  144. 'uncertain' => true,
  145. 'msg' => '三方游戏回收成功响应缺少有效 balanceAll,回收结果待核对',
  146. ];
  147. }
  148. $gameBalance = $this->decimalAmount($data['balanceAll']);
  149. if ($gameBalance === null) {
  150. return [
  151. 'ok' => false,
  152. 'uncertain' => true,
  153. 'msg' => '三方游戏回收金额格式异常,回收结果待核对',
  154. ];
  155. }
  156. $this->clearCache($memberId);
  157. return [
  158. 'ok' => true,
  159. 'game_balance' => $gameBalance,
  160. 'wallet_balance' => $this->toWalletBalance($gameBalance),
  161. ];
  162. }
  163. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  164. $this->clearCache($memberId);
  165. return ['ok' => true, 'game_balance' => '0.0000000000', 'wallet_balance' => '0.0000000000'];
  166. }
  167. return [
  168. 'ok' => false,
  169. 'uncertain' => false,
  170. 'msg' => $this->responseMessage($response),
  171. ];
  172. }
  173. public function toWalletBalance($gameBalance): string
  174. {
  175. $balance = $this->decimalAmount($gameBalance);
  176. if ($balance === null) {
  177. throw new \InvalidArgumentException('三方游戏余额格式异常');
  178. }
  179. return bcdiv($balance, $this->recycleRate(), 10);
  180. }
  181. private function recycleRate(): string
  182. {
  183. $rate = trim((string) config('third_game.recycle_rate', '1'));
  184. if (!preg_match('/^\d+(?:\.\d+)?$/D', $rate) || bccomp($rate, '0', 10) <= 0) {
  185. throw new \RuntimeException('GAME_RECYCLE_RATE 必须是大于 0 的数字');
  186. }
  187. return $rate;
  188. }
  189. private function balancesFromResponse($response): ?array
  190. {
  191. if (!$response instanceof Response) {
  192. return null;
  193. }
  194. $body = $response->json();
  195. if (!is_array($body)) {
  196. return null;
  197. }
  198. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  199. return is_array($body['data'] ?? null) ? $body['data'] : [];
  200. }
  201. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  202. return [];
  203. }
  204. Log::warning('third_game_balance_query_failed', [
  205. 'code' => $body['code'] ?? null,
  206. 'msg' => $body['msg'] ?? null,
  207. ]);
  208. return null;
  209. }
  210. private function detailResult(string $memberId, array $balances): array
  211. {
  212. $gameBalance = $this->sumBalances($balances);
  213. $walletBalances = [];
  214. $gameBalances = [];
  215. foreach ($balances as $platform => $balance) {
  216. if (is_numeric($balance)) {
  217. $walletBalances[] = [
  218. 'platform' => (string) $platform,
  219. 'balance' => (float) $balance,
  220. ];
  221. $gameBalances[] = [
  222. 'platform' => (string) $platform,
  223. 'balance' => (float) $balance,
  224. ];
  225. }
  226. }
  227. return [
  228. 'ok' => true,
  229. 'member_id' => $memberId,
  230. 'player_id' => $this->playerId($memberId),
  231. 'currency' => (string) config('third_game.currency', 'CNY'),
  232. 'rate' => 1,
  233. 'list' => $walletBalances,
  234. 'game_list' => $gameBalances,
  235. 'total_game_balance' => (float) $gameBalance,
  236. 'total_balance' => $this->totalFromBalances($balances),
  237. ];
  238. }
  239. private function totalFromBalances(array $balances): float
  240. {
  241. return (float) $this->sumBalances($balances);
  242. }
  243. private function sumBalances(array $balances): string
  244. {
  245. $total = '0.0000000000';
  246. foreach ($balances as $balance) {
  247. $amount = $this->decimalAmount($balance);
  248. if ($amount !== null) {
  249. $total = bcadd($total, $amount, 10);
  250. }
  251. }
  252. return $total;
  253. }
  254. private function decimalAmount($value): ?string
  255. {
  256. if (!is_int($value) && !is_float($value) && !is_string($value)) {
  257. return null;
  258. }
  259. $value = trim((string) $value);
  260. if (!preg_match('/^\d+(?:\.\d+)?$/D', $value)) {
  261. return null;
  262. }
  263. return bcadd($value, '0', 10);
  264. }
  265. private function request(string $path, array $data, bool $transfer = false)
  266. {
  267. if (!$this->configured()) {
  268. return null;
  269. }
  270. $random = $this->random();
  271. try {
  272. return Http::asJson()
  273. ->withHeaders([
  274. 'sign' => md5($random . config('third_game.sn') . config('third_game.key')),
  275. 'random' => $random,
  276. 'sn' => config('third_game.sn'),
  277. ])
  278. ->timeout(max(1, (int) config(
  279. $transfer ? 'third_game.transfer_timeout' : 'third_game.timeout',
  280. $transfer ? 65 : 10
  281. )))
  282. ->connectTimeout(5)
  283. ->withOptions($this->httpOptions())
  284. ->post(config('third_game.api_url') . $path, $data);
  285. } catch (\Throwable $e) {
  286. Log::warning('third_game_request_failed', [
  287. 'path' => $path,
  288. 'message' => $e->getMessage(),
  289. ]);
  290. return null;
  291. }
  292. }
  293. private function responseMessage($response): string
  294. {
  295. if (!$response instanceof Response) {
  296. return $this->configured() ? '三方游戏接口请求失败' : '三方游戏配置缺失';
  297. }
  298. return (string) ($response->json('msg') ?: '三方游戏接口异常');
  299. }
  300. private function configured(): bool
  301. {
  302. return config('third_game.api_url') !== ''
  303. && config('third_game.sn') !== ''
  304. && config('third_game.key') !== '';
  305. }
  306. private function isPlayerNotFound(string $message): bool
  307. {
  308. $message = strtolower($message);
  309. return str_contains($message, 'playerid')
  310. && (str_contains($message, '不存在')
  311. || str_contains($message, 'not exist')
  312. || str_contains($message, 'not found'));
  313. }
  314. private function httpOptions(): array
  315. {
  316. $options = [];
  317. $proxy = (string) config('third_game.proxy', '');
  318. if ($proxy !== '') {
  319. $options['proxy'] = $proxy;
  320. }
  321. $caBundle = (string) config('third_game.ca_bundle', '');
  322. if ($caBundle !== '') {
  323. $options['verify'] = $caBundle;
  324. }
  325. return $options;
  326. }
  327. private function cacheKey(string $memberId): string
  328. {
  329. return 'third_game_total_balance:' . $memberId;
  330. }
  331. private function detailCacheKey(string $memberId): string
  332. {
  333. return 'third_game_balance_detail:' . $memberId;
  334. }
  335. private function clearCache(string $memberId): void
  336. {
  337. Cache::forget($this->cacheKey($memberId));
  338. Cache::forget($this->detailCacheKey($memberId));
  339. }
  340. private function random(): string
  341. {
  342. $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
  343. $value = '';
  344. for ($i = 0; $i < 32; $i++) {
  345. $value .= $characters[random_int(0, strlen($characters) - 1)];
  346. }
  347. return $value;
  348. }
  349. }