You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Controllers/Admin/StripeController.php

244 lines
11 KiB
PHTML

<?php
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Models\StripeOrder;
use App\Services\AdminDataMasker;
use App\Services\AdminPermission;
use App\Services\Payment\PaymentAmount;
use App\Services\Payment\StripeClient;
use App\Services\Payment\StripeConfig;
class StripeController extends AdminController
{
public function index($request, $response, $args)
{
$this->setViewTheme('venix');
$config = StripeConfig::values();
$browserConfig = $config;
$callbackBase = rtrim((string)
($config['stripe_callback_base_url'] ?? ''), '/');
$browserConfig['stripe_callback_base_url_configured'] =
$callbackBase !== '';
$browserConfig['stripe_callback_base_url'] = '';
$orders = null;
$summary = ['total' => 0, 'pending' => 0, 'paid' => 0,
'paid_amount' => '0.00'];
$tableError = '';
$keyword = trim((string) $request->getParam('keyword', ''));
$status = trim((string) $request->getParam('status', ''));
$method = trim((string) $request->getParam('method', ''));
$page = max(1, min(100000, (int) $request->getParam('page', 1)));
try {
$query = StripeOrder::query()
->leftJoin('user', 'user.id', '=', 'stripe_orders.user_id')
->select('stripe_orders.id', 'stripe_orders.user_id',
'stripe_orders.payment_method', 'stripe_orders.amount',
'stripe_orders.currency', 'stripe_orders.livemode',
'stripe_orders.status', 'stripe_orders.created_at',
'user.email as user_email');
if ($keyword !== '') {
if (AdminPermission::isSuperAdmin()) {
$query->where(function ($builder) use ($keyword): void {
$builder->where('user.email', 'like',
'%' . $keyword . '%');
if (ctype_digit($keyword)) {
$builder->orWhere('stripe_orders.id', (int) $keyword)
->orWhere('stripe_orders.user_id',
(int) $keyword);
}
});
} elseif (ctype_digit($keyword)) {
$query->where(function ($builder) use ($keyword): void {
$builder->where('stripe_orders.id', (int) $keyword)
->orWhere('stripe_orders.user_id', (int) $keyword);
});
} else {
$query->whereRaw('1 = 0');
}
}
if (in_array($status, ['creating', 'pending', 'paid', 'failed',
'expired', 'not_created', 'creation_unknown'], true)) {
$query->where('stripe_orders.status', $status);
}
if (in_array($method, ['card', 'alipay'], true)) {
$query->where('stripe_orders.payment_method', $method);
}
$orders = $query->orderBy('stripe_orders.id', 'desc')
->paginate(30, ['*'], 'page', $page);
$orders->setPath('/admin/stripe');
$orders->appends(['keyword' => $keyword, 'status' => $status,
'method' => $method]);
foreach ($orders as $order) {
$order->setAttribute('user_email',
AdminDataMasker::email($order->user_email));
}
$summary['total'] = StripeOrder::count();
$summary['pending'] = StripeOrder::whereIn('status', [
'creating', 'pending', 'creation_unknown',
])->count();
$summary['paid'] = StripeOrder::where('status', 'paid')->count();
$summary['paid_amount'] = PaymentAmount::normalize(
StripeOrder::where('status', 'paid')->sum('amount')
);
} catch (\Throwable $exception) {
$tableError = 'Stripe 数据表不可用,请先导入 sql/stripe_payment.sql。';
}
return $this->view()
->assign('stripe_config', $browserConfig)
->assign('stripe_webhook_url', $callbackBase === '' ? ''
: $callbackBase . '/stripe/webhook')
->assign('stripe_orders', $orders)
->assign('stripe_summary', $summary)
->assign('stripe_table_error', $tableError)
->assign('stripe_filters', ['keyword' => $keyword,
'status' => $status, 'method' => $method])
->display('admin/stripe/index.tpl');
}
public function save($request, $response, $args)
{
$payload = $request->getParsedBody();
$payload = is_array($payload) ? $payload : [];
try {
$current = StripeConfig::values();
$values = $this->validateConfig($payload, $current);
$apiSecret = trim((string)
($payload[StripeConfig::API_SECRET_KEY] ?? ''));
$webhookSecret = trim((string)
($payload[StripeConfig::WEBHOOK_SECRET_KEY] ?? ''));
if (strlen($apiSecret) > 256 || strlen($webhookSecret) > 256) {
throw new \InvalidArgumentException('Stripe 密钥长度无效');
}
$apiForValidation = $apiSecret;
$webhookForValidation = $webhookSecret;
if ($apiForValidation === ''
&& $current['stripe_secret_configured']) {
$apiForValidation = StripeConfig::apiCredentials()[
StripeConfig::API_SECRET_KEY
];
}
if ($webhookForValidation === ''
&& $current['stripe_webhook_secret_configured']) {
$webhookForValidation = StripeConfig::webhookCredentials()[
StripeConfig::WEBHOOK_SECRET_KEY
];
}
if ($apiForValidation !== '') {
$this->assertApiKey($apiForValidation,
$values['stripe_test_mode'] === 'true');
}
if ($webhookForValidation !== ''
&& !preg_match('/^whsec_[A-Za-z0-9_]{8,}$/D',
$webhookForValidation)) {
throw new \InvalidArgumentException(
'Stripe Webhook 签名密钥格式无效'
);
}
if ($values['stripe_enabled'] === 'true') {
if ($values['stripe_card_enabled'] !== 'true'
&& $values['stripe_alipay_enabled'] !== 'true') {
throw new \InvalidArgumentException(
'至少启用 Stripe 银行卡或支付宝中的一种'
);
}
if ($values['stripe_callback_base_url'] === ''
|| $apiForValidation === ''
|| $webhookForValidation === '') {
throw new \InvalidArgumentException(
'启用 Stripe 前必须配置回调地址、API 密钥和 Webhook 签名密钥'
);
}
}
StripeConfig::save($values, $apiSecret, $webhookSecret);
return $this->json($response, 1, 'Stripe 配置保存成功');
} catch (\Throwable $exception) {
error_log('Stripe config save failed: ' . $exception->getMessage());
return $this->json($response, 0, $exception->getMessage(), 422);
}
}
public function test($request, $response, $args)
{
try {
$account = (new StripeClient(StripeConfig::apiRuntime()))
->retrieveAccount();
$suffix = $account['country'] !== ''
? ' · ' . $account['country'] : '';
return $this->json($response, 1,
'连接成功,Stripe 账户 ' . $account['id'] . $suffix);
} catch (\Throwable $exception) {
error_log('Stripe connection test failed: ' . $exception->getMessage());
return $this->json($response, 0,
'连接失败:' . $exception->getMessage(), 502);
}
}
private function validateConfig(array $payload, array $current): array
{
$callback = rtrim(trim((string)
($payload['stripe_callback_base_url'] ?? '')), '/');
$callback = $callback === ''
? trim((string) ($current['stripe_callback_base_url'] ?? ''))
: $callback;
if ($callback !== '' && !StripeConfig::isHttpsUrl($callback)) {
throw new \InvalidArgumentException(
'Stripe 回调地址必须是无查询参数的 HTTPS 地址'
);
}
$minimum = PaymentAmount::normalize(
$payload['stripe_min_amount'] ?? '1.00'
);
$maximum = PaymentAmount::normalize(
$payload['stripe_max_amount'] ?? '10000.00'
);
if ((float) $minimum < 0.50 || (float) $maximum > 1000000
|| (float) $minimum > (float) $maximum) {
throw new \InvalidArgumentException(
'Stripe 金额范围无效,最低金额不能低于 $0.50'
);
}
return [
'stripe_enabled' => StripeConfig::truthy(
$payload['stripe_enabled'] ?? 'false') ? 'true' : 'false',
'stripe_test_mode' => StripeConfig::truthy(
$payload['stripe_test_mode'] ?? 'false') ? 'true' : 'false',
'stripe_card_enabled' => StripeConfig::truthy(
$payload['stripe_card_enabled'] ?? 'false') ? 'true' : 'false',
'stripe_alipay_enabled' => StripeConfig::truthy(
$payload['stripe_alipay_enabled'] ?? 'false') ? 'true' : 'false',
'stripe_callback_base_url' => $callback,
'stripe_min_amount' => $minimum,
'stripe_max_amount' => $maximum,
'stripe_request_timeout_seconds' => (string) max(3,
min(60, (int) ($payload['stripe_request_timeout_seconds']
?? 15))),
];
}
private function assertApiKey(string $key, bool $testMode): void
{
if (!preg_match('/^sk_(test|live)_[A-Za-z0-9_]{8,}$/D', $key,
$matches)) {
throw new \InvalidArgumentException('Stripe API 密钥格式无效');
}
if ($matches[1] !== ($testMode ? 'test' : 'live')) {
throw new \InvalidArgumentException($testMode
? '测试模式必须使用 sk_test_ 密钥'
: '正式模式必须使用 sk_live_ 密钥');
}
}
private function json($response, int $ret, string $msg,
int $status = 200)
{
$response = $response->withStatus($status)
->withHeader('Content-Type', 'application/json; charset=utf-8');
$response->getBody()->write(json_encode([
'ret' => $ret, 'msg' => $msg,
], JSON_UNESCAPED_UNICODE));
return $response;
}
}