From 5db0e2240d27d3c604554e111be8c47981f56278 Mon Sep 17 00:00:00 2001 From: MiAn Date: Thu, 19 Nov 2026 17:53:12 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=AE=8C=E5=96=84=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E9=80=80=E6=AC=BE=E6=81=A2=E5=A4=8D=E4=B8=8E=E5=B8=88=E5=82=85?= =?UTF-8?q?=E7=AB=AF=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/cancel-refund-recovery.md | 11 ++ .../admin/command/OrderRefundRetry.php | 56 ++++++ .../application/admin/controller/PayOrder.php | 2 + server/application/api/controller/Auth.php | 6 - server/application/api/controller/Base.php | 19 +- server/application/api/controller/Master.php | 50 +++--- server/application/api/controller/Order.php | 50 ++++-- server/application/api/controller/Wxpay.php | 4 +- server/application/command.php | 1 + .../common/library/CancelRefundSummary.php | 20 +++ .../common/library/FinishImageUrls.php | 23 +++ .../common/library/PaymentService.php | 170 ++++++++++++++++-- tests/cancel_balance_refund.php | 43 +++++ tests/cancel_refund_summary.php | 11 ++ tests/finish_image_urls.php | 18 ++ tests/master_detail_refresh.test.js | 24 +++ tests/master_success_schedule.test.js | 16 ++ tests/order_transition_concurrency.php | 44 +++++ tests/refund_callback_idempotency.php | 52 ++++++ tests/refund_recovery_query.php | 17 ++ yjyf-app/components/master/MasterHallView.vue | 2 +- .../components/master/MasterWorkbenchView.vue | 8 +- yjyf-app/components/user/UserMineView.vue | 4 +- yjyf-app/pages.json | 2 +- yjyf-app/pages/login/login.vue | 2 +- yjyf-app/pages/master/apply.vue | 12 +- yjyf-app/pages/master/auth.vue | 2 +- yjyf-app/pages/master/detail.vue | 15 +- yjyf-app/pages/master/success.vue | 4 +- 29 files changed, 594 insertions(+), 94 deletions(-) create mode 100644 docs/cancel-refund-recovery.md create mode 100644 server/application/admin/command/OrderRefundRetry.php create mode 100644 server/application/common/library/CancelRefundSummary.php create mode 100644 server/application/common/library/FinishImageUrls.php create mode 100644 tests/cancel_balance_refund.php create mode 100644 tests/cancel_refund_summary.php create mode 100644 tests/finish_image_urls.php create mode 100644 tests/master_detail_refresh.test.js create mode 100644 tests/master_success_schedule.test.js create mode 100644 tests/order_transition_concurrency.php create mode 100644 tests/refund_callback_idempotency.php create mode 100644 tests/refund_recovery_query.php diff --git a/docs/cancel-refund-recovery.md b/docs/cancel-refund-recovery.md new file mode 100644 index 0000000..de6da6d --- /dev/null +++ b/docs/cancel-refund-recovery.md @@ -0,0 +1,11 @@ +# 取消订单退款恢复任务 + +订单取消后,退款申请可能因进程中断、网络故障或微信异步处理而未完成。部署后需在运行后端的服务器上每分钟执行一次: + +```sh +cd /path/to/yjyf/server && php think order:refund-retry +``` + +任务会查询已取消订单中尚待确认的微信支付,并核对、重试未完成的退款流水。退款失败时先查询原退款单;只有微信明确表示原单不存在,才使用同一退款单号重新提交。异常信息写入应用日志和支付流水,财务仍可在退款台账中查询、同步或重试。 + +仅注册命令不会使其自动运行。应通过服务器已有的计划任务系统配置执行频率,并使用该部署实际的 PHP 路径和项目目录。 diff --git a/server/application/admin/command/OrderRefundRetry.php b/server/application/admin/command/OrderRefundRetry.php new file mode 100644 index 0000000..ac5418c --- /dev/null +++ b/server/application/admin/command/OrderRefundRetry.php @@ -0,0 +1,56 @@ +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()); + } + } + } +} diff --git a/server/application/admin/controller/PayOrder.php b/server/application/admin/controller/PayOrder.php index 7e2cf8e..2202369 100644 --- a/server/application/admin/controller/PayOrder.php +++ b/server/application/admin/controller/PayOrder.php @@ -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; diff --git a/server/application/api/controller/Auth.php b/server/application/api/controller/Auth.php index 12d6a93..fc20c6b 100644 --- a/server/application/api/controller/Auth.php +++ b/server/application/api/controller/Auth.php @@ -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') { diff --git a/server/application/api/controller/Base.php b/server/application/api/controller/Base.php index 07f571a..fb360ab 100644 --- a/server/application/api/controller/Base.php +++ b/server/application/api/controller/Base.php @@ -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); } diff --git a/server/application/api/controller/Master.php b/server/application/api/controller/Master.php index 19a6819..2e9685f 100644 --- a/server/application/api/controller/Master.php +++ b/server/application/api/controller/Master.php @@ -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串) diff --git a/server/application/api/controller/Order.php b/server/application/api/controller/Order.php index 89b7013..4d018d1 100644 --- a/server/application/api/controller/Order.php +++ b/server/application/api/controller/Order.php @@ -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) { diff --git a/server/application/api/controller/Wxpay.php b/server/application/api/controller/Wxpay.php index d348815..375608f 100644 --- a/server/application/api/controller/Wxpay.php +++ b/server/application/api/controller/Wxpay.php @@ -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); } diff --git a/server/application/command.php b/server/application/command.php index 8a1ff62..497a177 100755 --- a/server/application/command.php +++ b/server/application/command.php @@ -20,4 +20,5 @@ return [ 'app\admin\command\AttachmentScan', 'app\admin\command\OrderAutoverify', 'app\admin\command\OrderRecycle', + 'app\admin\command\OrderRefundRetry', ]; diff --git a/server/application/common/library/CancelRefundSummary.php b/server/application/common/library/CancelRefundSummary.php new file mode 100644 index 0000000..0250e9d --- /dev/null +++ b/server/application/common/library/CancelRefundSummary.php @@ -0,0 +1,20 @@ + $state, 'amount' => round($amount, 2)]; + } +} diff --git a/server/application/common/library/FinishImageUrls.php b/server/application/common/library/FinishImageUrls.php new file mode 100644 index 0000000..b543bcb --- /dev/null +++ b/server/application/common/library/FinishImageUrls.php @@ -0,0 +1,23 @@ +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('报价状态已变更,请刷新重试'); } diff --git a/tests/cancel_balance_refund.php b/tests/cancel_balance_refund.php new file mode 100644 index 0000000..711c34d --- /dev/null +++ b/tests/cancel_balance_refund.php @@ -0,0 +1,43 @@ +where('id', 1)->find(); + if (!$user) throw new RuntimeException('Local test user missing'); + $order = Db::name('order')->find(); + if (!$order) throw new RuntimeException('Local test order template missing'); + $amount = 0.37; + $trade = 'BALTEST' . bin2hex(random_bytes(8)); + unset($order['id']); + $order['order_no'] = 'CANCELTEST' . bin2hex(random_bytes(6)); + $order['user_id'] = 1; + $order['status'] = 9; + $order['pay_status'] = 1; + $order['pay_amount'] = $amount; + $order['refund_amount'] = 0; + $orderId = Db::name('order')->insertGetId($order); + $id = Db::name('pay_order')->insertGetId([ + 'out_trade_no' => $trade, 'order_id' => $orderId, 'order_no' => $order['order_no'], + 'user_id' => 1, 'scene' => 'order', 'openid' => 'BALANCE', 'amount' => $amount, + 'status' => 'paid', 'refund_status' => 'none', + ]); + PaymentService::refundOrder($orderId, '取消订单退款测试'); + PaymentService::refundOrder($orderId, '取消订单退款测试'); + $summary = PaymentService::syncCancelledOrderRefund($orderId); + $payment = Db::name('pay_order')->where('id', $id)->find(); + $after = Db::name('user')->where('id', 1)->find(); + $orderAfter = Db::name('order')->where('id', $orderId)->find(); + if ($payment['status'] !== 'refunded' || abs((float)$payment['refund_amount'] - $amount) > 0.001 + || abs((float)$after['money'] - (float)$user['money'] - $amount) > 0.001 + || (int)$orderAfter['pay_status'] !== 2 || $summary['state'] !== 'success') { + throw new RuntimeException('Balance refund was not returned exactly once'); + } + echo "Balance refund checks passed\n"; +} finally { + Db::rollback(); +} diff --git a/tests/cancel_refund_summary.php b/tests/cancel_refund_summary.php new file mode 100644 index 0000000..e3c6de0 --- /dev/null +++ b/tests/cancel_refund_summary.php @@ -0,0 +1,11 @@ + 'processing', 'amount' => 0.0], CancelRefundSummary::summarize([['status' => 'refunding', 'refund_amount' => 0]])); +assertSummary(['state' => 'failed', 'amount' => 4.0], CancelRefundSummary::summarize([['status' => 'refunded', 'refund_amount' => 4], ['status' => 'refund_failed', 'refund_amount' => 0]])); +assertSummary(['state' => 'success', 'amount' => 10.0], CancelRefundSummary::summarize([['status' => 'refunded', 'refund_amount' => 4], ['status' => 'refunded', 'refund_amount' => 6]])); +assertSummary(['state' => 'missing', 'amount' => 0.0], CancelRefundSummary::summarize([])); +echo "Cancel refund summary checks passed\n"; diff --git a/tests/finish_image_urls.php b/tests/finish_image_urls.php new file mode 100644 index 0000000..88f929a --- /dev/null +++ b/tests/finish_image_urls.php @@ -0,0 +1,18 @@ + p.path === 'pages/master/detail'); +assert.strictEqual(page.style.enablePullDownRefresh, true, '师傅工单详情应启用下拉刷新'); +const source = fs.readFileSync('yjyf-app/pages/master/detail.vue', 'utf8').match(/