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

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

查看文件

@@ -0,0 +1,56 @@
<?php
namespace app\admin\command;
use app\common\library\OrderStatus;
use app\common\library\PaymentService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
/** 定期执行:php think order:refund-retry */
class OrderRefundRetry extends Command
{
protected function configure()
{
$this->setName('order:refund-retry')->setDescription('核对并重试已取消订单的原路退款');
}
protected function execute(Input $input, Output $output)
{
// 支付通知晚到或丢失时,先向微信确认取消订单下的待支付流水。
$pending = Db::name('pay_order')->alias('p')
->join('order o', 'o.id = p.order_id')
->where('o.status', OrderStatus::CANCELLED)
->where('p.status', 'pending')
->where('p.openid', '<>', 'BALANCE')
->where(function ($query) {
$query->whereNull('p.last_sync_time')->whereOr('p.last_sync_time', '<', time() - 60);
})
->field('p.out_trade_no')->order('p.id asc')->limit(100)->select();
foreach ($pending as $payment) {
try {
PaymentService::confirmOrderPay((string)$payment['out_trade_no']);
} catch (\Throwable $e) {
\think\Log::error('[OrderRefundRetry payment] ' . $payment['out_trade_no'] . ' ' . $e->getMessage());
}
}
$orders = Db::name('pay_order')->alias('p')->join('order o', 'o.id = p.order_id')
->where('o.status', OrderStatus::CANCELLED)
->whereIn('p.status', ['paid', 'refunding', 'refund_failed'])
->where('p.updatetime', '<', time() - 60)
->field('o.id')->group('o.id')->order('o.id asc')->limit(100)->select();
foreach ($orders as $order) {
$id = (int)$order['id'];
try {
PaymentService::refundOrder($id, '取消订单原路退款恢复');
PaymentService::syncCancelledOrderRefund($id);
$output->writeln('订单 #' . $id . ' 已核对退款');
} catch (\Throwable $e) {
PaymentService::syncCancelledOrderRefund($id);
\think\Log::error('[OrderRefundRetry] order_id=' . $id . ' ' . $e->getMessage());
$output->writeln('订单 #' . $id . ' 退款异常:' . $e->getMessage());
}
}
}
}

查看文件

@@ -79,6 +79,7 @@ class PayOrder extends Backend
}
try {
$after = PaymentService::syncRefundPayOrder($id);
PaymentService::syncCancelledOrderRefund((int)$po['order_id']);
} catch (\Throwable $e) {
$this->error('同步微信状态失败:' . $e->getMessage());
return;
@@ -103,6 +104,7 @@ class PayOrder extends Backend
}
try {
$after = PaymentService::refundSinglePayOrder($id, '平台人工重发原路退款(退款台账)');
PaymentService::syncCancelledOrderRefund((int)$po['order_id']);
} catch (\Throwable $e) {
$this->error('重发退款失败:' . $e->getMessage());
return;

查看文件

@@ -370,12 +370,6 @@ class Auth extends Base
if (!$master) {
$this->error('请先完成师傅入驻', ['need_apply' => 1], 2001);
}
if ($master['verify_status'] === 'pending') {
$this->error('师傅资质审核中,请耐心等待', ['verify_status' => 'pending'], 2002);
}
if ($master['verify_status'] === 'reject') {
$this->error('资质未通过:' . $master['audit_msg'], ['verify_status' => 'reject'], 2003);
}
}
if ($role === 'merchant') {

查看文件

@@ -51,20 +51,30 @@ class Base extends Api
}
/**
* 要求是已通过审核的师傅
* 要求拥有师傅档案,允许查看师傅端。
*/
protected function requireMaster()
protected function requireMasterProfile()
{
$master = $this->masterInfo();
if (!$master) {
$this->error('请先完成师傅入驻', ['need_apply' => 1], 2001);
}
return $master;
}
/** 要求师傅通过审核,供接单及敏感操作使用。 */
protected function requireMaster()
{
$master = $this->requireMasterProfile();
if ($master['verify_status'] === 'pending') {
$this->error('师傅资质审核中,请耐心等待', ['verify_status' => 'pending'], 2002);
}
if ($master['verify_status'] === 'reject') {
$this->error('资质未通过:' . $master['audit_msg'], ['verify_status' => 'reject'], 2003);
}
if ($master['verify_status'] !== 'pass') {
$this->error('师傅资质尚未审核通过,无法接单');
}
return $master;
}
@@ -145,7 +155,10 @@ class Base extends Api
'status' => (int)$to,
'updatetime' => time(),
]);
Db::name('order')->where('id', (int)$order['id'])->update($data);
$updated = Db::name('order')->where('id', (int)$order['id'])->where('status', $from)->update($data);
if (!$updated) {
$this->error('订单状态已变更,请刷新后重试');
}
$this->addLog((int)$order['id'], (int)$to, $remark, $operatorType, $operatorId);
return array_merge($order, $data);
}

查看文件

@@ -4,6 +4,7 @@ namespace app\api\controller;
use app\common\library\CommissionService;
use app\common\library\FinanceConfigService;
use app\common\library\FinishImageUrls;
use app\common\library\OrderStatus;
use app\common\library\PaymentService;
use app\common\library\TiandituService;
@@ -98,11 +99,9 @@ class Master extends Base
}
// 若是驳回后重提且未修改脱敏展示号,沿用原存储的完整身份证号;否则校验完整身份证号并真实入库
$needVerify = true;
if (strpos($rawIdcard, '*') !== false) {
if ($exist && !empty($exist['idcard_no']) && strpos((string)$exist['idcard_no'], '*') === false) {
$finalIdcard = (string)$exist['idcard_no'];
$needVerify = false;
} else {
$this->error('请填写真实完整的18位身份证号码');
return;
@@ -125,12 +124,10 @@ class Master extends Base
}
// 腾讯云公安权威二要素实名核验(姓名 + 身份证号)
if ($needVerify) {
$verifyRes = TencentVerifyService::verifyIdCard($realname, $finalIdcard);
if (!$verifyRes['pass']) {
$this->error('实名核验未通过:' . $verifyRes['msg']);
return;
}
$verifyRes = TencentVerifyService::verifyIdCard($realname, $finalIdcard);
if (!$verifyRes['pass']) {
$this->error('实名核验未通过:' . $verifyRes['msg']);
return;
}
$catNameMap = Db::name('service_cat')->where('id', 'in', $skillCatIds)->column('name', 'id');
@@ -144,9 +141,10 @@ class Master extends Base
'cert_images' => $certImages,
'city' => $normalizedCity,
'work_status' => 'off',
'verify_status' => 'pass',
'audit_msg' => '腾讯云二要素实名核验通过',
'audittime' => time(),
'verify_status' => 'pending',
'audit_msg' => '',
'audittime' => null,
'audit_admin_id' => 0,
'updatetime' => time(),
];
@@ -180,7 +178,7 @@ class Master extends Base
$this->error('提交失败:' . $e->getMessage());
}
$this->success('实名认证成功,已获得接单资格!', ['master_id' => (int)$masterId]);
$this->success('申请已提交,请等待后台审核', ['master_id' => (int)$masterId, 'verify_status' => 'pending']);
}
/**
@@ -312,7 +310,7 @@ class Master extends Base
*/
public function updateLocation()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$rawLat = $this->request->post('lat', '');
$rawLng = $this->request->post('lng', '');
if (!$this->isValidCoord($rawLat, $rawLng)) {
@@ -389,7 +387,7 @@ class Master extends Base
*/
public function searchLocation()
{
$this->requireMaster();
$this->requireMasterProfile();
$keyword = trim((string)$this->request->param('keyword', ''));
if (mb_strlen($keyword) < 2) {
$this->success('', ['list' => []]);
@@ -410,7 +408,7 @@ class Master extends Base
*/
public function locationContext()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$rawLat = $this->request->param('lat', '');
$rawLng = $this->request->param('lng', '');
$category = trim((string)$this->request->param('category', 'all'));
@@ -473,7 +471,7 @@ class Master extends Base
*/
public function locationOrderStats()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$rawLat = $this->request->param('lat', '');
$rawLng = $this->request->param('lng', '');
$city = trim((string)$this->request->param('city', ''));
@@ -496,7 +494,7 @@ class Master extends Base
*/
public function locateCity()
{
$this->requireMaster();
$this->requireMasterProfile();
$city = trim((string)$this->request->param('city', ''));
if ($city === '') {
$this->error('请提供城市名称');
@@ -529,7 +527,7 @@ class Master extends Base
*/
public function hall()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$this->recycleExpired();
$catIds = $this->getMasterSkillCatIds((int)$master['id']);
@@ -989,7 +987,7 @@ class Master extends Base
public function finish()
{
$order = $this->ownOrder((int)$this->request->post('order_id'), 'master');
$images = (array)$this->request->post('images/a', []);
$images = FinishImageUrls::normalize((array)$this->request->post('images/a', []));
$damage = trim((string)$this->request->post('damage_remark', ''));
Db::startTrans();
@@ -1142,7 +1140,7 @@ class Master extends Base
public function orders()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$status = $this->request->param('status', 'active');
$page = max(1, (int)$this->request->param('page', 1));
$limit = min(30, max(1, (int)$this->request->param('limit', 10)));
@@ -1198,7 +1196,7 @@ class Master extends Base
*/
public function income()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
// 顺带轻量同步最新 3 笔处理中的微信转账提现单(如师傅上次已确认收款但未回调或超时自动退回)
$syncCandidates = Db::name('withdraw')
@@ -1637,7 +1635,7 @@ class Master extends Base
*/
public function credit()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$mid = (int)$master['id'];
$reviewTotal = (int)Db::name('review')->where('master_id', $mid)->where('status', 'normal')->count();
@@ -1671,7 +1669,7 @@ class Master extends Base
*/
public function appeals()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$list = Db::name('appeal')->where('master_id', $master['id'])->order('id desc')->limit(30)->select();
$typeText = ['misjudge' => '误判申诉', 'review' => '恶意评价', 'deduct' => '扣款申诉', 'other' => '其他'];
$statusText = ['wait' => '待处理', 'handling' => '处理中', 'done' => '已处理', 'reject' => '已驳回'];
@@ -1749,7 +1747,7 @@ class Master extends Base
*/
public function quotes()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$list = Db::name('order_quote')->alias('q')
->join('order o', 'o.id = q.order_id', 'LEFT')
->field('q.*, o.order_no, o.service_name, o.pay_amount as order_amount, o.status as order_status')
@@ -1994,7 +1992,7 @@ class Master extends Base
public function orderDetail()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$masterId = (int)$master['id'];
$orderId = (int)$this->request->param('id') ?: (int)$this->request->param('order_id');
if ($orderId <= 0) {
@@ -2579,7 +2577,7 @@ class Master extends Base
*/
public function saveSkills()
{
$master = $this->requireMaster();
$master = $this->requireMasterProfile();
$masterId = (int)$master['id'];
// 同时兼容 skill_ids(ID 数组/逗号串/JSON串)与 selected_skills(名称数组/逗号串/JSON串)

查看文件

@@ -1309,18 +1309,6 @@ class Order extends Base
$this->error('该订单已开具发票,如需取消退款请联系客服办理发票冲红');
}
// 若订单已支付,先在数据库事务外部调用微信支付 APIv3 逐笔发起原路退款(无有效流水严格拦截,严禁静默跳过)
$refundedAmount = 0.00;
if ((int)$order['pay_status'] === 1) {
try {
$refundedAmount = PaymentService::refundOrder($orderId, '用户取消:' . $reason);
} catch (\Throwable $re) {
\think\Log::error('[Order::cancel refund] order_id=' . $orderId . ' reason=' . $re->getMessage());
$this->error('申请微信原路退款失败:' . $re->getMessage());
return;
}
}
$prevMasterId = 0;
Db::startTrans();
try {
@@ -1328,12 +1316,18 @@ class Order extends Base
if (!$lockedOrder || !OrderStatus::canCancelByUser($lockedOrder['status'])) {
throw new \InvalidArgumentException('当前状态不可取消,请刷新重试');
}
if (isset($lockedOrder['invoice_status']) && in_array($lockedOrder['invoice_status'], ['wait', 'issued'], true)) {
throw new \InvalidArgumentException('订单开票状态已变更,请刷新后重试');
}
if ((int)$lockedOrder['pay_status'] === 1 && (float)$lockedOrder['pay_amount'] > 0) {
$paymentAmount = (float)Db::name('pay_order')->where('order_id', $orderId)
->whereIn('status', ['paid', 'refunding', 'refunded', 'refund_failed'])->sum('amount');
if ($paymentAmount + 0.005 < (float)$lockedOrder['pay_amount']) {
throw new \InvalidArgumentException('支付流水金额不足,请联系客服核实后取消');
}
}
$prevMasterId = (int)$lockedOrder['master_id'];
$extra = ['cancel_reason' => mb_substr($reason, 0, 255)];
if ((int)$lockedOrder['pay_status'] === 1) {
$extra['pay_status'] = 2;
$extra['refund_amount'] = $refundedAmount > 0 ? $refundedAmount : (float)$lockedOrder['pay_amount'];
}
$this->transit($lockedOrder, OrderStatus::CANCELLED, '用户取消:' . $reason, $extra, 'user', $this->uid());
if ((int)$lockedOrder['coupon_id'] > 0) {
@@ -1370,6 +1364,19 @@ class Order extends Base
return;
}
if ((int)$lockedOrder['pay_status'] === 1 && (float)$lockedOrder['pay_amount'] > 0) {
try {
PaymentService::refundOrder($orderId, '用户取消:' . $reason);
PaymentService::syncCancelledOrderRefund($orderId);
} catch (\Throwable $re) {
\think\Log::error('[Order::cancel refund] order_id=' . $orderId . ' reason=' . $re->getMessage());
PaymentService::syncCancelledOrderRefund($orderId);
$this->success('订单已取消,退款申请异常,请联系客服处理');
return;
}
$this->success('订单已取消,退款已申请,请留意退款进度');
return;
}
$this->success('订单已取消');
}
@@ -1614,7 +1621,16 @@ class Order extends Base
$statusTimelineText = OrderStatus::tip($status);
$statusTime = !empty($row['updatetime']) ? (int)$row['updatetime'] : (int)$row['createtime'];
if ($status === OrderStatus::CANCELLED) {
$statusTimelineText = ((int)$row['pay_status'] === 0) ? '订单未支付,您已取消订单' : '订单已取消,退款处理中';
$refundRows = Db::name('pay_order')->where('order_id', (int)$row['id'])
->whereIn('status', ['paid', 'refunding', 'refunded', 'refund_failed'])->select();
$refundSummary = \app\common\library\CancelRefundSummary::summarize($refundRows);
if ($refundSummary['state'] === 'missing') {
$statusTimelineText = ((int)$row['pay_status'] === 0 || (float)$row['pay_amount'] <= 0)
? '订单已取消' : '订单已取消,退款异常,请联系客服';
} else {
$refundTips = ['success' => '订单已取消,退款成功', 'processing' => '订单已取消,退款处理中', 'failed' => '订单已取消,退款异常,请联系客服'];
$statusTimelineText = $refundTips[$refundSummary['state']];
}
} elseif ($status === OrderStatus::PENDING_PAY) {
$statusTimelineText = '订单待支付,请尽快完成支付';
} elseif ($status === OrderStatus::PENDING_ACCEPT) {

查看文件

@@ -74,9 +74,11 @@ class Wxpay extends Api
try {
PaymentService::applyWxRefundResult($po, $data);
PaymentService::syncCancelledOrderRefund((int)$po['order_id']);
} catch (\Throwable $refundEx) {
// 若微信已下发明确退款异常/关闭终态,系统已完整落库记录原因并写入告警日志,向微信回传成功避免重复轰炸
if (in_array($refStatus, ['ABNORMAL', 'CLOSED'], true)) {
if (in_array($refStatus, ['ABNORMAL', 'CLOSED'], true) && (int)$refundEx->getCode() === 10001) {
PaymentService::syncCancelledOrderRefund((int)$po['order_id']);
Log::error("[Wxpay::refundNotify] 退款终态异常已落库 out_trade_no={$po['out_trade_no']}, status={$refStatus}, reason=" . $refundEx->getMessage());
return $this->wxResponse(true);
}

查看文件

@@ -20,4 +20,5 @@ return [
'app\admin\command\AttachmentScan',
'app\admin\command\OrderAutoverify',
'app\admin\command\OrderRecycle',
'app\admin\command\OrderRefundRetry',
];

查看文件

@@ -0,0 +1,20 @@
<?php
namespace app\common\library;
class CancelRefundSummary
{
public static function summarize(array $rows)
{
$amount = 0.0;
$state = $rows ? 'success' : 'missing';
foreach ($rows as $row) {
$amount += (float)$row['refund_amount'];
if ($row['status'] === 'refund_failed') {
$state = 'failed';
} elseif ($row['status'] !== 'refunded' && $state !== 'failed') {
$state = 'processing';
}
}
return ['state' => $state, 'amount' => round($amount, 2)];
}
}

查看文件

@@ -0,0 +1,23 @@
<?php
namespace app\common\library;
class FinishImageUrls
{
public static function normalize(array $images)
{
$urls = [];
foreach ($images as $image) {
if (!is_string($image)) {
continue;
}
foreach (explode(',', $image) as $url) {
$url = trim($url);
if ($url !== '') {
$urls[] = $url;
}
}
}
return $urls;
}
}

查看文件

@@ -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('报价状态已变更,请刷新重试');
}