1.配置新版支付模块-菜单和接口都已重构

2.优化充值提现页面
3.菜单翻译问题
4.备份数据库
This commit is contained in:
2026-04-30 11:37:46 +08:00
parent e8c2b9d345
commit c7fc754573
23 changed files with 4042 additions and 400 deletions

View File

@@ -62,6 +62,7 @@ return [
'游戏对局' => 'Game rounds',
'游戏对局记录' => 'Game records',
'游戏实时对局' => 'Game live',
'游玩记录' => 'Play records',
'压注订单' => 'Bet orders',
'充值订单' => 'Deposit orders',
'提现订单' => 'Withdraw orders',
@@ -91,6 +92,20 @@ return [
'管理员钱包流水' => 'Admin wallet records',
'一键批量结算待结算渠道' => 'Batch settle pending channels',
'渠道结算统计' => 'Channel settlement statistics',
'推送配置' => 'Push configuration',
'连接服务器websocket' => 'Connect WebSocket server',
'连接配置' => 'Connection settings',
'数据快照' => 'Data snapshot',
'运行开关' => 'Runtime switch',
'预约开奖' => 'Schedule draw',
'作废本局' => 'Void round',
'计算盈亏' => 'Calculate P/L',
'档位查看' => 'View tiers',
'档位保存' => 'Save tiers',
'详情' => 'Detail',
'审核' => 'Review',
'通过' => 'Approve',
'拒绝' => 'Reject',
// 演示/运营公告标题(若入库为菜单展示)
'系统维护通知(演示)' => 'Maintenance notice (demo)',

View File

@@ -0,0 +1,348 @@
<?php
declare(strict_types=1);
namespace app\common\library\finance;
use InvalidArgumentException;
use RuntimeException;
use Webman\Http\Request;
/**
* DDPay 支付网关接入(基于文档 v1.1.3/1.1.x
* - MD5 签名key-value 按 ASCII 升序拼接 + 追加 &key=API_SECRET
* - 发送 HTTPS POSTapplication/json
* - 支持入金Deposit与回调通知Webhook
*
* 注意:生产环境需在 config/app.php 或环境变量中配置 DDPAY_*。
*/
final class DDPayGateway
{
private const SIGNATURE_FIELD = 'signature';
private const SECRET_KEY_PARAM = 'key';
/**
* 入金/出金回调 URL 使用的公网根地址(无尾部斜杠)。
* 优先 `DDPAY_PUBLIC_BASE_URL`(见 config/app.php未配置时按请求头推导生产务必配置 HTTPS 公网地址,与 DDPay 文档一致)。
*/
public static function publicBaseUrlForCallbacks(?Request $request = null): string
{
$cfg = config('app.ddpay_public_base_url', '');
if (is_string($cfg) && trim($cfg) !== '') {
return rtrim(trim($cfg), '/');
}
if ($request === null) {
return '';
}
$proto = strtolower((string) $request->header('x-forwarded-proto', ''));
$https = $proto === 'https' || strtolower((string) $request->header('x-forwarded-ssl', '')) === 'on';
$scheme = $https ? 'https' : 'http';
$host = trim((string) $request->header('host', ''));
if ($host === '') {
$host = trim((string) ($request->header('x-forwarded-host', '')));
}
if ($host === '') {
$host = '127.0.0.1:8787';
}
return $scheme . '://' . $host;
}
/**
* @return array<string, mixed>
*/
public static function depositInitiation(array $params): array
{
$endpoint = self::requireConfig('ddpay_deposit_init_url');
$apiSecret = self::requireConfig('ddpay_api_secret');
$req = $params;
if (isset($req[self::SIGNATURE_FIELD])) {
unset($req[self::SIGNATURE_FIELD]);
}
$req[self::SIGNATURE_FIELD] = self::computeSignature($req, $apiSecret);
$resp = self::postJson($endpoint, $req);
// 按文档:响应签名需使用同方法校验(字段名 signature
if (array_key_exists(self::SIGNATURE_FIELD, $resp)) {
$sig = is_string($resp[self::SIGNATURE_FIELD]) ? $resp[self::SIGNATURE_FIELD] : '';
if ($sig !== '') {
$respForSign = $resp;
unset($respForSign[self::SIGNATURE_FIELD]);
$expected = self::computeSignature($respForSign, $apiSecret);
if (!hash_equals($expected, $sig)) {
throw new RuntimeException('DDPay response signature mismatch');
}
}
}
$statusCode = self::intValue($resp['status_code'] ?? 0);
if ($statusCode !== 0) {
$msg = is_string($resp['status_message'] ?? null) ? $resp['status_message'] : 'DDPay deposit initiation failed';
throw new RuntimeException($msg);
}
return $resp;
}
/**
* 出金发起Payout Initiation
*
* @param array<string, mixed> $params
* @return array<string, mixed>
*/
public static function payoutInitiation(array $params): array
{
$endpoint = self::requireConfig('ddpay_payout_init_url');
$apiSecret = self::requireConfig('ddpay_api_secret');
$req = $params;
if (isset($req[self::SIGNATURE_FIELD])) {
unset($req[self::SIGNATURE_FIELD]);
}
$req[self::SIGNATURE_FIELD] = self::computeSignature($req, $apiSecret);
$resp = self::postJson($endpoint, $req);
// 按文档:响应签名需使用同方法校验(字段名 signature
if (array_key_exists(self::SIGNATURE_FIELD, $resp)) {
$sig = is_string($resp[self::SIGNATURE_FIELD]) ? $resp[self::SIGNATURE_FIELD] : '';
if ($sig !== '') {
$respForSign = $resp;
unset($respForSign[self::SIGNATURE_FIELD]);
$expected = self::computeSignature($respForSign, $apiSecret);
if (!hash_equals($expected, $sig)) {
throw new RuntimeException('DDPay response signature mismatch');
}
}
}
$statusCode = self::intValue($resp['status_code'] ?? 0);
if ($statusCode !== 0) {
$msg = is_string($resp['status_message'] ?? null) ? $resp['status_message'] : 'DDPay payout initiation failed';
throw new RuntimeException($msg);
}
return $resp;
}
/**
* 出金状态查询Payout Status Inquiry
*
* @param array<string, mixed> $params
* @return array<string, mixed>
*/
public static function payoutStatusInquiry(array $params): array
{
$endpoint = self::requireConfig('ddpay_payout_status_url');
$apiSecret = self::requireConfig('ddpay_api_secret');
$req = $params;
if (isset($req[self::SIGNATURE_FIELD])) {
unset($req[self::SIGNATURE_FIELD]);
}
$req[self::SIGNATURE_FIELD] = self::computeSignature($req, $apiSecret);
$resp = self::postJson($endpoint, $req);
if (array_key_exists(self::SIGNATURE_FIELD, $resp)) {
$sig = is_string($resp[self::SIGNATURE_FIELD]) ? $resp[self::SIGNATURE_FIELD] : '';
if ($sig !== '') {
$respForSign = $resp;
unset($respForSign[self::SIGNATURE_FIELD]);
$expected = self::computeSignature($respForSign, $apiSecret);
if (!hash_equals($expected, $sig)) {
throw new RuntimeException('DDPay response signature mismatch');
}
}
}
$statusCode = self::intValue($resp['status_code'] ?? 0);
if ($statusCode !== 0) {
$msg = is_string($resp['status_message'] ?? null) ? $resp['status_message'] : 'DDPay payout status inquiry failed';
throw new RuntimeException($msg);
}
return $resp;
}
/**
* 校验 DDPay Webhook 通知签名。
*
* @param array<string, mixed> $payload
*/
public static function verifyWebhookSignature(array $payload): bool
{
$apiSecret = self::requireConfig('ddpay_api_secret');
$sigRaw = $payload[self::SIGNATURE_FIELD] ?? '';
$sig = is_string($sigRaw) ? trim($sigRaw) : '';
if ($sig === '') {
return false;
}
$payloadForSign = $payload;
unset($payloadForSign[self::SIGNATURE_FIELD]);
$expected = self::computeSignature($payloadForSign, $apiSecret);
return hash_equals($expected, $sig);
}
/**
* @param array<string, mixed> $params
*/
private static function computeSignature(array $params, string $apiSecret): string
{
// 1) 排除 signature & 空值/null
$filtered = [];
foreach ($params as $k => $v) {
if (!is_string($k) || $k === '') {
continue;
}
if ($k === self::SIGNATURE_FIELD) {
continue;
}
if ($v === null) {
continue;
}
if (is_string($v) && trim($v) === '') {
continue;
}
if (is_bool($v)) {
$filtered[$k] = $v ? 'true' : 'false';
continue;
}
if (is_int($v) || is_float($v) || is_numeric($v)) {
$filtered[$k] = strval($v);
continue;
}
if (is_string($v)) {
$filtered[$k] = trim($v);
continue;
}
// 数组/对象等不应参与签名;忽略它们
if (is_array($v) || is_object($v)) {
continue;
}
$filtered[$k] = strval($v);
}
// 2) 按 ASCII 升序排序 key
ksort($filtered, SORT_STRING);
// 3) 拼接 key=value用 & 连接
$pairs = [];
foreach ($filtered as $k => $v) {
$pairs[] = $k . '=' . $v;
}
// 4) 追加 &key=API_SECRET
$base = implode('&', $pairs);
$signStr = $base . '&' . self::SECRET_KEY_PARAM . '=' . $apiSecret;
// 5) MD5 小写
$hash = md5($signStr);
return is_string($hash) ? strtolower($hash) : '';
}
/**
* @param array<string, mixed> $payload
* @return array<string, mixed>
*/
private static function postJson(string $url, array $payload): array
{
if (!function_exists('curl_init')) {
throw new RuntimeException('curl extension is required for DDPayGateway');
}
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($body) || $body === '') {
throw new RuntimeException('DDPay request body encode failed');
}
$ch = curl_init($url);
if ($ch === false) {
throw new RuntimeException('DDPay curl_init failed');
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json; charset=utf-8',
'Accept: application/json',
]);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$respBody = curl_exec($ch);
$errno = curl_errno($ch);
$httpCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($respBody === false) {
throw new RuntimeException('DDPay request failed: ' . ($errno > 0 ? 'curl_' . strval($errno) : 'unknown'));
}
if (!is_numeric($httpCode)) {
throw new RuntimeException('DDPay request http code invalid');
}
$httpCodeInt = intval(strval($httpCode));
if ($httpCodeInt < 200 || $httpCodeInt >= 300) {
$snippet = '';
if (is_string($respBody)) {
$snippet = trim($respBody);
if (mb_strlen($snippet) > 400) {
$snippet = mb_substr($snippet, 0, 400) . '...';
}
}
$suffix = $snippet !== '' ? (' body=' . $snippet) : '';
throw new RuntimeException('DDPay request http failed, http_code=' . strval($httpCodeInt) . $suffix);
}
$decoded = json_decode(is_string($respBody) ? $respBody : '', true);
if (!is_array($decoded)) {
throw new RuntimeException('DDPay response decode failed');
}
return $decoded;
}
/**
* @return mixed
*/
private static function requireConfig(string $key): mixed
{
$v = config('app.' . $key, '');
if (!is_string($v)) {
return '';
}
$s = trim($v);
if ($s === '') {
throw new InvalidArgumentException('Missing config: app.' . $key);
}
return $s;
}
/**
* @param mixed $v
*/
private static function intValue(mixed $v): int
{
if (is_int($v)) {
return $v;
}
if (is_string($v) && $v !== '') {
$n = filter_var($v, FILTER_VALIDATE_INT);
return $n === false ? 0 : intval(strval($n));
}
if (is_numeric($v)) {
$n = filter_var($v, FILTER_VALIDATE_INT);
return $n === false ? 0 : intval(strval($n));
}
return 0;
}
}

View File

@@ -1,71 +0,0 @@
<?php
declare(strict_types=1);
namespace app\common\library\finance;
/**
* 模拟第三方支付HMAC 签名的收银台地址 + 回调验签,便于未来替换为真实网关仅改 URL/验签实现。
*/
final class DepositMockGateway
{
/**
* 优先读取环境变量 DEPOSIT_MOCK_HMAC_KEY其次 config('app.deposit_mock_hmac_key'),再使用开发默认值(生产环境务必设置 env
*/
public static function hmacKey(): string
{
$raw = getenv('DEPOSIT_MOCK_HMAC_KEY');
if (is_string($raw) && trim($raw) !== '') {
return trim($raw);
}
$cfg = config('app.deposit_mock_hmac_key', '');
if (is_string($cfg) && $cfg !== '') {
return $cfg;
}
return 'webman-dfw-deposit-mock-dev-key-set-DEPOSIT_MOCK_HMAC_KEY-in-prod';
}
public static function signOrderNo(string $orderNo): string
{
if ($orderNo === '') {
return '';
}
return hash_hmac('sha256', $orderNo, self::hmacKey());
}
public static function verifyOrderNo(string $orderNo, string $sign): bool
{
if ($orderNo === '' || $sign === '') {
return false;
}
$e = self::signOrderNo($orderNo);
if ($e === '') {
return false;
}
return hash_equals($e, $sign);
}
/**
* 玩家浏览器打开的「第三方收银台」地址(本项目中为简单 HTML 模拟页,点击后向 notify 发起 POST 完成入账)。
*
* @param string|null $publicOrigin 如 https://api.example.com为 null 时只返回以 / 开头的 path+query由客户端与 API 域名拼接
*/
public static function payPageUrl(string $orderNo, ?string $publicOrigin = null): string
{
$sign = self::signOrderNo($orderNo);
$q = http_build_query([
'order_no' => $orderNo,
'sign' => $sign,
]);
$path = '/api/finance/depositMockPayPage?' . $q;
if ($publicOrigin === null) {
return $path;
}
$base = rtrim($publicOrigin, '/');
return $base . $path;
}
}

View File

@@ -10,9 +10,9 @@ use support\think\Db;
/**
* 充值支付渠道:优先读取 game_config.finance_cashier.channels无此键时回退 game_config.deposit_channel迁移期镜像
*
* 每项code须在代码/环境注册表内、sort、status(0/1)。
* 每项code须在代码/环境注册表内、sort、status(0/1)。**代码注册表当前仅内置 `ddpay`**DDPay 网关)。
*
* 渠道展示名以代码注册表为准;运营只配置开关排序,默认兼容全部充值档位。
* 渠道展示名以代码注册表为准;运营只配置开关排序与支持币种,默认兼容全部充值档位。
*/
final class DepositChannel
{
@@ -23,8 +23,9 @@ final class DepositChannel
*/
public static function codeRegistry(): array
{
// 仅保留 DDPay充值/回调只走网关文档约定,不再提供模拟或其它渠道码
$base = [
'directpay' => ['name' => 'DirectPay', 'name_en' => 'DirectPay', 'sort' => 10],
'ddpay' => ['name' => 'DDPay', 'name_en' => 'DDPay', 'sort' => 10],
];
$extra = self::registryFromEnv();
foreach ($extra as $code => $meta) {
@@ -150,17 +151,55 @@ final class DepositChannel
$sort = isset($row['sort']) && is_numeric($row['sort']) ? intval($row['sort']) : 0;
$status = isset($row['status']) && is_numeric($row['status']) ? intval($row['status']) : 1;
$status = $status === 1 ? 1 : 0;
$currencyCodes = null;
if (array_key_exists('currency_codes', $row)) {
if (is_array($row['currency_codes'])) {
$currencyCodes = self::normalizeCurrencyCodes($row['currency_codes']);
} else {
$currencyCodes = null;
}
}
$out[] = [
'code' => $code,
'sort' => $sort,
'status' => $status,
'tier_ids' => [],
// null 表示“兼容全部充值币种”(历史配置默认行为)
// 空数组 [] 表示“不支持任何充值币种”(运营可用作显式禁用某币种)
'currency_codes' => $currencyCodes,
];
}
return $out;
}
/**
* 归一化为小写/去空并返回大写币种码列表(允许为空数组)。
*
* @param mixed $raw
* @return list<string>
*/
private static function normalizeCurrencyCodes(mixed $raw): array
{
if (!is_array($raw)) {
return [];
}
$out = [];
foreach ($raw as $c) {
if (!is_string($c) && !is_numeric($c)) {
continue;
}
$s = is_string($c) ? trim($c) : strval($c);
$s = strtoupper($s);
if (!preg_match('/^[A-Z0-9]{2,12}$/', $s)) {
continue;
}
$out[] = $s;
}
$out = array_values(array_unique($out));
return $out;
}
/**
* 合并注册表与运营覆盖;若库中无覆盖则对注册表内全部渠道启用默认行
*
@@ -187,6 +226,7 @@ final class DepositChannel
'sort' => $sortVal,
'status' => 1,
'tier_ids' => [],
'currency_codes' => null, // 默认兼容全部币种(历史行为)
];
}
}
@@ -235,7 +275,7 @@ final class DepositChannel
*
* @return list<array{code: string, name: string, sort: int}>
*/
public static function channelsForTier(string $tierId, array $overrideRows, string $lang): array
public static function channelsForTier(string $tierId, array $overrideRows, string $lang, string $fiatCurrencyCode = ''): array
{
$registry = self::codeRegistry();
$out = [];
@@ -247,6 +287,9 @@ final class DepositChannel
if (!isset($registry[$code])) {
continue;
}
if ($fiatCurrencyCode !== '' && !self::isCurrencyAllowedForRow($row, $fiatCurrencyCode)) {
continue;
}
$meta = $registry[$code];
$name = self::pickLangName($meta, $lang);
$sortRaw = $row['sort'] ?? 0;
@@ -268,6 +311,27 @@ final class DepositChannel
return $out;
}
private static function isCurrencyAllowedForRow(array $row, string $fiatCurrencyCode): bool
{
$normCurrency = strtoupper(trim($fiatCurrencyCode));
if ($normCurrency === '') {
return true;
}
$cc = $row['currency_codes'] ?? null;
if ($cc === null) {
// 历史/默认配置:不填则表示兼容全部币种
return true;
}
if (!is_array($cc)) {
return true;
}
// 显式空数组:不支持任何币种
if ($cc === []) {
return false;
}
return in_array($normCurrency, $cc, true);
}
/**
* @param array<string, string> $meta
*/
@@ -300,6 +364,22 @@ final class DepositChannel
return self::isTierAllowed($row, $tierId);
}
/**
* @param array<array{code: string, sort: int, status: int, tier_ids: list<string>, currency_codes: (list<string>|null)}> $effectiveRows
*/
public static function assertChannelAllowsCurrency(string $channelCode, string $fiatCurrencyCode, array $effectiveRows): bool
{
$row = self::findMergedByCode($effectiveRows, $channelCode);
if ($row === null) {
return false;
}
if (($row['status'] ?? 0) !== 1) {
return false;
}
return self::isCurrencyAllowedForRow($row, $fiatCurrencyCode);
}
/**
* @param list<array{code: string, sort: int, status: int, tier_ids: list<string>}> $effectiveRows
*
@@ -399,6 +479,7 @@ final class DepositChannel
'sort' => $sortDefault,
'status' => 1,
'tier_ids' => [],
'currency_codes' => null,
];
}
usort($items, static function (array $a, array $b): int {

View File

@@ -37,24 +37,23 @@ final class FinanceCashierConfig
'withdraw_coins_per_fiat' => '100',
],
[
'code' => 'VND',
'label_zh' => '越南盾',
'label_en' => 'Vietnamese Dong',
'code' => 'THB',
'label_zh' => '泰铢',
'label_en' => 'Thai Baht',
'sort' => 20,
'deposit_coins_per_fiat' => '10',
'withdraw_coins_per_fiat' => '10',
],
[
'code' => 'USDT',
'label_zh' => 'USDT',
'label_en' => 'USDT',
'sort' => 30,
'deposit_coins_per_fiat' => '1',
'withdraw_coins_per_fiat' => '1',
'deposit_coins_per_fiat' => '100',
'withdraw_coins_per_fiat' => '100',
],
],
'deposit_banks' => [
['currency_code' => 'MYR', 'code' => 'pbb', 'name_zh' => 'Public Bank', 'name_en' => 'Public Bank', 'sort' => 10],
['currency_code' => 'MYR', 'code' => 'mbb', 'name_zh' => 'Maybank2U', 'name_en' => 'Maybank2U', 'sort' => 20],
['currency_code' => 'THB', 'code' => '106', 'name_zh' => 'BANGKOK BANK PUBLIC COMPANY LTD.', 'name_en' => 'BANGKOK BANK PUBLIC COMPANY LTD.', 'sort' => 10],
['currency_code' => 'THB', 'code' => '107', 'name_zh' => 'KASIKORNBANK PUBLIC COMPANY LIMITED', 'name_en' => 'KASIKORNBANK PUBLIC COMPANY LIMITED', 'sort' => 20],
],
'withdraw_banks' => [
['code' => 'agrobank', 'name_zh' => 'Agrobank', 'name_en' => 'Agrobank', 'sort' => 10],
['currency_code' => 'MYR', 'code' => 'pbb', 'name_zh' => 'Public Bank', 'name_en' => 'Public Bank', 'sort' => 10],
['currency_code' => 'MYR', 'code' => 'mbb', 'name_zh' => 'Maybank2U', 'name_en' => 'Maybank2U', 'sort' => 20],
],
'withdraw_limits' => [
'min_ewallet' => '10',
@@ -69,12 +68,6 @@ final class FinanceCashierConfig
'fee_note_en' => 'A minimum RM 1 handling fee may apply for withdrawals between RM 10 and RM 99.99.',
'rate_mode' => 'fixed',
],
'withdraw_fields' => [
'require_cardholder' => true,
'require_bank_account' => true,
'require_email' => true,
'require_mobile' => true,
],
'channels' => [],
];
}
@@ -99,7 +92,7 @@ final class FinanceCashierConfig
if (isset($decoded['rates']) && is_array($decoded['rates'])) {
$legacyRates = array_values($decoded['rates']);
}
foreach (['currencies', 'withdraw_banks', 'channels'] as $listKey) {
foreach (['currencies', 'deposit_banks', 'withdraw_banks', 'channels'] as $listKey) {
if (isset($decoded[$listKey]) && is_array($decoded[$listKey])) {
$out[$listKey] = array_values($decoded[$listKey]);
}
@@ -110,9 +103,6 @@ final class FinanceCashierConfig
if (isset($decoded['withdraw_copy']) && is_array($decoded['withdraw_copy'])) {
$out['withdraw_copy'] = array_replace($out['withdraw_copy'], array_intersect_key($decoded['withdraw_copy'], $out['withdraw_copy']));
}
if (isset($decoded['withdraw_fields']) && is_array($decoded['withdraw_fields'])) {
$out['withdraw_fields'] = array_replace($out['withdraw_fields'], array_intersect_key($decoded['withdraw_fields'], $out['withdraw_fields']));
}
return self::normalizePayload($out, $legacyRates);
}
@@ -208,33 +198,12 @@ final class FinanceCashierConfig
return strcmp($ca, $cb);
});
if (isset($out['withdraw_banks']) && is_array($out['withdraw_banks'])) {
foreach ($out['withdraw_banks'] as $i => $row) {
if (!is_array($row)) {
unset($out['withdraw_banks'][$i]);
continue;
}
$code = isset($row['code']) && is_string($row['code']) ? strtolower(trim($row['code'])) : '';
$out['withdraw_banks'][$i] = [
'code' => $code,
'name_zh' => isset($row['name_zh']) && is_string($row['name_zh']) ? trim($row['name_zh']) : '',
'name_en' => isset($row['name_en']) && is_string($row['name_en']) ? trim($row['name_en']) : '',
'sort' => self::normalizeSort($row['sort'] ?? 0),
];
}
$out['withdraw_banks'] = array_values(array_filter($out['withdraw_banks'], static fn ($r) => is_array($r) && $r['code'] !== ''));
usort($out['withdraw_banks'], static function (array $a, array $b): int {
$sa = $a['sort'] ?? 0;
$sb = $b['sort'] ?? 0;
if ($sa !== $sb) {
return $sa <=> $sb;
}
$ca = $a['code'] ?? '';
$cb = $b['code'] ?? '';
return strcmp($ca, $cb);
});
}
$out['deposit_banks'] = self::normalizeBanksByCurrency(
isset($out['deposit_banks']) && is_array($out['deposit_banks']) ? $out['deposit_banks'] : []
);
$out['withdraw_banks'] = self::normalizeBanksByCurrency(
isset($out['withdraw_banks']) && is_array($out['withdraw_banks']) ? $out['withdraw_banks'] : []
);
if (isset($out['withdraw_limits']) && is_array($out['withdraw_limits'])) {
$wl = array_replace($defaults['withdraw_limits'], $out['withdraw_limits']);
foreach (['min_ewallet', 'min_bank'] as $k) {
@@ -257,13 +226,6 @@ final class FinanceCashierConfig
}
$out['withdraw_copy']['rate_mode'] = $mode;
}
if (isset($out['withdraw_fields']) && is_array($out['withdraw_fields'])) {
$wf = array_replace($defaults['withdraw_fields'], array_intersect_key($out['withdraw_fields'], $defaults['withdraw_fields']));
foreach (array_keys($defaults['withdraw_fields']) as $fk) {
$wf[$fk] = !empty($wf[$fk]);
}
$out['withdraw_fields'] = $wf;
}
if (isset($out['channels']) && is_array($out['channels'])) {
$out['channels'] = DepositChannel::normalizeOverrides(array_values($out['channels']));
} else {
@@ -280,6 +242,8 @@ final class FinanceCashierConfig
});
unset($out['fx_pairs']);
// 历史 JSON 可能含 withdraw_fields已废弃不再落库与返回给后台表单
unset($out['withdraw_fields']);
return $out;
}
@@ -322,6 +286,57 @@ final class FinanceCashierConfig
return 0;
}
/**
* @param list<mixed> $rows
* @return list<array{currency_code: string, code: string, name_zh: string, name_en: string, sort: int}>
*/
private static function normalizeBanksByCurrency(array $rows): array
{
$out = [];
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$currencyCode = isset($row['currency_code']) && is_string($row['currency_code']) ? strtoupper(trim($row['currency_code'])) : '';
if ($currencyCode === '') {
$currencyCode = 'MYR';
}
$codeRaw = $row['code'] ?? '';
$code = '';
if (is_string($codeRaw)) {
$code = strtolower(trim($codeRaw));
} elseif (is_numeric($codeRaw)) {
$code = strtolower(trim(strval($codeRaw)));
}
$out[] = [
'currency_code' => $currencyCode,
'code' => $code,
'name_zh' => isset($row['name_zh']) && is_string($row['name_zh']) ? trim($row['name_zh']) : '',
'name_en' => isset($row['name_en']) && is_string($row['name_en']) ? trim($row['name_en']) : '',
'sort' => self::normalizeSort($row['sort'] ?? 0),
];
}
$out = array_values(array_filter($out, static fn ($r) => is_array($r) && $r['currency_code'] !== '' && $r['code'] !== ''));
usort($out, static function (array $a, array $b): int {
$ca = isset($a['currency_code']) && is_string($a['currency_code']) ? $a['currency_code'] : '';
$cb = isset($b['currency_code']) && is_string($b['currency_code']) ? $b['currency_code'] : '';
if ($ca !== $cb) {
return strcmp($ca, $cb);
}
$sa = isset($a['sort']) && is_numeric($a['sort']) ? intval(strval($a['sort'])) : 0;
$sb = isset($b['sort']) && is_numeric($b['sort']) ? intval(strval($b['sort'])) : 0;
if ($sa !== $sb) {
return $sa <=> $sb;
}
$ka = isset($a['code']) && is_string($a['code']) ? $a['code'] : '';
$kb = isset($b['code']) && is_string($b['code']) ? $b['code'] : '';
return strcmp($ka, $kb);
});
return $out;
}
/**
* @param array<string, mixed> $p
*/
@@ -360,20 +375,57 @@ final class FinanceCashierConfig
throw new InvalidArgumentException('Withdraw rate must be a number greater than 0');
}
}
if (isset($p['withdraw_banks']) && is_array($p['withdraw_banks'])) {
// 校验 deposit channels 的币种白名单currency_codes 仅允许来自 currencies
if (isset($p['channels']) && is_array($p['channels'])) {
foreach ($p['channels'] as $row) {
if (!is_array($row)) {
continue;
}
$status = isset($row['status']) && is_numeric($row['status']) ? intval($row['status']) : 0;
$cc = array_key_exists('currency_codes', $row) ? ($row['currency_codes'] ?? null) : null;
if ($cc === null) {
continue; // null => 兼容全部币种(历史配置默认行为)
}
if (!is_array($cc)) {
throw new InvalidArgumentException('Channel currency_codes format error');
}
if ($status === 1 && $cc === []) {
throw new InvalidArgumentException('Enabled channel currency_codes can not be empty');
}
foreach ($cc as $c) {
if (!is_string($c) || !preg_match('/^[A-Z0-9]{2,12}$/', $c)) {
throw new InvalidArgumentException('Channel currency_codes contains invalid currency code');
}
if (!isset($seenCodes[$c])) {
throw new InvalidArgumentException('Channel currency_codes contains currency not configured');
}
}
}
}
foreach (['deposit_banks', 'withdraw_banks'] as $bankKey) {
if (!isset($p[$bankKey]) || !is_array($p[$bankKey])) {
continue;
}
$seen = [];
foreach ($p['withdraw_banks'] as $idx => $row) {
foreach ($p[$bankKey] as $row) {
if (!is_array($row)) {
throw new InvalidArgumentException('Bank row format error');
}
$currencyCode = $row['currency_code'] ?? '';
if (!is_string($currencyCode) || !isset($seenCodes[$currencyCode])) {
throw new InvalidArgumentException('Bank currency_code is invalid');
}
$code = $row['code'] ?? '';
if (!is_string($code) || !preg_match('/^[a-z0-9][a-z0-9_\-]{0,31}$/', $code)) {
throw new InvalidArgumentException('Bank code is invalid');
}
if (isset($seen[$code])) {
$uniq = $currencyCode . '|' . $code;
if (isset($seen[$uniq])) {
throw new InvalidArgumentException('Duplicate bank code');
}
$seen[$code] = true;
$seen[$uniq] = true;
}
}
if (isset($p['withdraw_limits']) && is_array($p['withdraw_limits'])) {

View File

@@ -0,0 +1,232 @@
<?php
declare(strict_types=1);
namespace app\common\middleware;
use support\Log;
use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
/**
* 接口调用日志中间件
*
* 目标:
* - 统一记录接口调用(请求 + 响应)
* - 成功记录返回参数
* - 失败记录失败原因
*/
class InterfaceRequestLog implements MiddlewareInterface
{
/**
* 仅记录接口路由(避免静态资源噪音)
*/
private const API_PATH_PREFIXES = ['api/', 'admin/'];
/**
* 需要脱敏的字段名(不区分大小写)
*/
private const SENSITIVE_KEYS = [
'password',
'oldpassword',
'newpassword',
'token',
'user-token',
'user_token',
'auth-token',
'auth_token',
'refresh_token',
'secret',
'signature',
'sign',
];
public function process(Request $request, callable $handler): Response
{
$path = trim($request->path(), '/');
if (!$this->shouldLogPath($path)) {
return $handler($request);
}
$start = microtime(true);
$requestPayload = $this->buildRequestPayload($request);
try {
$response = $handler($request);
} catch (Throwable $e) {
$costMs = $this->costMs($start);
Log::error('[InterfaceRequestLog] ' . $this->encodeJson([
'path' => '/' . $path,
'method' => strtoupper($request->method()),
'ip' => $request->getRealIp(),
'cost_ms' => $costMs,
'request' => $requestPayload,
'success' => false,
'fail_reason' => $e->getMessage(),
'exception_class' => get_class($e),
'exception_trace' => $this->truncateText($e->getTraceAsString(), 3000),
]));
throw $e;
}
$costMs = $this->costMs($start);
$statusCode = method_exists($response, 'getStatusCode') ? intval($response->getStatusCode()) : 200;
$responseBodyRaw = $this->extractResponseBody($response);
$responseDecoded = $this->decodeJsonArray($responseBodyRaw);
$success = false;
$failReason = '';
$responseData = null;
if (is_array($responseDecoded)) {
if (array_key_exists('code', $responseDecoded)) {
$success = intval($responseDecoded['code']) === 1;
} else {
$success = $statusCode >= 200 && $statusCode < 400;
}
$responseData = $responseDecoded['data'] ?? $responseDecoded;
if (!$success) {
$failReasonRaw = $responseDecoded['message'] ?? ($responseDecoded['msg'] ?? '');
$failReason = is_string($failReasonRaw) ? $failReasonRaw : strval($failReasonRaw);
}
} else {
$success = $statusCode >= 200 && $statusCode < 400;
if ($success) {
$responseData = $this->truncateText($responseBodyRaw, 2000);
} else {
$failReason = $this->truncateText($responseBodyRaw, 2000);
}
}
$logPayload = [
'path' => '/' . $path,
'method' => strtoupper($request->method()),
'ip' => $request->getRealIp(),
'status_code' => $statusCode,
'cost_ms' => $costMs,
'request' => $requestPayload,
'success' => $success,
];
if ($success) {
$logPayload['response_data'] = $this->maskMixed($responseData);
Log::info('[InterfaceRequestLog] ' . $this->encodeJson($logPayload));
} else {
$logPayload['fail_reason'] = $failReason !== '' ? $failReason : 'Unknown error';
if (is_array($responseDecoded)) {
$logPayload['api_response'] = $this->maskMixed($responseDecoded);
}
Log::error('[InterfaceRequestLog] ' . $this->encodeJson($logPayload));
}
return $response;
}
private function shouldLogPath(string $path): bool
{
foreach (self::API_PATH_PREFIXES as $prefix) {
if (str_starts_with($path, $prefix)) {
return true;
}
}
return false;
}
private function buildRequestPayload(Request $request): array
{
$query = $request->get();
$post = $request->post();
if (!is_array($query)) {
$query = [];
}
if (!is_array($post)) {
$post = [];
}
$rawBody = method_exists($request, 'rawBody') ? strval($request->rawBody()) : '';
$jsonBody = [];
if ($rawBody !== '') {
$jsonDecoded = json_decode($rawBody, true);
if (is_array($jsonDecoded)) {
$jsonBody = $jsonDecoded;
}
}
return [
'query' => $this->maskMixed($query),
'post' => $this->maskMixed($post),
'json' => $this->maskMixed($jsonBody),
];
}
private function extractResponseBody(Response $response): string
{
if (method_exists($response, 'rawBody')) {
return strval($response->rawBody());
}
return '';
}
private function decodeJsonArray(string $content): ?array
{
if ($content === '') {
return null;
}
$decoded = json_decode($content, true);
return is_array($decoded) ? $decoded : null;
}
private function maskMixed($value, ?string $parentKey = null)
{
if (is_array($value)) {
$result = [];
foreach ($value as $k => $v) {
$keyName = is_string($k) ? $k : $parentKey;
$result[$k] = $this->maskMixed($v, $keyName);
}
return $result;
}
if ($parentKey !== null && $this->isSensitiveKey($parentKey)) {
return '***';
}
return $value;
}
private function isSensitiveKey(string $key): bool
{
$normalized = strtolower(trim($key));
foreach (self::SENSITIVE_KEYS as $sensitive) {
if ($normalized === $sensitive) {
return true;
}
if (str_contains($normalized, $sensitive)) {
return true;
}
}
return false;
}
private function truncateText(string $text, int $maxLen): string
{
if ($maxLen <= 0) {
return '';
}
if (mb_strlen($text) <= $maxLen) {
return $text;
}
return mb_substr($text, 0, $maxLen) . '...';
}
private function encodeJson(array $payload): string
{
return json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
private function costMs(float $start): int
{
return intval((microtime(true) - $start) * 1000);
}
}

View File

@@ -26,7 +26,7 @@ class LoadLangPack implements MiddlewareInterface
/**
* 解析当前请求语言。
* - 后台 admin优先请求头 think-langzh-cn / en其次 lang 头,再次查询/表单参数 lang支持 zh→zh-cn
* - 对外 api优先查询/表单参数 langzh / en其次 lang 头,再次 think-lang。
* - 对外 api优先查询/表单参数 langzh / en其次 lang 头,再次 think-lang;未显式指定时固定 zh-cn不使用 Accept-Language
*/
protected function resolveLangSet(Request $request): string
{
@@ -86,6 +86,11 @@ class LoadLangPack implements MiddlewareInterface
}
}
// 对外 api无显式 lang / think-lang 时默认中文,避免浏览器 Accept-Language: en 覆盖产品默认
if ($app === 'api') {
return 'zh-cn';
}
$acceptRaw = $request->header('accept-language');
$acceptLang = is_string($acceptRaw) ? $acceptRaw : '';
if (preg_match('/^zh[-_]?cn|^zh/i', $acceptLang)) {