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/StripePaymentService.php

426 lines
18 KiB
PHP

<?php
namespace App\Services\Payment;
use App\Models\CloudInvoicePayment;
use App\Models\Paylist;
use App\Models\StripeOrder;
use App\Models\StripeWebhookEvent;
use App\Models\User;
use App\Services\Cloud\CloudInvoicePaymentService;
/** Hosted Stripe Checkout with signed, idempotent server-side settlement. */
class StripePaymentService
{
public const LEDGER_TYPE = 10007;
private const ORDER_PATTERN = '/^ST\d{14}[A-F0-9]{16}$/D';
private const EVENT_TYPES = [
'checkout.session.completed',
'checkout.session.async_payment_succeeded',
'checkout.session.async_payment_failed',
'checkout.session.expired',
];
public function createOrder(User $user, $rawAmount, string $method,
string $clientIp, string $userAgent, string $returnBaseUrl,
array $businessContext = [])
{
$method = strtolower(trim($method));
$settings = StripeConfig::runtimeForUser($user, $method);
$amount = $this->validateAmount($rawAmount, $settings);
$orderNo = $this->orderNo();
$now = time();
if (StripeOrder::where('user_id', (int) $user->id)
->where('created_at', '>=', $now - 60)->count() >= 5) {
throw new \RuntimeException('Stripe 下单过于频繁,请稍后重试');
}
$connection = (new StripeOrder())->getConnection();
$connection->transaction(function () use ($user, $amount, $method,
$orderNo, $now, $settings, $businessContext): void {
$lockedUser = User::where('id', (int) $user->id)
->lockForUpdate()->first();
if ($lockedUser === null) {
throw new \RuntimeException('支付账户不存在');
}
if ($businessContext !== []) {
CloudInvoicePaymentService::assertInvoicePaymentAllowed(
$lockedUser
);
}
$paylist = new Paylist();
$paylist->userid = (int) $user->id;
$paylist->total = $amount;
$paylist->status = 0;
$paylist->tradeno = $orderNo;
$paylist->datetime = $now;
$paylist->save();
$order = new StripeOrder();
$order->order_no = $orderNo;
$order->checkout_session_id = null;
$order->payment_intent_id = null;
$order->paylist_id = (int) $paylist->id;
$order->user_id = (int) $user->id;
$order->payment_method = $method;
$order->amount = $amount;
$order->currency = StripeConfig::CURRENCY;
$order->livemode = $settings['stripe_test_mode'] ? 0 : 1;
$order->checkout_url = null;
$order->status = 'creating';
$order->error_message = '';
$order->paid_at = 0;
$order->created_at = $now;
$order->updated_at = $now;
$order->save();
CloudInvoicePaymentService::recordAttempt(
$businessContext,
$orderNo,
$amount,
(int) $user->id,
$now
);
});
$returnBaseUrl = rtrim($returnBaseUrl, '/');
$isInvoice = $businessContext !== [];
$payload = [
'mode' => 'payment',
'payment_method_types' => [$method],
'client_reference_id' => $orderNo,
'customer_email' => trim((string) $user->email),
'success_url' => $returnBaseUrl
. '/stripe/return?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $returnBaseUrl . ($isInvoice
? '/user/cloud/invoices' : '/user/code?payment=stripe_cancelled'),
'expires_at' => $now + 1860,
'line_items' => [[
'quantity' => 1,
'price_data' => [
'currency' => StripeConfig::CURRENCY,
'unit_amount' => $this->amountCents($amount),
'product_data' => [
'name' => $isInvoice
? 'Virt Cloud invoice #' . (int) $businessContext['invoice_id']
: 'Account balance recharge',
],
],
]],
'metadata' => [
'virt_order_no' => $orderNo,
'virt_user_id' => (string) (int) $user->id,
'virt_purpose' => $isInvoice ? 'invoice' : 'recharge',
],
'payment_intent_data' => [
'metadata' => [
'virt_order_no' => $orderNo,
'virt_user_id' => (string) (int) $user->id,
],
],
];
try {
$session = $this->gatewayClient($settings)
->createCheckoutSession($payload, $orderNo);
return $this->bindSession($orderNo, $session);
} catch (\Throwable $exception) {
$failedAt = time();
$effectUnknown = !($exception instanceof
PaymentOrderCreationException)
|| $exception->effectMayHaveApplied;
$failureStatus = $effectUnknown
? 'creation_unknown' : 'not_created';
$connection->transaction(function () use ($orderNo,
$businessContext, $exception, $failedAt,
$failureStatus): void {
StripeOrder::where('order_no', $orderNo)
->where('status', 'creating')->update([
'status' => $failureStatus,
'error_message' => mb_substr(
$exception->getMessage(), 0, 500
),
'updated_at' => $failedAt,
]);
if ($businessContext !== []) {
CloudInvoicePayment::where('provider_order_no', $orderNo)
->where('provider', (string)
($businessContext['provider'] ?? ''))
->where('status', 'creating')->update([
'status' => $failureStatus,
'updated_at' => $failedAt,
]);
}
});
throw $exception instanceof PaymentOrderCreationException
? $exception : PaymentOrderCreationException::unknown(
'Stripe Checkout 已发送,但本地结果未确认'
);
}
}
public function processWebhook(string $rawBody,
string $signatureHeader): array
{
$credentials = StripeConfig::webhookCredentials();
$event = StripeWebhookSignature::verify(
$rawBody,
$signatureHeader,
$credentials[StripeConfig::WEBHOOK_SECRET_KEY]
);
$eventId = trim((string) ($event['id'] ?? ''));
$eventType = trim((string) ($event['type'] ?? ''));
if (!preg_match('/^evt_[A-Za-z0-9]+$/D', $eventId)) {
throw new \RuntimeException('Stripe 事件 ID 无效');
}
if (!in_array($eventType, self::EVENT_TYPES, true)) {
return ['ignored' => true, 'duplicate' => false, 'credited' => false];
}
$session = $event['data']['object'];
$sessionId = trim((string) ($session['id'] ?? ''));
if (($session['object'] ?? '') !== 'checkout.session'
|| !preg_match('/^cs_(?:test|live)_[A-Za-z0-9]+$/D', $sessionId)) {
throw new \RuntimeException('Stripe Checkout 会话格式无效');
}
$metadata = is_array($session['metadata'] ?? null)
? $session['metadata'] : [];
$orderNo = trim((string) ($metadata['virt_order_no']
?? $session['client_reference_id'] ?? ''));
if (!preg_match(self::ORDER_PATTERN, $orderNo)) {
throw new \RuntimeException('Stripe 本地订单号无效');
}
$now = time();
$result = ['ignored' => false, 'duplicate' => false,
'credited' => false, 'order_no' => $orderNo];
$connection = (new StripeOrder())->getConnection();
$connection->transaction(function () use ($event, $eventId,
$eventType, $session, $sessionId, $orderNo, $rawBody, $now,
&$result): void {
$existingEvent = StripeWebhookEvent::where('event_id', $eventId)
->lockForUpdate()->first();
if ($existingEvent !== null) {
$result['duplicate'] = true;
return;
}
$order = StripeOrder::where('order_no', $orderNo)
->lockForUpdate()->first();
if ($order === null) {
throw new \RuntimeException('Stripe 本地订单不存在');
}
$this->assertSessionMatches($order, $event, $session,
$sessionId);
if (StripeOrder::where('checkout_session_id', $sessionId)
->where('order_no', '<>', $orderNo)->exists()) {
throw new \RuntimeException('Stripe Checkout 会话已绑定其他订单');
}
$webhook = new StripeWebhookEvent();
$webhook->event_id = $eventId;
$webhook->event_type = $eventType;
$webhook->object_id = $sessionId;
$webhook->order_no = $orderNo;
$webhook->livemode = !empty($event['livemode']) ? 1 : 0;
$webhook->payload = $rawBody;
$webhook->received_at = $now;
$webhook->processed_at = 0;
$webhook->save();
$order->checkout_session_id = $sessionId;
$paymentIntent = trim((string)
($session['payment_intent'] ?? ''));
if ($paymentIntent !== '') {
if (!preg_match('/^pi_[A-Za-z0-9]+$/D', $paymentIntent)) {
throw new \RuntimeException('Stripe PaymentIntent ID 无效');
}
if (StripeOrder::where('payment_intent_id', $paymentIntent)
->where('order_no', '<>', $orderNo)->exists()) {
throw new \RuntimeException(
'Stripe PaymentIntent 已绑定其他订单'
);
}
$order->payment_intent_id = $paymentIntent;
}
$successEvent = in_array($eventType, [
'checkout.session.completed',
'checkout.session.async_payment_succeeded',
], true) && (string) ($session['payment_status'] ?? '') === 'paid';
if ($successEvent && (string) $order->status !== 'paid') {
if (!in_array((string) $order->status, [
'creating', 'pending', 'failed', 'expired',
'creation_unknown', 'not_created',
], true)) {
throw new \RuntimeException('Stripe 本地订单状态无效');
}
$paylist = Paylist::where('id', (int) $order->paylist_id)
->lockForUpdate()->first();
if ($paylist === null
|| (string) $paylist->tradeno !== $orderNo
|| (int) $paylist->userid !== (int) $order->user_id) {
throw new \RuntimeException('Stripe 关联充值订单无效');
}
$result['credited'] = RechargeCreditService::creditLocked(
$paylist,
self::LEDGER_TYPE,
true
);
$provider = 'stripe_' . (string) $order->payment_method;
if (CloudInvoicePayment::where('provider', $provider)
->where('provider_order_no', $orderNo)->exists()) {
CloudInvoicePaymentService::settleForProvider(
$provider,
$orderNo
);
}
$order->status = 'paid';
$order->paid_at = $now;
$order->error_message = '';
} elseif (in_array($eventType, [
'checkout.session.async_payment_failed',
'checkout.session.expired',
], true) && (string) $order->status !== 'paid') {
$terminalStatus = $eventType === 'checkout.session.expired'
? 'expired' : 'failed';
$order->status = $terminalStatus;
$order->error_message = $terminalStatus === 'expired'
? 'Stripe Checkout 会话已过期'
: 'Stripe 异步付款失败';
$provider = 'stripe_' . (string) $order->payment_method;
CloudInvoicePaymentService::markProviderOrdersTerminal(
$provider, [$orderNo], $terminalStatus, $now
);
} elseif ((string) $order->status !== 'paid'
&& in_array((string) $order->status,
['creating', 'creation_unknown', 'not_created'], true)) {
// A valid signed session proves the create call applied even
// when the initial HTTPS response was lost.
$order->status = 'pending';
$order->error_message = '';
$provider = 'stripe_' . (string) $order->payment_method;
CloudInvoicePayment::where('provider', $provider)
->where('provider_order_no', $orderNo)
->whereIn('status', [
'creating', 'creation_unknown', 'not_created',
])->update(['status' => 'pending', 'updated_at' => $now]);
} else {
$result['duplicate'] = (string) $order->status === 'paid';
}
$order->updated_at = $now;
$order->save();
$webhook->processed_at = $now;
$webhook->save();
}, 3);
return $result;
}
protected function gatewayClient(array $settings): StripeClient
{
return new StripeClient($settings);
}
private function bindSession(string $orderNo, array $session)
{
$sessionId = trim((string) ($session['checkout_session_id'] ?? ''));
$url = trim((string) ($session['checkout_url'] ?? ''));
if (!preg_match('/^cs_(?:test|live)_[A-Za-z0-9]+$/D', $sessionId)
|| $url === '') {
throw new \RuntimeException('Stripe Checkout 支付信息无效');
}
$order = null;
(new StripeOrder())->getConnection()->transaction(function () use (
$orderNo,
$sessionId,
$url,
&$order
): void {
$order = StripeOrder::where('order_no', $orderNo)
->lockForUpdate()->first();
if ($order === null) {
throw new \RuntimeException('Stripe 本地订单不存在');
}
if (StripeOrder::where('checkout_session_id', $sessionId)
->where('order_no', '<>', $orderNo)->exists()) {
throw new \RuntimeException('Stripe Checkout 会话已绑定其他订单');
}
if ((string) $order->checkout_session_id !== ''
&& (string) $order->checkout_session_id !== $sessionId) {
throw new \RuntimeException('Stripe Checkout 会话不匹配');
}
if (!in_array((string) $order->status,
['creating', 'pending', 'paid'], true)) {
throw new \RuntimeException('Stripe 本地订单状态无效');
}
$order->checkout_session_id = $sessionId;
$order->checkout_url = $url;
if ((string) $order->status === 'creating') {
$order->status = 'pending';
}
$order->updated_at = time();
$order->save();
}, 3);
return $order;
}
private function assertSessionMatches(StripeOrder $order, array $event,
array $session, string $sessionId): void
{
if ((string) $order->checkout_session_id !== ''
&& (string) $order->checkout_session_id !== $sessionId) {
throw new \RuntimeException('Stripe Checkout 会话不匹配');
}
if ($this->amountCents((string) $order->amount)
!== (int) ($session['amount_total'] ?? -1)) {
throw new \RuntimeException('Stripe 回调金额不匹配');
}
if (strtolower((string) ($session['currency'] ?? ''))
!== StripeConfig::CURRENCY) {
throw new \RuntimeException('Stripe 回调币种不匹配');
}
if ((string) ($session['mode'] ?? '') !== 'payment') {
throw new \RuntimeException('Stripe Checkout 模式不匹配');
}
if ((int) $order->livemode !== (!empty($event['livemode']) ? 1 : 0)) {
throw new \RuntimeException('Stripe 回调环境不匹配');
}
$methods = is_array($session['payment_method_types'] ?? null)
? $session['payment_method_types'] : [];
if (!in_array((string) $order->payment_method, $methods, true)) {
throw new \RuntimeException('Stripe 回调支付方式不匹配');
}
$reference = trim((string) ($session['client_reference_id'] ?? ''));
if ($reference !== '' && $reference !== (string) $order->order_no) {
throw new \RuntimeException('Stripe 客户端引用不匹配');
}
}
private function validateAmount($rawAmount, array $settings): string
{
$rawAmount = trim((string) $rawAmount);
if (!preg_match('/^\d{1,10}(?:\.\d{1,2})?$/D', $rawAmount)) {
throw new \InvalidArgumentException(
'充值金额格式无效,最多保留两位小数'
);
}
$amount = PaymentAmount::normalize($rawAmount);
if ((float) $amount < (float) $settings['stripe_min_amount']
|| (float) $amount > (float) $settings['stripe_max_amount']) {
throw new \InvalidArgumentException(
'充值金额必须在 $' . $settings['stripe_min_amount']
. ' 到 $' . $settings['stripe_max_amount'] . ' 之间'
);
}
return $amount;
}
private function amountCents(string $amount): int
{
$normalized = PaymentAmount::normalize($amount);
[$whole, $fraction] = array_pad(explode('.', $normalized, 2), 2, '00');
return ((int) $whole * 100) + (int) str_pad($fraction, 2, '0');
}
private function orderNo(): string
{
return 'ST' . date('YmdHis') . strtoupper(bin2hex(random_bytes(8)));
}
}