fix: 完善取消退款恢复与师傅端流程

这个提交包含在:
2026-11-19 17:53:12 +08:00
父节点 5dd04b2f24
当前提交 5db0e2240d
共有 29 个文件被更改,包括 594 次插入 和 94 次删除

查看文件

@@ -172,6 +172,9 @@ class PaymentService
if (!$master) {
throw new \InvalidArgumentException('报价师傅信息不存在');
}
if ($master['verify_status'] !== 'pass') {
throw new \InvalidArgumentException('该师傅资质尚未审核通过,请选择其他师傅');
}
$quoteAmount = round((float)$quote['amount'], 2);
$targetTotalPay = max(0, round($quoteAmount - (float)$order['discount_amount'], 2));
@@ -517,6 +520,7 @@ class PaymentService
if (
!$quote
|| !$master
|| $master['verify_status'] !== 'pass'
|| (int)$lockedOrder['status'] !== OrderStatus::QUOTING
|| (int)$lockedOrder['master_id'] !== 0
) {
@@ -563,7 +567,7 @@ class PaymentService
self::sendNotify('master', (int)$master['id'], '您的报价已被选中', '订单 ' . $lockedOrder['order_no'] . ' 客户已选择您的报价 ¥' . $quoteAmount . ' 并完成支付托管,请尽快联系客户', 'order', $orderId);
}
} elseif ($scene === 'diff') {
if ((int)$lockedOrder['diff_status'] !== 1) {
if ((int)$lockedOrder['diff_status'] !== 1 || (int)$lockedOrder['status'] === OrderStatus::CANCELLED) {
$autoRefundDuplicate = true;
} else {
$diffAmount = round((float)$lockedPay['amount'], 2);
@@ -607,6 +611,7 @@ class PaymentService
self::addOrderLog((int)$payOrder['order_id'], 0, '【高危财务异常】' . $duplicateRefundError, 'system', (int)$payOrder['user_id']);
Log::error('[PaymentService::confirmOrderPay] ' . $duplicateRefundError);
}
self::syncCancelledOrderRefund((int)$payOrder['order_id']);
}
// 事务外:新工单广播给在线认证师傅
@@ -672,29 +677,72 @@ class PaymentService
}
$totalRefunded = 0.00;
$errors = [];
foreach ($effectiveRows as $po) {
if ($po['status'] === 'refunded') {
// 已退满:直接累计已退金额(含此前部分退款累计)
$totalRefunded = round($totalRefunded + (float)$po['refund_amount'], 2);
continue;
}
if ($po['status'] === 'refunding') {
$synced = self::syncRefundPayOrder((int)$po['id']);
if ($synced['status'] === 'refund_failed') {
throw new \RuntimeException('历史退款单(' . $synced['refund_no'] . ')微信侧退款异常:' . $synced['fail_reason']);
try {
if ($po['status'] === 'refunded') {
// 已退满:直接累计已退金额(含此前部分退款累计)
$totalRefunded = round($totalRefunded + (float)$po['refund_amount'], 2);
continue;
}
// 以同步后流水的累计已退金额为准(准确支持部分退款累计)
$totalRefunded = round($totalRefunded + (float)$synced['refund_amount'], 2);
continue;
if ($po['status'] === 'refunding') {
$synced = self::syncRefundPayOrder((int)$po['id']);
if ($synced['status'] === 'refund_failed') {
throw new \RuntimeException('历史退款单(' . $synced['refund_no'] . ')微信侧退款异常:' . $synced['fail_reason']);
}
$totalRefunded = round($totalRefunded + (float)$synced['refund_amount'], 2);
continue;
}
// paid 或 refund_failed 自动退还该笔流水的全部剩余可退金额。
$after = self::refundSinglePayOrder((int)$po['id'], $reason);
$totalRefunded = round($totalRefunded + (float)($after['refund_amount'] ?: $po['amount']), 2);
} catch (\Throwable $e) {
if ((int)$e->getCode() !== 409) {
Db::name('pay_order')->where('id', (int)$po['id'])->where('status', 'paid')->update([
'status' => 'refund_failed',
'fail_reason' => mb_substr('取消订单退款申请失败:' . $e->getMessage(), 0, 480),
'updatetime' => time(),
]);
}
$errors[] = '支付流水 ' . $po['id'] . ':' . $e->getMessage();
}
// paid 或 refund_failed 均发起/重试原路退款(自动退该笔流水全部剩余可退金额)
$after = self::refundSinglePayOrder((int)$po['id'], $reason);
$totalRefunded = round($totalRefunded + (float)($after['refund_amount'] ?: $po['amount']), 2);
}
if ($errors) {
throw new \RuntimeException(implode(';', $errors));
}
return $totalRefunded;
}
/** 汇总已取消订单的真实退款结果;事务内只读取支付流水,绝不调用外部服务。 */
public static function syncCancelledOrderRefund($orderId)
{
Db::startTrans();
try {
$order = Db::name('order')->where('id', (int)$orderId)->lock(true)->find();
if (!$order || (int)$order['status'] !== OrderStatus::CANCELLED) {
Db::commit();
return null;
}
$rows = Db::name('pay_order')->where('order_id', (int)$orderId)
->whereIn('status', ['paid', 'refunding', 'refunded', 'refund_failed'])->select();
$summary = CancelRefundSummary::summarize($rows);
if ($summary['state'] !== 'missing') {
Db::name('order')->where('id', (int)$orderId)->update([
'refund_amount' => $summary['amount'],
'pay_status' => $summary['state'] === 'success' ? 2 : 1,
'updatetime' => time(),
]);
}
Db::commit();
return $summary;
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
}
/**
* 售后部分退款:按指定退款总额在订单名下有效支付流水间依次原路退回(必须在事务外部调用)
*
@@ -816,6 +864,20 @@ class PaymentService
* @return array 更新后的 pay_order 记录
*/
public static function refundSinglePayOrder($payOrderId, $reason = '订单取消原路退款', $partialAmount = null)
{
$lockName = 'yjyf_refund_' . (int)$payOrderId;
$rows = Db::query('SELECT GET_LOCK(?, 2) AS acquired', [$lockName]);
if (empty($rows) || (int)$rows[0]['acquired'] !== 1) {
throw new \RuntimeException('该支付流水正在退款处理中,请稍后重试', 409);
}
try {
return self::refundSinglePayOrderLocked($payOrderId, $reason, $partialAmount);
} finally {
Db::query('SELECT RELEASE_LOCK(?)', [$lockName]);
}
}
protected static function refundSinglePayOrderLocked($payOrderId, $reason, $partialAmount)
{
$po = Db::name('pay_order')->where('id', (int)$payOrderId)->find();
if (!$po) {
@@ -831,6 +893,24 @@ class PaymentService
throw new \InvalidArgumentException('当前支付单状态(' . self::payOrderStatusLabel($po['status']) . ')不允许发起退款');
}
// 对请求超时等未知结果先查微信;仅明确不存在时使用原退款单号重新提交。
if ($po['status'] === 'refund_failed' && $po['openid'] !== 'BALANCE'
&& strpos((string)$po['out_trade_no'], 'BAL') !== 0 && !empty($po['refund_no'])
&& !in_array($po['refund_status'], ['abnormal', 'closed'], true)) {
try {
$po = self::syncRefundPayOrder((int)$po['id']);
if (in_array($po['status'], ['refunding', 'refunded'], true)) {
return $po;
}
} catch (\Throwable $e) {
$fail = WxPayV3Service::extractFailInfo($e);
if ($fail['code'] !== 'RESOURCE_NOT_EXISTS') {
throw $e;
}
$po = Db::name('pay_order')->where('id', (int)$po['id'])->find();
}
}
// 可退余额 = 流水支付总额 - 已累计成功退款金额(支持一笔流水多次部分退款)
$payTotal = round((float)$po['amount'], 2);
$refundable = round($payTotal - round((float)$po['refund_amount'], 2), 2);
@@ -942,7 +1022,7 @@ class PaymentService
throw $e;
}
return self::applyWxRefundResult($po, $resp, round((float)$po['amount'], 2));
return self::applyWxRefundResult($po, $resp);
}
/**
@@ -953,6 +1033,52 @@ class PaymentService
* 累计退满后流水状态置为 refunded,未退满则保持 paid 可继续发起退款。
*/
public static function applyWxRefundResult(array $po, array $wxRefundData, $fallbackAmount = 0.00)
{
Db::startTrans();
$transactionClosed = false;
try {
$locked = Db::name('pay_order')->where('id', (int)$po['id'])->lock(true)->find();
if (!$locked) {
throw new \RuntimeException('支付交易单不存在');
}
$incomingNo = trim((string)($wxRefundData['out_refund_no'] ?? ''));
if ($incomingNo !== '' && $incomingNo !== (string)$locked['refund_no']) {
throw new \RuntimeException('退款通知的退款单号与当前退款单不一致');
}
$incomingId = trim((string)($wxRefundData['refund_id'] ?? ''));
$wxStatus = strtoupper(trim((string)($wxRefundData['status'] ?? $wxRefundData['refund_status'] ?? '')));
if ($wxStatus === 'SUCCESS' && $incomingId === '') {
throw new \RuntimeException('微信退款成功报文缺少退款单号,无法安全核对');
}
if ($incomingId !== '' && $locked['refund_status'] === 'success'
&& $incomingId === (string)$locked['refund_id']) {
Db::commit();
$transactionClosed = true;
return $locked;
}
try {
$result = self::applyWxRefundResultLocked($locked, $wxRefundData, $fallbackAmount);
} catch (\Throwable $e) {
if (in_array($wxStatus, ['ABNORMAL', 'CLOSED'], true) && (int)$e->getCode() === 10001) {
Db::commit();
} else {
Db::rollback();
}
$transactionClosed = true;
throw $e;
}
Db::commit();
$transactionClosed = true;
return $result;
} catch (\Throwable $e) {
if (!$transactionClosed) {
Db::rollback();
}
throw $e;
}
}
protected static function applyWxRefundResultLocked(array $po, array $wxRefundData, $fallbackAmount = 0.00)
{
$wxStatus = strtoupper(trim((string)($wxRefundData['status'] ?? $wxRefundData['refund_status'] ?? '')));
if ($wxStatus === '') {
@@ -967,10 +1093,16 @@ class PaymentService
if ($thisRefund <= 0) {
$thisRefund = round((float)$fallbackAmount, 2);
}
if ($wxStatus === 'SUCCESS' && $thisRefund <= 0) {
throw new \RuntimeException('微信退款成功报文缺少退款金额,无法安全核对');
}
// 此前已完成的部分退款累计(PROCESSING 阶段不写入本次金额,避免同步到账后重复累计)
$prevRefunded = round((float)$po['refund_amount'], 2);
if ($wxStatus === 'SUCCESS') {
if ($prevRefunded + $thisRefund > $payTotal + 0.005) {
throw new \RuntimeException('退款金额超过支付流水可退余额,请人工核查');
}
$succTime = !empty($wxRefundData['success_time'])
? (strtotime((string)$wxRefundData['success_time']) ?: $now)
: $now;
@@ -1027,7 +1159,7 @@ class PaymentService
self::addOrderLog((int)$po['order_id'], 0, '【退款异常告警】' . $reasonZh . '(退款单号:' . $po['refund_no'] . ')', 'system', 0);
Log::error("[PaymentService::applyWxRefundResult] 退款失败 out_trade_no={$po['out_trade_no']}, refund_no={$po['refund_no']}, wxStatus={$wxStatus}");
throw new \RuntimeException($reasonZh);
throw new \RuntimeException($reasonZh, 10001);
}
/**
@@ -1898,7 +2030,7 @@ class PaymentService
}
$quote = Db::name('order_quote')->where('id', $quoteId)->where('order_id', $orderId)->lock(true)->find();
$master = $quote ? Db::name('master')->where('id', (int)$quote['master_id'])->find() : null;
if (!$quote || !$master || $quote['status'] !== 'wait') {
if (!$quote || !$master || $master['verify_status'] !== 'pass' || $quote['status'] !== 'wait') {
throw new \InvalidArgumentException('报价状态已变更,请刷新重试');
}