新增 HttpMainSiteWalletBalanceClient,用于在配置启用时获取主站钱包余额。 更新 WalletBalanceController:根据主站 API 返回结果新增 main_balance 与 main_balance_formatted 字段。 在 lottery.php 中新增钱包余额 API 路径配置项。 增强 WalletBalanceTest,验证在配置主站 API 后可正确获取 main_balance。
62 lines
1.7 KiB
PHP
62 lines
1.7 KiB
PHP
<?php
|
||
|
||
namespace App\Services\Wallet;
|
||
|
||
use App\Models\Player;
|
||
use Illuminate\Support\Facades\Http;
|
||
|
||
/**
|
||
* 查询主站钱包余额(供玩家端余额接口填充 main_balance)。
|
||
*/
|
||
final class HttpMainSiteWalletBalanceClient
|
||
{
|
||
public function fetch(Player $player, string $currencyCode): ?int
|
||
{
|
||
$base = rtrim((string) config('lottery.main_site.wallet_api_url'), '/');
|
||
if ($base === '') {
|
||
return null;
|
||
}
|
||
|
||
$path = (string) config('lottery.main_site.wallet_balance_path', '/wallet/balance');
|
||
$url = $base.'/'.ltrim($path, '/');
|
||
$timeout = (int) config('lottery.main_site.wallet_timeout', 10);
|
||
$apiKey = config('lottery.main_site.wallet_api_key');
|
||
|
||
$headers = ['Accept' => 'application/json'];
|
||
if (is_string($apiKey) && $apiKey !== '') {
|
||
$headers['Authorization'] = 'Bearer '.$apiKey;
|
||
}
|
||
|
||
try {
|
||
$response = Http::withHeaders($headers)
|
||
->timeout($timeout)
|
||
->acceptJson()
|
||
->get($url, [
|
||
'site_code' => $player->site_code,
|
||
'site_player_id' => $player->site_player_id,
|
||
'currency_code' => $currencyCode,
|
||
]);
|
||
} catch (\Throwable) {
|
||
return null;
|
||
}
|
||
|
||
if (! $response->successful()) {
|
||
return null;
|
||
}
|
||
|
||
$payload = $response->json();
|
||
if (! is_array($payload)) {
|
||
return null;
|
||
}
|
||
|
||
$raw = data_get($payload, 'data.main_balance')
|
||
?? data_get($payload, 'main_balance');
|
||
|
||
if (! is_numeric($raw)) {
|
||
return null;
|
||
}
|
||
|
||
return max(0, (int) $raw);
|
||
}
|
||
}
|