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/Cloud/CloudInvoicePaymentService.php

631 lines
30 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\CloudInvoicePayment;
use App\Models\CloudInstance;
use App\Models\CloudOrder;
use App\Models\PaytaroOrder;
use App\Models\StripeOrder;
use App\Models\UsdtPaymentOrder;
use App\Models\User;
use App\Models\YipayOrder;
use App\Services\Config;
use App\Services\Payment\PaytaroConfig;
use App\Services\Payment\PaytaroPaymentService;
use App\Services\Payment\StripeConfig;
use App\Services\Payment\StripePaymentService;
use App\Services\Payment\UsdtConfig;
use App\Services\Payment\UsdtPaymentService;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\YipayPaymentService;
final class CloudInvoicePaymentService
{
/** Queue one provider-order creation attempt; execution never retries. */
public static function enqueue(CloudInvoice $invoice, User $user,
array $input, string $clientIp, string $userAgent): \App\Models\CloudJob
{
CloudInput::only($input, ['method', 'idempotency_key']);
self::assertInvoicePaymentAllowed($user);
$sourcePurpose = self::paymentPurpose($invoice);
$method = strtolower(trim((string) ($input['method'] ?? '')));
if (!in_array($method, array_column(self::methods($user), 'id'), true)) {
throw new CloudError('所选在线支付方式不可用', 409);
}
$key = trim((string) ($input['idempotency_key'] ?? ''));
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
throw new CloudError('支付请求标识无效', 400);
}
$fingerprint = hash('sha256', json_encode([
'invoice_id' => (int) $invoice->id,
'method' => $method,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES));
return $invoice->getConnection()->transaction(function () use (
$invoice, $user, $clientIp, $userAgent, $method, $key,
$fingerprint, $sourcePurpose
) {
$instance = $sourcePurpose === 'renewal'
? CloudInstance::where('id', (int) $invoice->instance_id)
->where('user_id', (int) $user->id)
->lockForUpdate()->first()
: null;
$locked = CloudInvoice::where('id', (int) $invoice->id)
->where('user_id', (int) $user->id)->lockForUpdate()->first();
if ($locked === null) {
throw new CloudError('账单不存在', 404);
}
if (self::paymentPurpose($locked) !== $sourcePurpose) {
throw new CloudError('账单类型已变更,请刷新后重试', 409);
}
$prior = \App\Models\CloudJob::where('user_id', (int) $user->id)
->where('request_idempotency_key', $key)
->lockForUpdate()->first();
if ($prior !== null) {
if (!hash_equals((string) $prior->request_fingerprint,
$fingerprint)) {
throw new CloudError('同一支付请求标识不能用于其他请求', 409);
}
CloudInvoicePayment::where('invoice_id', (int) $locked->id)
->where('user_id', (int) $user->id)
->where('idempotency_key', $key)
->whereIn('status', [
'creating', 'pending', 'creation_unknown',
])->update(['updated_at' => time()]);
return $prior;
}
if (!in_array((string) $locked->status,
['open', 'overdue'], true)) {
throw new CloudError('账单已结清或不可支付', 409);
}
if ($sourcePurpose === 'renewal'
&& ($instance === null
|| CloudInvoiceService::instanceDeleting($instance)
|| CloudInvoiceService::paymentDeadlinePassed($locked))) {
throw new CloudError('续费账单已失效,请刷新后重试', 409);
}
if ($instance !== null
&& CloudJobService::blockingQueryForInstance(
(int) $instance->id
)->where('kind', 'instance_upgrade')->exists()) {
throw new CloudError(
'实例正在升级或等待核对,续费账单暂不可支付',
409
);
}
$sameMethodJob = CloudJobService::blockingQueryForInvoice(
(int) $locked->id
)->where('user_id', (int) $user->id)
->where('request_fingerprint', $fingerprint)
->orderByDesc('id')->lockForUpdate()->first();
if ($sameMethodJob !== null) {
CloudInvoicePayment::where('invoice_id', (int) $locked->id)
->where('user_id', (int) $user->id)
->where('idempotency_key',
(string) $sameMethodJob->request_idempotency_key)
->whereIn('status', [
'creating', 'pending', 'creation_unknown',
])->update(['updated_at' => time()]);
return $sameMethodJob;
}
$sameMethodPayment = CloudInvoicePayment::where(
'invoice_id', (int) $locked->id
)->where('user_id', (int) $user->id)
->where('provider', $method)
->whereIn('status',
['creating', 'pending', 'creation_unknown'])
->orderByDesc('updated_at')->orderByDesc('id')
->lockForUpdate()->first();
if ($sameMethodPayment !== null) {
$sameMethodPayment->updated_at = time();
$sameMethodPayment->save();
$sameMethodPaymentJob = \App\Models\CloudJob::where(
'invoice_id', (int) $locked->id
)->where('user_id', (int) $user->id)
->where('kind', 'payment_create')
->where('request_idempotency_key',
(string) $sameMethodPayment->idempotency_key)
->orderByDesc('id')->lockForUpdate()->first();
if ($sameMethodPaymentJob !== null) {
return $sameMethodPaymentJob;
}
throw new CloudError('该支付方式已有未完成订单,请刷新后继续', 409);
}
$job = new \App\Models\CloudJob();
$job->invoice_id = $locked->id;
$job->user_id = $user->id;
$job->host_id = null;
$job->kind = 'payment_create';
$job->execution_mode = 'local';
$job->request_idempotency_key = $key;
$job->request_fingerprint = $fingerprint;
$job->sealed_payload = CloudSecrets::encrypt([
'input' => ['method' => $method,
'idempotency_key' => $key],
'client_ip' => mb_substr($clientIp, 0, 64),
'user_agent' => mb_substr($userAgent, 0, 500),
], 'job-payload');
$job->available_at = time();
$job->created_at = $job->updated_at = time();
$job->save();
return $job;
}, 3);
}
private static function paymentPurpose(CloudInvoice $invoice): string
{
$purpose = (string) ($invoice->purpose ?: 'renewal');
if (!in_array($purpose, ['provision', 'renewal'], true)) {
throw new CloudError('该账单不支持再次支付', 409);
}
return $purpose;
}
/**
* Recheck the account at the final, row-locked provider-order boundary.
*
* The controller performs the same validation for a useful early error,
* but an administrator can disable the account before the payment
* provider's transaction begins. Each provider calls this method after it
* locks the user row so a disabled account cannot still receive a real
* external payment order through that race window.
*/
public static function assertInvoicePaymentAllowed(User $user): void
{
if ((int) $user->enable !== 1) {
throw new CloudError('账户不存在或不可用', 403);
}
}
public static function methods(User $user): array
{
$methods = [];
foreach (YipayConfig::visibleMethods($user) as $method) {
$methods[] = ['id' => 'yipay_' . $method,
'name' => $method === 'wxpay' ? '易支付 · 微信' : '易支付 · 支付宝'];
}
if (PaytaroConfig::isUserVisible($user)) {
$methods[] = ['id' => 'paytaro', 'name' => 'Paytaro · 支付宝'];
}
foreach (StripeConfig::visibleMethods($user) as $method) {
$methods[] = [
'id' => 'stripe_' . $method,
'name' => $method === 'alipay'
? 'Stripe · 支付宝' : 'Stripe · 银行卡',
];
}
if (UsdtConfig::isUserVisible($user)) {
$methods[] = ['id' => 'usdt', 'name' => 'USDT-TRC20'];
}
return $methods;
}
public static function create(CloudInvoice $invoice, User $user, array $input,
string $clientIp, string $userAgent): array
{
CloudInput::only($input, ['method', 'idempotency_key']);
$sourcePurpose = self::paymentPurpose($invoice);
$validated = (new CloudInstance())->getConnection()->transaction(
function () use ($invoice, $user, $sourcePurpose) {
$lockedUser = User::where('id', $user->id)->lockForUpdate()->first();
if ($lockedUser === null || (int) $lockedUser->enable !== 1) {
return ['error' => '账户不存在或不可用', 'status' => 403];
}
if ($sourcePurpose === 'provision') {
$current = CloudInvoice::where('id', $invoice->id)
->where('user_id', $user->id)->lockForUpdate()->first();
if ($current === null) {
return ['error' => '账单不存在', 'status' => 404];
}
if (self::paymentPurpose($current) !== $sourcePurpose) {
return ['error' => '账单类型已变更,请刷新后重试',
'status' => 409];
}
$order = CloudOrder::where('id', $current->order_id)
->where('user_id', $user->id)->lockForUpdate()->first();
if (!in_array((string) $current->status, ['open', 'overdue'], true)
|| self::provisionUnavailable($current, $order)) {
return ['error' => '账单已失效,请重新提交开通请求',
'status' => 409];
}
return ['invoice' => $current];
}
// Lock in the same instance -> invoice order as lifecycle. If
// the three-day cutoff wins, no new provider order is opened;
// if payment validation wins, final settlement still rechecks
// the cutoff before consuming credited wallet funds.
$instance = CloudInstance::where('id', $invoice->instance_id)
->where('user_id', $user->id)->lockForUpdate()->first();
$current = CloudInvoice::where('id', $invoice->id)
->where('user_id', $user->id)->lockForUpdate()->first();
if ($current === null) {
return ['error' => '账单不存在', 'status' => 404];
}
if (self::paymentPurpose($current) !== $sourcePurpose) {
return ['error' => '账单类型已变更,请刷新后重试',
'status' => 409];
}
if (!in_array((string) $current->status, ['open', 'overdue'], true)) {
return ['error' => '账单已结清或不可支付', 'status' => 409];
}
if ($instance !== null
&& CloudJobService::blockingQueryForInstance(
(int) $instance->id
)->where('kind', 'instance_upgrade')->exists()) {
return ['error' => '实例正在升级或等待核对,续费账单暂不可支付',
'status' => 409];
}
if ($instance === null || CloudInvoiceService::instanceDeleting($instance)
|| CloudInvoiceService::paymentDeadlinePassed($current)) {
$current->status = 'expired';
$current->updated_at = time();
$current->save();
return ['error' => '账单已超过支付宽限期,实例正在删除',
'status' => 409];
}
if ($instance->expires_at === null
|| (int) $instance->expires_at !== (int) $current->renews_expires_at
|| $instance->renewal_price === null
|| !CloudInvoiceService::renewalInvoiceMatches(
$instance,
$current
)
|| (int) $instance->renewal_days !== (int) $current->validity_days
|| (int) $instance->renewal_traffic_bytes
!== (int) $current->traffic_quota_bytes) {
$current->status = 'void';
$current->updated_at = time();
$current->save();
return ['error' => '账单已失效,请刷新账单列表',
'status' => 409];
}
return ['invoice' => $current];
}, 3);
if (isset($validated['error'])) {
throw new CloudError($validated['error'], (int) $validated['status']);
}
$invoice = $validated['invoice'];
$method = strtolower(trim((string) ($input['method'] ?? '')));
$allowed = array_column(self::methods($user), 'id');
if (!in_array($method, $allowed, true)) {
throw new CloudError('所选在线支付方式不可用', 409);
}
$idempotency = trim((string) ($input['idempotency_key'] ?? ''));
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new CloudError('支付请求标识无效');
}
$existing = CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($existing !== null) {
if ((int) $existing->invoice_id !== (int) $invoice->id
|| (string) $existing->provider !== $method) {
throw new CloudError('同一支付请求标识不能用于其他账单或渠道', 409);
}
if (in_array((string) $existing->status,
['creating', 'creation_unknown'], true)) {
throw new CloudError('支付订单创建结果不明,不能自动重试', 409);
}
if ((string) $existing->status === 'not_created') {
throw new CloudError(
'上次支付订单创建失败,请使用新的请求标识重新发起支付',
409
);
}
return self::display($existing);
}
$baseUrl = rtrim((string) Config::get('baseUrl', ''), '/');
if (filter_var($baseUrl, FILTER_VALIDATE_URL) === false
|| preg_match('#^https://#i', $baseUrl) !== 1) {
throw new CloudError('站点 HTTPS 地址未正确配置,不能创建在线支付', 409);
}
$context = ['invoice_id' => (int) $invoice->id,
'idempotency_key' => $idempotency, 'provider' => $method];
try {
if (str_starts_with($method, 'yipay_')) {
$order = (new YipayPaymentService())->createOrder($user, (string) $invoice->amount,
substr($method, 6), $clientIp, $userAgent, $baseUrl, $context);
} elseif ($method === 'paytaro') {
$order = (new PaytaroPaymentService())->createOrder($user, (string) $invoice->amount,
$clientIp, $userAgent, $baseUrl, $context);
} elseif (str_starts_with($method, 'stripe_')) {
$order = (new StripePaymentService())->createOrder(
$user,
(string) $invoice->amount,
substr($method, 7),
$clientIp,
$userAgent,
$baseUrl,
$context
);
} else {
$order = (new UsdtPaymentService())->createInvoiceOrder(
$user, (string) $invoice->amount, $context);
}
CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->where('status', 'creating')
->update(['status' => 'pending', 'updated_at' => time()]);
} catch (\Throwable $error) {
// A concurrent request with the same idempotency key may have won
// the unique insert. Never mutate that request's attempt here.
$winner = CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($winner !== null) {
if ((int) $winner->invoice_id !== (int) $invoice->id
|| (string) $winner->provider !== $method) {
throw new CloudError('同一支付请求标识不能用于其他账单或渠道', 409);
}
if (!in_array((string) $winner->status,
['creating', 'creation_unknown', 'not_created'], true)) {
return self::display($winner);
}
if (in_array((string) $winner->status,
['creating', 'creation_unknown'], true)) {
throw new CloudError('支付订单创建结果不明,不能自动重试', 409);
}
}
throw $error;
}
$payment = CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($payment === null) {
throw new \RuntimeException('在线支付关联记录创建失败');
}
return self::display($payment);
}
private static function provisionUnavailable(CloudInvoice $invoice,
?CloudOrder $order): bool
{
return $order === null
|| (string) $order->status !== 'awaiting_payment'
|| CloudInvoiceService::paymentDeadlinePassed($invoice)
|| (int) $order->plan_id !== (int) $invoice->plan_id
|| CloudMoney::cents((string) $order->amount)
!== CloudMoney::cents((string) $invoice->amount);
}
public static function recordAttempt(array $context, string $orderNo, string $amount,
int $userId, int $now): void
{
if ($context === []) {
return;
}
$provider = (string) ($context['provider'] ?? '');
$idempotency = (string) ($context['idempotency_key'] ?? '');
$invoiceId = (int) ($context['invoice_id'] ?? 0);
if ($invoiceId < 1 || !in_array($provider,
['yipay_alipay', 'yipay_wxpay', 'paytaro', 'stripe_card',
'stripe_alipay', 'usdt'], true)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new \RuntimeException('账单支付上下文无效');
}
// The gateway services call this inside the same transaction that
// persists their local order, immediately before any remote request.
// Re-lock the billing state here so lifecycle cannot cross the grace
// cutoff between the controller's early validation and creation of a
// real provider order.
$source = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->first();
if ($source === null) {
throw new CloudError('账单不存在', 404);
}
$sourcePurpose = self::paymentPurpose($source);
if ($sourcePurpose === 'provision') {
$invoice = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->lockForUpdate()->first();
$order = $invoice === null ? null : CloudOrder::where('id', $invoice->order_id)
->where('user_id', $userId)->lockForUpdate()->first();
if ($invoice === null || !in_array((string) $invoice->status,
['open', 'overdue'], true)) {
throw new CloudError('账单已结清或不可支付', 409);
}
if (self::paymentPurpose($invoice) !== $sourcePurpose) {
throw new CloudError('账单类型已变更,请刷新后重试', 409);
}
if (self::provisionUnavailable($invoice, $order)) {
throw new CloudError('账单已失效,请重新提交开通请求', 409);
}
self::saveAttempt($invoiceId, $provider, $orderNo, $idempotency,
$amount, $userId, $now);
return;
}
$instance = CloudInstance::where('id', (int) $source->instance_id)
->where('user_id', $userId)->lockForUpdate()->first();
$invoice = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->lockForUpdate()->first();
if ($invoice === null || !in_array((string) $invoice->status,
['open', 'overdue'], true)) {
throw new CloudError('账单已结清或不可支付', 409);
}
if (self::paymentPurpose($invoice) !== $sourcePurpose) {
throw new CloudError('账单类型已变更,请刷新后重试', 409);
}
if ($instance !== null
&& CloudJobService::blockingQueryForInstance(
(int) $instance->id
)->where('kind', 'instance_upgrade')->exists()) {
throw new CloudError(
'实例正在升级或等待核对,续费账单暂不可支付',
409
);
}
if ($instance === null || CloudInvoiceService::instanceDeleting($instance)
|| CloudInvoiceService::paymentDeadlinePassed($invoice)
|| $instance->expires_at === null
|| (int) $instance->expires_at !== (int) $invoice->renews_expires_at
|| $instance->renewal_price === null
|| !CloudInvoiceService::renewalInvoiceMatches(
$instance,
$invoice
)
|| (int) $instance->renewal_days !== (int) $invoice->validity_days
|| (int) $instance->renewal_traffic_bytes
!== (int) $invoice->traffic_quota_bytes) {
throw new CloudError('账单已失效,请刷新账单列表', 409);
}
self::saveAttempt($invoiceId, $provider, $orderNo, $idempotency,
$amount, $userId, $now);
}
private static function saveAttempt(int $invoiceId, string $provider,
string $orderNo, string $idempotency, string $amount, int $userId,
int $now): void
{
// The invoice row is already locked by recordAttempt(). Keep at most
// one unfinished order per provider, while allowing the customer to
// switch to another provider before either order is paid.
if (CloudInvoicePayment::where('invoice_id', $invoiceId)
->where('idempotency_key', '<>', $idempotency)
->where('provider', $provider)
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
->lockForUpdate()->exists()) {
throw new CloudError(
'该支付方式已有未完成订单,请继续原订单或选择其他方式',
409
);
}
$payment = new CloudInvoicePayment();
$payment->invoice_id = $invoiceId;
$payment->user_id = $userId;
$payment->provider = $provider;
$payment->provider_order_no = $orderNo;
$payment->idempotency_key = $idempotency;
$payment->amount = $amount;
$payment->status = 'creating';
$payment->created_at = $payment->updated_at = $now;
$payment->save();
}
/** Synchronize a provider terminal result without touching settled money. */
public static function markProviderOrdersTerminal(string $provider,
array $orderNumbers, string $status, ?int $now = null): int
{
$provider = trim($provider);
$orderNumbers = array_values(array_unique(array_filter(array_map(
static fn ($value): string => trim((string) $value),
$orderNumbers
), static fn (string $value): bool => $value !== '')));
if ($provider === '' || $orderNumbers === []
|| !in_array($status, ['failed', 'expired'], true)) {
return 0;
}
$now ??= time();
$payments = CloudInvoicePayment::where('provider', $provider)
->whereIn('provider_order_no', $orderNumbers)
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
->orderBy('id')->lockForUpdate()->get();
if ($payments->isEmpty()) {
return 0;
}
CloudInvoicePayment::whereIn('id', $payments->pluck('id')->all())
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
->update(['status' => $status, 'updated_at' => $now]);
foreach ($payments as $payment) {
self::resolveUnknownCreationFromProviderEvidence(
$payment,
'渠道终态证明原支付订单已创建',
$now
);
}
return $payments->count();
}
public static function settleForProvider(string $provider, string $orderNo): ?string
{
$payment = CloudInvoicePayment::where('provider', $provider)
->where('provider_order_no', $orderNo)->lockForUpdate()->first();
if ($payment === null) {
return null;
}
if (in_array((string) $payment->status, ['paid_invoice', 'credited_balance'], true)) {
return (string) $payment->status;
}
$status = CloudInvoiceService::settleCreditedPayment($payment);
self::resolveUnknownCreationFromProviderEvidence($payment);
return $status;
}
/** A signed provider callback is authoritative proof that creation applied. */
private static function resolveUnknownCreationFromProviderEvidence(
CloudInvoicePayment $payment,
string $reason = '经签名支付回调确认原订单已由渠道接受',
?int $now = null
): void {
$now ??= time();
\App\Models\CloudJob::where('kind', 'payment_create')
->where('execution_mode', 'local')
->where('invoice_id', (int) $payment->invoice_id)
->where('user_id', (int) $payment->user_id)
->where('request_idempotency_key',
(string) $payment->idempotency_key)
->where('phase', 'terminal')->where('outcome', 'failed')
->where('effect_may_have_applied', 1)
->where('effect_resolution', 'unknown')->update([
'effect_resolution' => 'applied',
'effect_resolved_at' => $now,
'effect_resolved_by' => null,
'effect_resolution_reason' => $reason,
'updated_at' => $now,
]);
}
public static function display(CloudInvoicePayment $payment): array
{
$provider = (string) $payment->provider;
$result = [
'id' => (string) $payment->id,
'invoice_id' => (string) $payment->invoice_id,
'method' => $provider,
'status' => (string) $payment->status,
'amount' => (string) $payment->amount,
'poll_url' => '/api/v1/invoices/' . (int) $payment->invoice_id,
];
if (str_starts_with($provider, 'yipay_')) {
$order = YipayOrder::where('order_no', $payment->provider_order_no)
->where('user_id', (int) $payment->user_id)->first();
if ($order === null) {
throw new CloudError('在线支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => (string) $order->payment_kind,
'payment_value' => (string) $order->payment_value,
'label' => $provider === 'yipay_wxpay'
? '易支付 · 微信' : '易支付 · 支付宝']);
}
if ($provider === 'paytaro') {
$order = PaytaroOrder::where('order_no', $payment->provider_order_no)
->where('user_id', (int) $payment->user_id)->first();
if ($order === null) {
throw new CloudError('在线支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => (string) $order->payment_kind,
'payment_value' => (string) $order->payment_value,
'label' => 'Paytaro · 支付宝']);
}
if (str_starts_with($provider, 'stripe_')) {
$order = StripeOrder::where('order_no',
$payment->provider_order_no)
->where('user_id', (int) $payment->user_id)->first();
if ($order === null) {
throw new CloudError('Stripe 支付订单不存在', 404);
}
return array_merge($result, [
'payment_kind' => 'payurl',
'payment_value' => (string) $order->checkout_url,
'label' => $provider === 'stripe_alipay'
? 'Stripe · 支付宝' : 'Stripe · 银行卡',
]);
}
$order = UsdtPaymentOrder::where('order_no', $payment->provider_order_no)
->where('user_id', (int) $payment->user_id)->first();
if ($order === null) {
throw new CloudError('USDT 支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => 'usdt', 'label' => 'USDT-TRC20',
'actual_amount' => (string) $order->actual_amount,
'receive_address' => (string) $order->receive_address,
'expires_at' => (int) $order->expires_at]);
}
}