ThirdGameBalanceService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. * 批量查询用户的三方游戏总余额,返回值已按 GAME_RATE 换算为主钱包货币。
  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. $response = $this->request('/api/server/transferAll', [
  121. 'playerId' => $this->playerId($memberId),
  122. 'currency' => config('third_game.currency', 'CNY'),
  123. ], true);
  124. $body = $response instanceof Response ? $response->json() : null;
  125. if (!is_array($body)) {
  126. return [
  127. 'ok' => false,
  128. 'uncertain' => true,
  129. 'msg' => $response instanceof Response
  130. ? '三方游戏接口返回异常,回收结果待核对'
  131. : '三方游戏接口请求失败,回收结果待核对',
  132. ];
  133. }
  134. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  135. $data = $body['data'] ?? null;
  136. if (!is_array($data)
  137. || !array_key_exists('balanceAll', $data)
  138. || !is_numeric($data['balanceAll'])
  139. || (float) $data['balanceAll'] < 0) {
  140. return [
  141. 'ok' => false,
  142. 'uncertain' => true,
  143. 'msg' => '三方游戏回收成功响应缺少有效 balanceAll,回收结果待核对',
  144. ];
  145. }
  146. $gameBalance = (float) $data['balanceAll'];
  147. $this->clearCache($memberId);
  148. return [
  149. 'ok' => true,
  150. 'game_balance' => $gameBalance,
  151. 'wallet_balance' => $this->toWalletBalance($gameBalance),
  152. ];
  153. }
  154. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  155. $this->clearCache($memberId);
  156. return ['ok' => true, 'game_balance' => 0.0, 'wallet_balance' => 0.0];
  157. }
  158. return [
  159. 'ok' => false,
  160. 'uncertain' => false,
  161. 'msg' => $this->responseMessage($response),
  162. ];
  163. }
  164. public function toWalletBalance($gameBalance): float
  165. {
  166. return round((float) $gameBalance / $this->rate(), 2);
  167. }
  168. private function balancesFromResponse($response): ?array
  169. {
  170. if (!$response instanceof Response) {
  171. return null;
  172. }
  173. $body = $response->json();
  174. if (!is_array($body)) {
  175. return null;
  176. }
  177. if ((int) ($body['code'] ?? 0) === self::CODE_SUCCESS) {
  178. return is_array($body['data'] ?? null) ? $body['data'] : [];
  179. }
  180. if ($this->isPlayerNotFound((string) ($body['msg'] ?? ''))) {
  181. return [];
  182. }
  183. Log::warning('third_game_balance_query_failed', [
  184. 'code' => $body['code'] ?? null,
  185. 'msg' => $body['msg'] ?? null,
  186. ]);
  187. return null;
  188. }
  189. private function detailResult(string $memberId, array $balances): array
  190. {
  191. $gameBalance = array_sum(array_filter($balances, 'is_numeric'));
  192. $walletBalances = [];
  193. foreach ($balances as $platform => $balance) {
  194. if (is_numeric($balance)) {
  195. $walletBalances[$platform] = round((float) $balance / $this->rate(), 2);
  196. }
  197. }
  198. return [
  199. 'ok' => true,
  200. 'member_id' => $memberId,
  201. 'player_id' => $this->playerId($memberId),
  202. 'currency' => (string) config('third_game.currency', 'CNY'),
  203. 'rate' => $this->rate(),
  204. 'list' => $walletBalances,
  205. 'game_list' => $balances,
  206. 'total_game_balance' => round($gameBalance, 2),
  207. 'total_balance' => $this->totalFromBalances($balances),
  208. ];
  209. }
  210. private function totalFromBalances(array $balances): float
  211. {
  212. $gameBalance = array_sum(array_filter($balances, 'is_numeric'));
  213. return round($gameBalance / $this->rate(), 2);
  214. }
  215. private function rate(): float
  216. {
  217. $rate = (float) config('third_game.rate', 10);
  218. return $rate > 0 ? $rate : 1;
  219. }
  220. private function request(string $path, array $data, bool $transfer = false)
  221. {
  222. if (!$this->configured()) {
  223. return null;
  224. }
  225. $random = $this->random();
  226. try {
  227. return Http::asJson()
  228. ->withHeaders([
  229. 'sign' => md5($random . config('third_game.sn') . config('third_game.key')),
  230. 'random' => $random,
  231. 'sn' => config('third_game.sn'),
  232. ])
  233. ->timeout(max(1, (int) config(
  234. $transfer ? 'third_game.transfer_timeout' : 'third_game.timeout',
  235. $transfer ? 65 : 10
  236. )))
  237. ->connectTimeout(5)
  238. ->withOptions($this->httpOptions())
  239. ->post(config('third_game.api_url') . $path, $data);
  240. } catch (\Throwable $e) {
  241. Log::warning('third_game_request_failed', [
  242. 'path' => $path,
  243. 'message' => $e->getMessage(),
  244. ]);
  245. return null;
  246. }
  247. }
  248. private function responseMessage($response): string
  249. {
  250. if (!$response instanceof Response) {
  251. return $this->configured() ? '三方游戏接口请求失败' : '三方游戏配置缺失';
  252. }
  253. return (string) ($response->json('msg') ?: '三方游戏接口异常');
  254. }
  255. private function configured(): bool
  256. {
  257. return config('third_game.api_url') !== ''
  258. && config('third_game.sn') !== ''
  259. && config('third_game.key') !== '';
  260. }
  261. private function isPlayerNotFound(string $message): bool
  262. {
  263. $message = strtolower($message);
  264. return str_contains($message, 'playerid')
  265. && (str_contains($message, '不存在')
  266. || str_contains($message, 'not exist')
  267. || str_contains($message, 'not found'));
  268. }
  269. private function httpOptions(): array
  270. {
  271. $options = [];
  272. $proxy = (string) config('third_game.proxy', '');
  273. if ($proxy !== '') {
  274. $options['proxy'] = $proxy;
  275. }
  276. $caBundle = (string) config('third_game.ca_bundle', '');
  277. if ($caBundle !== '') {
  278. $options['verify'] = $caBundle;
  279. }
  280. return $options;
  281. }
  282. private function cacheKey(string $memberId): string
  283. {
  284. return 'third_game_total_balance:' . $memberId;
  285. }
  286. private function detailCacheKey(string $memberId): string
  287. {
  288. return 'third_game_balance_detail:' . $memberId;
  289. }
  290. private function clearCache(string $memberId): void
  291. {
  292. Cache::forget($this->cacheKey($memberId));
  293. Cache::forget($this->detailCacheKey($memberId));
  294. }
  295. private function random(): string
  296. {
  297. $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
  298. $value = '';
  299. for ($i = 0; $i < 32; $i++) {
  300. $value .= $characters[random_int(0, strlen($characters) - 1)];
  301. }
  302. return $value;
  303. }
  304. }