fix(payment): separate Yipay charges from USD credits

go
codex 1 day ago
parent 8fc0057ae0
commit c6557c0cd1

@ -108,6 +108,9 @@ class YipayController extends AdminController
throw new \InvalidArgumentException('易支付商户密钥长度不能超过 256 个字符');
}
if ($values['yipay_enabled'] === 'true') {
if ($values['yipay_cny_confirmed'] !== 'true') {
throw new \InvalidArgumentException('启用前请确认易支付商户以人民币收款');
}
if ($values['yipay_alipay_enabled'] !== 'true' && $values['yipay_wxpay_enabled'] !== 'true') {
throw new \InvalidArgumentException('启用易支付前至少选择一种支付方式');
}
@ -158,7 +161,8 @@ class YipayController extends AdminController
try {
$admin = Auth::getUser();
$result = (new YipayPaymentService())->refundById($request->getParam('record_id'), (int) $admin->id);
return $this->json($response, 1, '退款成功,已退回 ¥' . $result['amount'] . ' 并同步扣回用户余额');
return $this->json($response, 1, '退款成功,已退回 ' . $result['gateway_amount'] . ' '
. $result['gateway_currency'] . ',已扣回 ' . $result['amount'] . ' USD 余额');
} catch (\InvalidArgumentException $exception) {
return $this->json($response, 0, $exception->getMessage(), 422);
} catch (\Throwable $exception) {
@ -206,6 +210,9 @@ class YipayController extends AdminController
'yipay_order_name' => $name,
'yipay_min_amount' => $minimum,
'yipay_max_amount' => $maximum,
'yipay_cny_confirmed' => YipayConfig::truthy($payload['yipay_cny_confirmed'] ?? false) ? 'true' : 'false',
'yipay_quote_minutes' => (string) max(5, min(1440, (int) ($payload['yipay_quote_minutes']
?? $current['yipay_quote_minutes']))),
'yipay_request_timeout_seconds' => (string) max(3, min(60, (int) ($payload['yipay_request_timeout_seconds'] ?? 15))),
];
}

@ -20,6 +20,8 @@ class YipayConfig
'yipay_order_name' => '账户余额充值',
'yipay_min_amount' => '1.00',
'yipay_max_amount' => '10000.00',
'yipay_cny_confirmed' => 'false',
'yipay_quote_minutes' => '30',
'yipay_request_timeout_seconds' => '15',
];
@ -50,6 +52,8 @@ class YipayConfig
}
$values['yipay_min_amount'] = PaymentAmount::normalize($values['yipay_min_amount']);
$values['yipay_max_amount'] = PaymentAmount::normalize($values['yipay_max_amount']);
$values['yipay_cny_confirmed'] = self::truthy($values['yipay_cny_confirmed']);
$values['yipay_quote_minutes'] = max(5, min(1440, (int) $values['yipay_quote_minutes']));
$values['yipay_request_timeout_seconds'] = max(3, min(60, (int) $values['yipay_request_timeout_seconds']));
return $values;
}
@ -74,6 +78,9 @@ class YipayConfig
public static function runtimeForUser($user, $method)
{
$values = self::runtime(true);
if (!$values['yipay_cny_confirmed']) {
throw new \InvalidArgumentException('请先核实易支付商户以人民币收款');
}
if (!self::canUserAccess($user, $values)) {
throw new \RuntimeException('易支付当前处于测试模式,仅管理员可用');
}
@ -119,7 +126,7 @@ class YipayConfig
public static function visibleMethods($user = null, ?array $values = null)
{
$values = $values === null ? self::values() : $values;
if (!self::canUserAccess($user, $values)) {
if (!self::canUserAccess($user, $values) || !self::truthy($values['yipay_cny_confirmed'] ?? false)) {
return [];
}
$methods = [];

@ -3,14 +3,12 @@
namespace App\Services\Payment;
use App\Models\CloudInvoicePayment;
use App\Models\Code;
use App\Models\Paylist;
use App\Models\Payback;
use App\Models\User;
use App\Models\YipayCallbackEvent;
use App\Models\YipayOrder;
use App\Models\YipayRefund;
use App\Services\Cloud\CloudInvoicePaymentService;
use App\Services\Cloud\CloudMoney;
class YipayPaymentService
{
@ -24,13 +22,15 @@ class YipayPaymentService
$amount = $this->validateAmount($rawAmount, $settings);
$orderNo = $this->orderNo();
$now = time();
$quote = PaymentCheckoutQuotes::prepare('yipay_' . $method, $amount, $now,
$now + (int) $settings['yipay_quote_minutes'] * 60);
if (YipayOrder::where('user_id', (int) $user->id)->where('created_at', '>=', $now - 60)->count() >= 5) {
throw new \RuntimeException('易支付下单过于频繁,请稍后重试');
}
$connection = (new YipayOrder())->getConnection();
$connection->transaction(function () use (
$user, $amount, $method, $orderNo, $now, $businessContext
$user, $amount, $method, $orderNo, $now, $businessContext, $quote
) {
$lockedUser = User::where('id', (int) $user->id)->lockForUpdate()->first();
if ($lockedUser === null) {
@ -57,6 +57,7 @@ class YipayPaymentService
$order->created_at = $now;
$order->updated_at = $now;
$order->save();
PaymentCheckoutQuotes::persist($quote, $orderNo, (int) $user->id);
CloudInvoicePaymentService::recordAttempt(
$businessContext, $orderNo, $amount, (int) $user->id, $now
@ -71,7 +72,7 @@ class YipayPaymentService
'notify_url' => $baseUrl . '/yipay/callback',
'return_url' => rtrim((string) $returnBaseUrl, '/') . '/yipay/return',
'name' => (string) $settings['yipay_order_name'],
'money' => $amount,
'money' => PaymentCheckoutQuotes::formatUnits('CNY', $quote->expected_units),
'clientip' => $this->normalizeIp($clientIp),
'device' => $this->device((string) $userAgent),
];
@ -120,9 +121,13 @@ class YipayPaymentService
$now = time();
$credited = false;
$duplicate = false;
$review = false;
$units = CloudMoney::cents(PaymentAmount::normalize($payload['money']));
$connection = (new YipayOrder())->getConnection();
$connection->transaction(function () use ($payload, $orderNo, $tradeNo, $eventKey, $now, &$credited, &$duplicate) {
$connection->transaction(function () use (
$payload, $orderNo, $tradeNo, $eventKey, $now, $units, &$credited, &$duplicate, &$review
) {
$order = YipayOrder::where('order_no', $orderNo)->lockForUpdate()->first();
if ($order === null) {
throw new \RuntimeException('易支付本地订单不存在');
@ -130,9 +135,6 @@ class YipayPaymentService
if ((string) $order->payment_type !== (string) $payload['type']) {
throw new \RuntimeException('易支付回调支付方式不匹配');
}
if (PaymentAmount::normalize($payload['money']) !== PaymentAmount::normalize($order->amount)) {
throw new \RuntimeException('易支付回调金额不匹配');
}
if ((string) $order->gateway_trade_no !== '' && (string) $order->gateway_trade_no !== $tradeNo) {
throw new \RuntimeException('易支付平台订单号不匹配');
}
@ -144,19 +146,29 @@ class YipayPaymentService
throw new \RuntimeException('易支付平台订单号已绑定其他订单');
}
if ((string) $order->status === 'refunded') {
$invoiceProvider = 'yipay_' . (string) $order->payment_type;
if (in_array((string) $order->status, ['paid', 'refunded'], true)) {
$received = PaymentCheckoutQuotes::find($invoiceProvider, $orderNo)?->received_units
?? CloudMoney::cents((string) $order->amount);
if ($received !== $units) {
throw new \RuntimeException('易支付已支付金额与回调不一致');
}
$duplicate = true;
return;
}
$existing = YipayCallbackEvent::where('event_key', $eventKey)->first();
if ($existing !== null) {
if ((string) $order->status !== 'paid' || (int) $existing->processed_at <= 0) {
if ((int) $existing->processed_at <= 0) {
throw new \RuntimeException('易支付重复回调事件状态异常');
}
$review = PaymentCheckoutQuotes::find($invoiceProvider, $orderNo)?->status === 'review';
$duplicate = true;
return;
}
if (!in_array((string) $order->status, ['creating', 'pending', 'creation_unknown', 'not_created'], true)) {
throw new \RuntimeException('易支付本地订单状态无效');
}
$event = new YipayCallbackEvent();
$event->event_key = $eventKey;
@ -169,13 +181,29 @@ class YipayPaymentService
$event->processed_at = 0;
$event->save();
$quote = PaymentCheckoutQuotes::receive($invoiceProvider, $orderNo, (int) $order->user_id,
(string) $order->amount, CloudMoney::cents((string) $order->amount), $units, $tradeNo, $now,
null, strtoupper(trim((string) ($payload['currency'] ?? 'CNY'))));
if ($quote->status === 'review') {
$review = true;
$order->gateway_trade_no = $tradeNo;
$order->status = 'pending';
$order->payment_value = null;
$order->error_message = '收款凭证已保存,需人工核对';
$order->updated_at = $now;
$order->save();
$event->processed_at = $now;
$event->save();
CloudInvoicePaymentService::recordProviderReview($invoiceProvider, $orderNo, $now);
return;
}
$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('易支付关联充值订单无效');
}
$credited = RechargeCreditService::creditLocked($paylist, self::LEDGER_TYPE, true);
$invoiceProvider = 'yipay_' . (string) $order->payment_type;
$credited = RechargeCreditService::creditLocked($paylist, self::LEDGER_TYPE, true, $quote);
if (CloudInvoicePayment::where('provider', $invoiceProvider)
->where('provider_order_no', $orderNo)->exists()) {
CloudInvoicePaymentService::settleForProvider($invoiceProvider, $orderNo);
@ -191,7 +219,7 @@ class YipayPaymentService
$event->save();
}, 3);
return ['credited' => $credited, 'duplicate' => $duplicate, 'order_no' => $orderNo];
return ['credited' => $credited, 'duplicate' => $duplicate, 'review' => $review, 'order_no' => $orderNo];
}
public function validateReturn(array $payload)
@ -216,128 +244,8 @@ class YipayPaymentService
public function refund($rawOrderNo, $adminUserId)
{
$orderNo = trim((string) $rawOrderNo);
if (!preg_match('/^YP\d{14}[A-F0-9]{16}$/', $orderNo)) {
throw new \InvalidArgumentException('易支付商户订单号格式无效');
}
$adminUserId = (int) $adminUserId;
if ($adminUserId <= 0) {
throw new \RuntimeException('退款管理员身份无效');
}
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
->whereIn('provider', ['yipay_alipay', 'yipay_wxpay'])->exists()) {
throw new \RuntimeException('账单支付不支持自动退款,请人工核对服务期后处理');
}
$settings = YipayConfig::runtime(false);
$result = null;
$gatewaySucceeded = false;
$connection = (new YipayOrder())->getConnection();
try {
$connection->transaction(function () use ($orderNo, $adminUserId, $settings, &$result, &$gatewaySucceeded) {
$order = YipayOrder::where('order_no', $orderNo)->lockForUpdate()->first();
if ($order === null) {
throw new \RuntimeException('易支付订单不存在');
}
if ((string) $order->status === 'refunded') {
throw new \RuntimeException('该订单已经退款,不能重复操作');
}
if ((string) $order->status !== 'paid') {
throw new \RuntimeException('只有已支付订单可以退款');
}
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
->whereIn('provider', ['yipay_alipay', 'yipay_wxpay'])->exists()) {
throw new \RuntimeException('账单支付不支持自动退款,请人工核对服务期后处理');
}
$tradeNo = trim((string) $order->gateway_trade_no);
if (!preg_match('/^[A-Za-z0-9_-]{1,80}$/', $tradeNo)) {
throw new \RuntimeException('易支付平台订单号无效,不能退款');
}
if (YipayRefund::where('order_no', $orderNo)->exists()) {
throw new \RuntimeException('该订单已经存在退款记录,不能重复操作');
}
$paylist = Paylist::where('id', (int) $order->paylist_id)->lockForUpdate()->first();
if ($paylist === null || (int) $paylist->status !== 1 || (string) $paylist->tradeno !== $orderNo) {
throw new \RuntimeException('订单充值记录状态异常,已阻止退款');
}
$user = User::where('id', (int) $order->user_id)->lockForUpdate()->first();
if ($user === null) {
throw new \RuntimeException('充值用户不存在,已阻止退款');
}
$amount = PaymentAmount::normalize($order->amount);
$payback = $this->matchingReferral($order);
$gateway = $this->gatewayClient($settings)->refund($tradeNo, $orderNo, $amount);
$gatewaySucceeded = true;
$now = time();
$referralAmount = '0.00';
$user->money = round((float) $user->money - (float) $amount, 2);
$user->save();
$paylist->status = 2;
$paylist->save();
if ($payback !== null) {
$referralAmount = PaymentAmount::normalize($payback->ref_get);
$referrer = User::where('id', (int) $payback->ref_by)->lockForUpdate()->first();
if ($referrer !== null) {
$referrer->aff_money = round((float) $referrer->aff_money - (float) $referralAmount, 2);
$referrer->save();
$reversal = new Payback();
$reversal->total = 0 - (float) PaymentAmount::normalize($payback->total);
$reversal->userid = (int) $payback->userid;
$reversal->ref_by = (int) $payback->ref_by;
$reversal->ref_get = 0 - (float) $referralAmount;
$reversal->datetime = $now;
$reversal->save();
}
}
$ledger = new Code();
$ledger->code = 'YPR-' . $orderNo;
$ledger->isused = 1;
$ledger->type = -2;
$ledger->number = $amount;
$ledger->usedatetime = date('Y-m-d H:i:s', $now);
$ledger->userid = (int) $user->id;
$ledger->save();
$refund = new YipayRefund();
$refund->order_no = $orderNo;
$refund->gateway_trade_no = $tradeNo;
$refund->amount = $amount;
$refund->status = 'success';
$refund->gateway_message = mb_substr(trim((string) ($gateway['msg'] ?? '退款成功')), 0, 500);
$refund->admin_user_id = $adminUserId;
$refund->referral_reversal_amount = $referralAmount;
$refund->requested_at = $now;
$refund->completed_at = $now;
$refund->updated_at = $now;
$refund->save();
$order->status = 'refunded';
$order->error_message = '';
$order->updated_at = $now;
$order->save();
$result = [
'order_no' => $orderNo,
'amount' => $amount,
'referral_reversal_amount' => $referralAmount,
];
}, 1);
} catch (\Throwable $exception) {
if ($gatewaySucceeded) {
error_log('CRITICAL: Yipay gateway refund succeeded but local transaction failed for ' . $orderNo . ': ' . $exception->getMessage());
throw new \RuntimeException('易支付已接受退款,但本地记账失败,请立即人工核对订单 ' . $orderNo);
}
throw $exception;
}
return $result;
return YipayRefundService::execute(trim((string) $rawOrderNo), (int) $adminUserId,
fn (): callable => [$this->gatewayClient(YipayConfig::runtime(false)), 'refund']);
}
private function validateNotification(array $payload, array $settings)
@ -386,6 +294,10 @@ class YipayPaymentService
$connection = (new YipayOrder())->getConnection();
$connection->transaction(function () use ($orderNo, $tradeNo, $kind, $paymentValue, &$order) {
$order = YipayOrder::where('order_no', $orderNo)->lockForUpdate()->first();
if ($order !== null && (string) $order->gateway_trade_no === $tradeNo
&& PaymentCheckoutQuotes::find('yipay_' . $order->payment_type, $orderNo)?->receipt_ref !== null) {
return;
}
if ($order === null || (string) $order->status !== 'creating') {
throw new \RuntimeException('易支付本地订单状态无效');
}
@ -468,27 +380,4 @@ class YipayPaymentService
{
return new YipayClient($settings);
}
private function matchingReferral(YipayOrder $order)
{
if ((int) $order->paid_at <= 0) {
return null;
}
$query = Payback::where('userid', (int) $order->user_id)
->where('total', PaymentAmount::normalize($order->amount))
->where('ref_get', '>=', 0)
->whereBetween('datetime', [(int) $order->paid_at - 2, (int) $order->paid_at + 2])
->lockForUpdate();
$matches = $query->orderBy('id', 'desc')->get();
if ($matches->count() <= 1) {
return $matches->first();
}
$exact = $matches->filter(function ($payback) use ($order) {
return (int) $payback->datetime === (int) $order->paid_at;
});
if ($exact->count() === 1) {
return $exact->first();
}
throw new \RuntimeException('订单对应的邀请返利记录无法唯一识别,已阻止自动退款');
}
}

@ -0,0 +1,170 @@
<?php
namespace App\Services\Payment;
use App\Models\CloudInvoicePayment;
use App\Models\Code;
use App\Models\Payback;
use App\Models\Paylist;
use App\Models\User;
use App\Models\YipayOrder;
use App\Models\YipayRefund;
use App\Services\Cloud\CloudMoney;
use Brick\Math\BigDecimal;
final class YipayRefundService
{
public static function execute(string $orderNo, int $adminId, callable $gatewayFactory): array
{
if (preg_match('/^YP\d{14}[A-F0-9]{16}$/D', $orderNo) !== 1 || $adminId <= 0) {
throw new \InvalidArgumentException('易支付订单或退款管理员无效');
}
$connection = (new YipayOrder())->getConnection();
[$intent, $gateway] = $connection->transaction(static function () use ($orderNo, $adminId, $gatewayFactory): array {
[$order, $quote] = self::lockedPayment($orderNo);
$prior = YipayRefund::where('order_no', $orderNo)->lockForUpdate()->first();
if ($prior !== null) {
if ($prior->status === 'gateway_accepted') {
return [$prior, null];
}
throw new \RuntimeException('易支付已有退款凭证,请核对原订单');
}
$gateway = $gatewayFactory();
$intent = new YipayRefund();
$intent->order_no = $orderNo;
$intent->gateway_trade_no = $order->gateway_trade_no;
$intent->amount = CloudMoney::decimal($quote->credit_cents);
$intent->gateway_amount = PaymentCheckoutQuotes::formatUnits('CNY', $quote->received_units);
$intent->gateway_currency = 'CNY';
$intent->status = 'dispatching';
$intent->admin_user_id = $adminId;
$intent->completed_at = 0;
$intent->requested_at = $intent->updated_at = time();
$intent->save();
return [$intent, $gateway];
}, 3);
if ($gateway !== null) {
try {
$result = $gateway((string) $intent->gateway_trade_no,
$orderNo, self::decimal($intent->gateway_amount));
if (!is_array($result) || !in_array($result['code'] ?? null, [1, '1'], true)) {
throw new \RuntimeException('易支付未返回确认退款的回执');
}
} catch (\Throwable) {
YipayRefund::where('id', $intent->id)->where('status', 'dispatching')->update([
'status' => 'uncertain', 'gateway_message' => '退款结果待查证', 'updated_at' => time(),
]);
throw new \RuntimeException('易支付退款结果未知,请核对原商户流水');
}
if (YipayRefund::where('id', $intent->id)->where('status', 'dispatching')->update([
'status' => 'gateway_accepted', 'gateway_message' => '渠道已确认退款', 'updated_at' => time(),
]) !== 1) {
throw new \RuntimeException('易支付已接受退款,请核对原退款凭证');
}
}
try {
return $connection->transaction(static fn () => self::finalize($orderNo), 3);
} catch (\Throwable $exception) {
throw new \RuntimeException('渠道已确认退款,本地记账待完成,可继续核对原退款', 0, $exception);
}
}
private static function lockedPayment(string $orderNo): array
{
$order = YipayOrder::where('order_no', $orderNo)->lockForUpdate()->first();
if ($order === null || $order->status !== 'paid') {
throw new \RuntimeException('只有已支付且未退款的订单可以退款');
}
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
->whereIn('provider', ['yipay_alipay', 'yipay_wxpay'])->exists()) {
throw new \RuntimeException('账单支付不支持自动退款,请人工核对服务期后处理');
}
$trade = (string) $order->gateway_trade_no;
$quote = PaymentCheckoutQuotes::find('yipay_' . $order->payment_type, $orderNo, true);
$paylist = Paylist::where('id', (int) $order->paylist_id)->lockForUpdate()->first();
if ($quote?->status !== 'accepted' || $quote->asset !== 'CNY' || $quote->receipt_ref !== $trade
|| $quote->user_id !== (int) $order->user_id || $quote->received_units <= 0
|| preg_match('/^[A-Za-z0-9_-]{1,80}$/D', $trade) !== 1
|| $paylist === null || (int) $paylist->status !== 1 || (string) $paylist->tradeno !== $orderNo
|| (int) $paylist->userid !== (int) $order->user_id
|| CloudMoney::cents((string) $paylist->total) !== $quote->credit_cents) {
throw new \RuntimeException('订单缺少可核实的原币收款和 USD 入账记录,请人工核对');
}
$user = User::where('id', (int) $order->user_id)->lockForUpdate()->first();
if ($user === null) {
throw new \RuntimeException('充值用户不存在,已阻止退款');
}
$referral = $quote->referral_id === null ? null
: Payback::where('id', $quote->referral_id)->lockForUpdate()->first();
if ($quote->referral_id !== null && ($referral === null
|| (int) $referral->userid !== (int) $user->id
|| CloudMoney::cents((string) $referral->total) !== $quote->credit_cents)) {
throw new \RuntimeException('无法核实原充值返利,请人工核对');
}
return [$order, $quote, $paylist, $user, $referral];
}
private static function finalize(string $orderNo): array
{
[$order, $quote, $paylist, $user, $referral] = self::lockedPayment($orderNo);
$intent = YipayRefund::where('order_no', $orderNo)->lockForUpdate()->first();
$amount = CloudMoney::decimal($quote->credit_cents);
$gatewayAmount = PaymentCheckoutQuotes::formatUnits('CNY', $quote->received_units);
if ($intent?->status !== 'gateway_accepted' || $intent->gateway_trade_no !== $quote->receipt_ref
|| $intent->gateway_currency !== 'CNY' || self::decimal($intent->gateway_amount) !== $gatewayAmount
|| self::decimal($intent->amount) !== $amount) {
throw new \RuntimeException('退款凭证与原入账记录不一致');
}
$now = time();
$user->money = (string) BigDecimal::of((string) $user->money)->minus($amount)->toScale(2);
$user->save();
$paylist->status = 2;
$paylist->save();
$referralAmount = '0.00';
if ($referral !== null) {
$referrer = User::where('id', (int) $referral->ref_by)->lockForUpdate()->first();
if ($referrer !== null) {
$referralAmount = self::decimal($referral->ref_get);
$referrer->aff_money = (string) BigDecimal::of((string) $referrer->aff_money)
->minus($referralAmount)->toScale(2);
$referrer->save();
$reversal = new Payback();
$reversal->total = '-' . $amount;
$reversal->userid = (int) $user->id;
$reversal->ref_by = (int) $referrer->id;
$reversal->ref_get = '-' . $referralAmount;
$reversal->datetime = $now;
$reversal->save();
}
}
$ledger = new Code();
$ledger->code = 'YPR-' . $orderNo;
$ledger->isused = 1;
$ledger->type = -2;
$ledger->number = $amount;
$ledger->usedatetime = date('Y-m-d H:i:s', $now);
$ledger->userid = (int) $user->id;
$ledger->save();
$intent->status = 'success';
$intent->referral_reversal_amount = $referralAmount;
$intent->completed_at = $intent->updated_at = $now;
$intent->save();
$order->status = 'refunded';
$order->error_message = '';
$order->updated_at = $now;
$order->save();
return ['order_no' => $orderNo, 'amount' => $amount, 'gateway_amount' => $gatewayAmount,
'gateway_currency' => 'CNY', 'referral_reversal_amount' => $referralAmount];
}
private static function decimal($amount): string
{
return CloudMoney::decimal(CloudMoney::cents((string) $amount));
}
}

@ -106,6 +106,14 @@ class UserDataDeletionService
'用户仍有支付安全栅栏,请先完成网关或链上状态处理');
}
}
if ($this->hasColumns($connection, 'yipay_refunds', ['order_no', 'status'])
&& $this->hasColumns($connection, 'yipay_orders', ['order_no', 'user_id'])
&& $connection->table('yipay_refunds as refund')
->join('yipay_orders as payment', 'payment.order_no', '=', 'refund.order_no')
->whereIn('payment.user_id', $ids)
->whereIn('refund.status', ['dispatching', 'uncertain', 'gateway_accepted'])->exists()) {
throw new \RuntimeException('用户仍有待核对或记账的易支付退款');
}
$activeCompensationItems = collect();
if ($this->hasColumns(
$connection,

@ -35,6 +35,9 @@
<label class="yp-switch"><input type="checkbox" name="yipay_test_mode" value="true" {if $yipay_config.yipay_test_mode}checked{/if}>测试模式</label>
<span class="yp-help">开启后仅管理员能在用户充值页看到和调用易支付,普通用户直接请求接口也会被拒绝。</span>
</div>
<div class="yp-field is-wide">
<label class="yp-switch"><input type="checkbox" name="yipay_cny_confirmed" value="true" {if $yipay_config.yipay_cny_confirmed|default:false}checked{/if}>已核实启用的商户方式以人民币收款</label>
</div>
<div class="yp-field">
<label class="yp-switch"><input type="checkbox" name="yipay_alipay_enabled" value="true" {if $yipay_config.yipay_alipay_enabled}checked{/if}>支付宝</label>
</div>

@ -49,3 +49,7 @@ CREATE TABLE `payment_checkout_quotes` (
ALTER TABLE `usdt_payment_orders`
MODIFY COLUMN `exchange_rate` decimal(12,4) DEFAULT NULL,
ALTER COLUMN `currency` SET DEFAULT 'USD';
ALTER TABLE `yipay_refunds`
ADD COLUMN `gateway_amount` decimal(12,2) DEFAULT NULL AFTER `amount`,
ADD COLUMN `gateway_currency` char(3) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL AFTER `gateway_amount`;

@ -331,6 +331,8 @@ CREATE TABLE `yipay_refunds` (
`order_no` varchar(32) NOT NULL,
`gateway_trade_no` varchar(80) NOT NULL,
`amount` decimal(12,2) NOT NULL,
`gateway_amount` decimal(12,2) DEFAULT NULL,
`gateway_currency` char(3) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,
`status` varchar(16) NOT NULL DEFAULT 'success',
`gateway_message` varchar(500) NOT NULL DEFAULT '',
`admin_user_id` bigint(20) UNSIGNED NOT NULL,

@ -6,6 +6,8 @@ CREATE TABLE `yipay_refunds` (
`order_no` varchar(32) NOT NULL,
`gateway_trade_no` varchar(80) NOT NULL,
`amount` decimal(12,2) NOT NULL,
`gateway_amount` decimal(12,2) DEFAULT NULL,
`gateway_currency` char(3) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,
`status` varchar(16) NOT NULL DEFAULT 'success',
`gateway_message` varchar(500) NOT NULL DEFAULT '',
`admin_user_id` bigint(20) UNSIGNED NOT NULL,

@ -1,6 +1,7 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
require __DIR__ . '/Support/PaymentCheckoutFixture.php';
$System_Config = ['baseUrl' => 'https://panel.example.com'];
@ -11,6 +12,8 @@ use App\Services\Payment\YipayCredentialCipher;
use App\Services\Payment\YipayPaymentService;
use App\Services\Payment\YipaySigner;
use App\Services\Payment\PaymentOrderCreationException;
use App\Services\Payment\PaymentCheckoutQuotes;
use App\Services\Payment\PaymentRateService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
@ -59,9 +62,10 @@ $capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'defau
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->getConnection('default')->getSchemaBuilder();
createPaymentCheckoutFixture($schema);
$schema->create('configurations', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('name')->unique();
$table->text('value')->nullable();
});
$schema->create('user', function (Blueprint $table) {
@ -130,6 +134,8 @@ $schema->create('yipay_refunds', function (Blueprint $table) {
$table->string('order_no')->unique();
$table->string('gateway_trade_no')->unique();
$table->decimal('amount', 12, 2);
$table->decimal('gateway_amount', 12, 2)->nullable();
$table->string('gateway_currency')->nullable();
$table->string('status');
$table->string('gateway_message')->default('');
$table->integer('admin_user_id');
@ -222,6 +228,7 @@ Capsule::table('configurations')->insert([
['name' => 'yipay_enabled', 'value' => 'true'],
['name' => 'yipay_test_mode', 'value' => 'false'],
['name' => 'yipay_pid', 'value' => '1001'],
['name' => 'yipay_cny_confirmed', 'value' => 'true'],
['name' => 'yipay_secret_key', 'value' => YipayCredentialCipher::encrypt($secret)],
]);
Capsule::table('user')->insert([
@ -242,9 +249,13 @@ Capsule::table('cloud_invoices')->insert([
'user_id' => 1, 'plan_id' => 1, 'due_at' => time() + 1800,
'amount' => '43.00', 'status' => 'open'],
]);
PaymentRateService::override('USD/CNY', '7.20', time() + 3600, 9, 'Yipay test quote');
$invoiceCreateGateway = new class {
public array $outbound = [];
public function createOrder(array $payload)
{
$this->outbound = $payload;
return [
'trade_no' => '202609270000000001',
'payurl' => 'https://pay.example.com/invoice/yipay',
@ -265,6 +276,7 @@ $createdAttempt = Capsule::table('cloud_invoice_payments')
if ($createdAttempt === null
|| (string) $createdAttempt->status !== 'creating'
|| (string) $createdAttempt->provider !== 'yipay_alipay'
|| ($invoiceCreateGateway->outbound['money'] ?? '') !== '302.40'
|| (int) $createdAttempt->user_id !== 1
|| !Capsule::table('paylist')->where('tradeno', (string) $createdInvoiceOrder->order_no)->exists()) {
fwrite(STDERR, 'Yipay invoice attempt was not recorded with the local order.' . PHP_EOL);
@ -325,6 +337,8 @@ Capsule::table('yipay_orders')->insert([
'status' => 'pending',
]);
$refundRecordId = (int) Capsule::table('yipay_orders')->where('order_no', $orderNo)->value('id');
$now = time();
PaymentCheckoutQuotes::persist(PaymentCheckoutQuotes::prepare('yipay_alipay', '100.00', $now, $now + 1800), $orderNo, 1);
$callback = [
'pid' => '1001',
@ -332,7 +346,7 @@ $callback = [
'out_trade_no' => $orderNo,
'type' => 'alipay',
'name' => '账户余额充值',
'money' => '100.00',
'money' => '720.00',
'trade_status' => 'TRADE_SUCCESS',
'param' => '',
'sign_type' => 'MD5',
@ -385,7 +399,7 @@ $refundGateway = new class {
public function refund($tradeNo, $orderNo, $amount)
{
$this->calls++;
if ($tradeNo !== '202608151234567890' || $orderNo !== 'YP20260815120000A1B2C3D4E5F60708' || $amount !== '100.00') {
if ($tradeNo !== '202608151234567890' || $orderNo !== 'YP20260815120000A1B2C3D4E5F60708' || $amount !== '720.00') {
throw new RuntimeException('Unexpected refund payload.');
}
return ['code' => 1, 'msg' => '退款成功'];
@ -396,8 +410,22 @@ $refundService = new class($refundGateway) extends YipayPaymentService {
public function __construct($fakeGateway) { $this->fakeGateway = $fakeGateway; }
protected function gatewayClient(array $settings) { return $this->fakeGateway; }
};
PaymentRateService::override('USD/CNY', '7.30', time() + 3600, 9, 'Later rate before refund');
$capsule->getConnection()->statement("CREATE TRIGGER block_refund_ledger BEFORE INSERT ON code
WHEN NEW.type = -2 BEGIN SELECT RAISE(ABORT, 'simulated local posting failure'); END");
try {
$refundService->refundById($refundRecordId, 99);
throw new LogicException('A failed local re-entry was reported successful.');
} catch (RuntimeException $exception) {
if (Capsule::table('yipay_refunds')->where('order_no', $orderNo)->value('status') !== 'gateway_accepted'
|| $refundGateway->calls !== 1 || (float) User::find(1)->money !== 0.0) {
throw new RuntimeException('Yipay did not retain remote acceptance separately from local posting.', 0, $exception);
}
}
$capsule->getConnection()->statement('DROP TRIGGER block_refund_ledger');
$refund = $refundService->refundById($refundRecordId, 99);
if ($refund['amount'] !== '100.00'
|| $refund['gateway_amount'] !== '720.00' || $refund['gateway_currency'] !== 'CNY'
|| $refundGateway->calls !== 1
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== -100.0
|| (float) Capsule::table('user')->where('id', 2)->value('aff_money') !== 0.0
@ -498,12 +526,14 @@ $invoiceCallback = [
'out_trade_no' => $invoiceOrderNo,
'type' => 'alipay',
'name' => '云服务器续费账单',
'money' => '25.00',
'money' => '182.50',
'trade_status' => 'TRADE_SUCCESS',
'param' => '',
'sign_type' => 'MD5',
];
$invoiceCallback['sign'] = YipaySigner::sign($invoiceCallback, $secret);
$now = time();
PaymentCheckoutQuotes::persist(PaymentCheckoutQuotes::prepare('yipay_alipay', '25.00', $now, $now + 1800), $invoiceOrderNo, 1);
$invoiceResult = $service->processCallback($invoiceCallback);
$resolvedPaymentJob = Capsule::table('cloud_jobs')
->where('request_idempotency_key', 'yipay-invoice-callback-0001')->first();
@ -543,6 +573,53 @@ if ($refundGateway->calls !== 1
exit(1);
}
$wechatGateway = new class {
public array $submitted = [];
public int $refundCalls = 0;
public function createOrder(array $payload): array
{
$this->submitted = $payload;
return ['trade_no' => '202609270000000007', 'payurl' => 'https://pay.example.com/wechat'];
}
public function refund(string $tradeNo, string $orderNo, string $amount): array
{
$this->refundCalls++;
throw new RuntimeException('Simulated missing refund response');
}
};
$wechatService = new class($wechatGateway) extends YipayPaymentService {
public function __construct(private object $gateway) {}
protected function gatewayClient(array $settings) { return $this->gateway; }
};
$wechat = $wechatService->createOrder(
User::find(1), '10.00', 'wxpay', '192.0.2.20', 'test', 'https://panel.example.com'
);
$wechatCallback = array_replace($callback, [
'trade_no' => $wechat->gateway_trade_no,
'out_trade_no' => $wechat->order_no,
'type' => 'wxpay',
'money' => '73.00',
]);
$wechatCallback['sign'] = YipaySigner::sign($wechatCallback, $secret);
if ($wechatGateway->submitted['type'] !== 'wxpay' || $wechatGateway->submitted['money'] !== '73.00'
|| !$wechatService->processCallback($wechatCallback)['credited'] || (float) User::find(1)->money !== -65.0) {
throw new RuntimeException('WeChat did not collect CNY and credit USD.');
}
for ($attempt = 0; $attempt < 2; $attempt++) {
try {
$wechatService->refund($wechat->order_no, 99);
throw new LogicException('Unconfirmed refund was reported successful.');
} catch (RuntimeException $exception) {
if ($wechatGateway->refundCalls !== 1
|| Capsule::table('yipay_refunds')->where('order_no', $wechat->order_no)->value('status') !== 'uncertain'
|| (float) User::find(1)->money !== -65.0) {
throw new RuntimeException('Unconfirmed remote refund was retried or debited.', 0, $exception);
}
}
}
$controllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/YipayController.php');
if ($controllerSource === false
|| strpos($controllerSource, "->whereNotExists(function (\$query)") === false

Loading…
Cancel
Save