fix(payment): separate Yipay charges from USD credits
parent
8fc0057ae0
commit
c6557c0cd1
@ -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));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue