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/Services/Payment/StripeConfig.php

247 lines
8.9 KiB
PHP

<?php
namespace App\Services\Payment;
use App\Models\Configurations;
use App\Services\Config;
/** Stripe Checkout configuration. The panel ledger is denominated in USD. */
final class StripeConfig
{
public const API_SECRET_KEY = 'stripe_secret_key';
public const WEBHOOK_SECRET_KEY = 'stripe_webhook_secret';
public const API_BASE_URL = 'https://api.stripe.com/v1';
public const CURRENCY = 'usd';
private const DEFAULTS = [
'stripe_enabled' => 'false',
'stripe_test_mode' => 'true',
'stripe_card_enabled' => 'true',
'stripe_alipay_enabled' => 'false',
'stripe_callback_base_url' => '',
'stripe_min_amount' => '1.00',
'stripe_max_amount' => '10000.00',
'stripe_request_timeout_seconds' => '15',
];
public static function values(): array
{
$values = self::DEFAULTS;
if ($values['stripe_callback_base_url'] === '') {
$values['stripe_callback_base_url'] = rtrim(
(string) Config::get('baseUrl', ''),
'/'
);
}
try {
$rows = Configurations::whereIn('name', array_merge(
array_keys(self::DEFAULTS),
[self::API_SECRET_KEY, self::WEBHOOK_SECRET_KEY]
))->get()->keyBy('name');
foreach (array_keys(self::DEFAULTS) as $key) {
if (isset($rows[$key])) {
$values[$key] = (string) $rows[$key]->value;
}
}
$values['stripe_secret_configured'] = isset($rows[self::API_SECRET_KEY])
&& trim((string) $rows[self::API_SECRET_KEY]->value) !== '';
$values['stripe_webhook_secret_configured'] =
isset($rows[self::WEBHOOK_SECRET_KEY])
&& trim((string) $rows[self::WEBHOOK_SECRET_KEY]->value) !== '';
} catch (\Throwable $exception) {
$values['stripe_secret_configured'] = false;
$values['stripe_webhook_secret_configured'] = false;
}
foreach (['stripe_enabled', 'stripe_test_mode',
'stripe_card_enabled', 'stripe_alipay_enabled'] as $key) {
$values[$key] = self::truthy($values[$key]);
}
$values['stripe_min_amount'] = PaymentAmount::normalize(
$values['stripe_min_amount']
);
$values['stripe_max_amount'] = PaymentAmount::normalize(
$values['stripe_max_amount']
);
$values['stripe_request_timeout_seconds'] = max(
3,
min(60, (int) $values['stripe_request_timeout_seconds'])
);
$values['stripe_currency'] = self::CURRENCY;
return $values;
}
public static function runtime(bool $requireEnabled = true,
?string $method = null): array
{
$values = self::values();
if ($requireEnabled && !$values['stripe_enabled']) {
throw new \RuntimeException('Stripe 支付暂未开放');
}
if (!self::isHttpsUrl($values['stripe_callback_base_url'])) {
throw new \RuntimeException('Stripe 回调地址必须使用无查询参数的 HTTPS 地址');
}
if ($method !== null) {
self::assertMethod($method);
if (!$values['stripe_' . $method . '_enabled']) {
throw new \RuntimeException(
$method === 'alipay'
? 'Stripe 支付宝暂未开放' : 'Stripe 银行卡暂未开放'
);
}
}
return array_merge($values, self::apiCredentials(),
self::webhookCredentials());
}
public static function runtimeForUser($user, string $method): array
{
$values = self::runtime(true, $method);
if (!self::canUserAccess($user, $values)) {
throw new \RuntimeException('Stripe 当前处于测试模式,仅管理员可用');
}
return $values;
}
public static function apiRuntime(): array
{
return array_merge(self::values(), self::apiCredentials());
}
public static function apiCredentials(): array
{
$values = self::values();
if (!$values['stripe_secret_configured']) {
throw new \RuntimeException('Stripe API 密钥尚未配置');
}
$row = Configurations::where('name', self::API_SECRET_KEY)->first();
$secret = $row === null ? ''
: StripeCredentialCipher::decrypt((string) $row->value);
if (!preg_match('/^sk_(test|live)_[A-Za-z0-9_]{8,}$/D', $secret,
$matches)) {
throw new \RuntimeException('Stripe API 密钥格式无效');
}
$expectedMode = $values['stripe_test_mode'] ? 'test' : 'live';
if ($matches[1] !== $expectedMode) {
throw new \RuntimeException(
$values['stripe_test_mode']
? '测试模式必须使用 sk_test_ 密钥'
: '正式模式必须使用 sk_live_ 密钥'
);
}
return [self::API_SECRET_KEY => $secret];
}
public static function webhookCredentials(): array
{
$values = self::values();
if (!$values['stripe_webhook_secret_configured']) {
throw new \RuntimeException('Stripe Webhook 签名密钥尚未配置');
}
$row = Configurations::where('name', self::WEBHOOK_SECRET_KEY)->first();
$secret = $row === null ? ''
: StripeCredentialCipher::decrypt((string) $row->value);
if (!preg_match('/^whsec_[A-Za-z0-9_]{8,}$/D', $secret)) {
throw new \RuntimeException('Stripe Webhook 签名密钥格式无效');
}
return [self::WEBHOOK_SECRET_KEY => $secret];
}
public static function visibleMethods($user, ?array $values = null): array
{
$values = $values ?? self::values();
if (!self::canUserAccess($user, $values)) {
return [];
}
$methods = [];
foreach (['card', 'alipay'] as $method) {
if (!empty($values['stripe_' . $method . '_enabled'])) {
try {
self::runtimeForUser($user, $method);
$methods[] = $method;
} catch (\Throwable $exception) {
// An incomplete method is intentionally not advertised.
}
}
}
return $methods;
}
public static function canUserAccess($user, ?array $values = null): bool
{
$values = $values ?? self::values();
if (!self::truthy($values['stripe_enabled'] ?? false)) {
return false;
}
if (!self::truthy($values['stripe_test_mode'] ?? true)) {
return true;
}
return $user !== null && method_exists($user, 'isAdmin')
&& (bool) $user->isAdmin();
}
public static function save(array $values, string $apiSecret = '',
string $webhookSecret = ''): void
{
$apiSecret = trim($apiSecret);
$webhookSecret = trim($webhookSecret);
$encryptedApi = $apiSecret === '' ? ''
: StripeCredentialCipher::encrypt($apiSecret);
$encryptedWebhook = $webhookSecret === '' ? ''
: StripeCredentialCipher::encrypt($webhookSecret);
(new Configurations())->getConnection()->transaction(function () use (
$values,
$encryptedApi,
$encryptedWebhook
): void {
foreach (self::DEFAULTS as $key => $default) {
if (array_key_exists($key, $values)) {
self::set($key, (string) $values[$key]);
}
}
if ($encryptedApi !== '') {
self::set(self::API_SECRET_KEY, $encryptedApi);
}
if ($encryptedWebhook !== '') {
self::set(self::WEBHOOK_SECRET_KEY, $encryptedWebhook);
}
});
}
public static function truthy($value): bool
{
return in_array(strtolower(trim((string) $value)),
['1', 'true', 'yes', 'on'], true);
}
public static function isHttpsUrl($value): bool
{
$value = trim((string) $value);
if (filter_var($value, FILTER_VALIDATE_URL) === false
|| preg_match('#^https://#i', $value) !== 1) {
return false;
}
$parts = parse_url($value);
return is_array($parts) && empty($parts['user'])
&& empty($parts['pass']) && empty($parts['query'])
&& empty($parts['fragment']);
}
private static function assertMethod(string $method): void
{
if (!in_array($method, ['card', 'alipay'], true)) {
throw new \InvalidArgumentException('Stripe 支付方式无效');
}
}
private static function set(string $name, string $value): void
{
$row = Configurations::where('name', $name)->first();
if ($row === null) {
$row = new Configurations();
$row->name = $name;
}
$row->value = $value;
$row->save();
}
}