255 || (int)$operatorId <= 0) { throw new \InvalidArgumentException('请填写退款原因和操作人'); } $initial = Db::name('pay_order')->where('id', (int)$payId)->find(); if (!$initial || $initial['scene'] !== 'recharge') throw new \InvalidArgumentException('充值订单不存在'); Db::startTrans(); try { $user = Db::name('user')->where('id', (int)$initial['user_id'])->lock(true)->find(); $pay = Db::name('pay_order')->where('id', (int)$payId)->lock(true)->find(); if (!$user || !$pay || $pay['scene'] !== 'recharge' || (int)$pay['user_id'] !== (int)$user['id'] || $pay['status'] !== 'paid') { throw new \InvalidArgumentException('充值订单当前状态不允许退款'); } if (Db::name('recharge_refund')->where('pay_order_id', (int)$payId)->whereIn('status', ['pending','submitting','processing','unknown','abnormal'])->find()) { throw new \InvalidArgumentException('该充值订单已有未完成的退款申请'); } $fen = RechargeRefundPolicy::validateAmount($amount, $pay['amount'], $pay['refund_amount'], $user['money']); $newBalance = number_format(((int)round((float)$user['money'] * 100) - $fen) / 100, 2, '.', ''); $now = time(); $refundNo = 'RR' . date('YmdHis', $now) . strtoupper(bin2hex(random_bytes(8))); $id = Db::name('recharge_refund')->insertGetId(['pay_order_id'=>(int)$payId,'user_id'=>(int)$user['id'],'amount'=>number_format($fen / 100, 2, '.', ''),'refund_no'=>$refundNo,'reason'=>$reason,'operator_id'=>(int)$operatorId,'status'=>'pending','createtime'=>$now,'updatetime'=>$now]); Db::name('user')->where('id', (int)$user['id'])->update(['money'=>$newBalance,'updatetime'=>$now]); Db::name('wallet_log')->insert(['user_type'=>'user','user_id'=>(int)$user['id'],'type'=>'recharge_refund_hold','amount'=>number_format(-$fen / 100, 2, '.', ''),'balance'=>$newBalance,'order_id'=>0,'remark'=>'充值退款占用余额(退款单 '.$refundNo.')','createtime'=>$now]); Db::commit(); return Db::name('recharge_refund')->where('id', $id)->find(); } catch (\Throwable $e) { Db::rollback(); throw $e; } } public static function begin($refundId, $reviewerId, $note) { if ((int)$reviewerId <= 0 || mb_strlen(trim((string)$note)) > 255) throw new \InvalidArgumentException('审核信息不正确'); $changed = Db::name('recharge_refund')->where('id', (int)$refundId)->where('status', 'pending')->update([ 'status'=>'submitting', 'reviewer_id'=>(int)$reviewerId, 'audit_note'=>trim((string)$note), 'updatetime'=>time() ]); if (!$changed) throw new \InvalidArgumentException('退款申请不在待审核状态'); return Db::name('recharge_refund')->where('id', (int)$refundId)->find(); } public static function applyResult($refundNo, array $data) { if (empty($data['out_refund_no']) || !hash_equals((string)$refundNo, (string)$data['out_refund_no'])) throw new \InvalidArgumentException('退款单号不匹配'); $initial = Db::name('recharge_refund')->where('refund_no', $refundNo)->find(); if (!$initial) throw new \InvalidArgumentException('充值退款申请不存在'); $status = strtoupper((string)($data['refund_status'] ?? $data['status'] ?? '')); if (!in_array($status, ['SUCCESS','PROCESSING','CLOSED','ABNORMAL'], true)) throw new \InvalidArgumentException('微信退款状态无效'); Db::startTrans(); try { $user = Db::name('user')->where('id', (int)$initial['user_id'])->lock(true)->find(); $pay = Db::name('pay_order')->where('id', (int)$initial['pay_order_id'])->lock(true)->find(); $refund = Db::name('recharge_refund')->where('id', (int)$initial['id'])->lock(true)->find(); if (!$user || !$pay || !$refund || $pay['scene'] !== 'recharge') throw new \RuntimeException('退款关联数据不存在'); if (in_array($refund['status'], ['success','closed'], true)) { if ($status !== 'PROCESSING' && strtolower($status) !== $refund['status']) throw new \RuntimeException('退款终态不一致,请人工核查'); if ($status === 'SUCCESS' && ((string)($data['refund_id'] ?? '') !== (string)$refund['wx_refund_id'] || (int)($data['amount']['refund'] ?? 0) !== (int)round((float)$refund['amount'] * 100) || (int)($data['amount']['total'] ?? 0) !== (int)round((float)$pay['amount'] * 100))) throw new \InvalidArgumentException('重复退款通知与原记录不一致'); Db::commit(); return $refund; } if (!in_array($refund['status'], ['submitting','unknown','processing','abnormal'], true)) throw new \RuntimeException('退款尚未提交微信'); $now = time(); $update = ['status'=>strtolower($status), 'wx_refund_id'=>(string)($data['refund_id'] ?? ''), 'updatetime'=>$now]; if ($status === 'SUCCESS') { $fen = (int)round((float)$refund['amount'] * 100); if (empty($data['refund_id']) || (int)($data['amount']['refund'] ?? 0) !== $fen || (int)($data['amount']['total'] ?? 0) !== (int)round((float)$pay['amount'] * 100)) throw new \RuntimeException('微信退款金额或单号不匹配'); $total = (int)round((float)$pay['refund_amount'] * 100) + $fen; if ($total > (int)round((float)$pay['amount'] * 100)) throw new \RuntimeException('累计退款超过充值金额'); Db::name('pay_order')->where('id', (int)$pay['id'])->update(['refund_amount'=>number_format($total / 100, 2, '.', ''),'status'=>$total === (int)round((float)$pay['amount'] * 100) ? 'refunded' : 'paid','refund_status'=>'success','refund_no'=>$refundNo,'refund_id'=>$data['refund_id'],'refund_time'=>$now,'updatetime'=>$now]); } elseif ($status === 'CLOSED') { $balance = number_format(((int)round((float)$user['money'] * 100) + (int)round((float)$refund['amount'] * 100)) / 100, 2, '.', ''); Db::name('user')->where('id', (int)$user['id'])->update(['money'=>$balance,'updatetime'=>$now]); Db::name('wallet_log')->insert(['user_type'=>'user','user_id'=>(int)$user['id'],'type'=>'recharge_refund_release','amount'=>$refund['amount'],'balance'=>$balance,'order_id'=>0,'remark'=>'充值退款关闭释放余额(退款单 '.$refundNo.')','createtime'=>$now]); } Db::name('recharge_refund')->where('id', (int)$refund['id'])->update($update); Db::commit(); return Db::name('recharge_refund')->where('id', (int)$refund['id'])->find(); } catch (\Throwable $e) { Db::rollback(); throw $e; } } public static function sync($id) { $refund = Db::name('recharge_refund')->where('id', (int)$id)->find(); if (!$refund || !in_array($refund['status'], ['submitting','unknown','processing','abnormal'], true)) throw new \InvalidArgumentException('当前状态不支持查询'); $wx = new WxPayV3Service(); return self::applyResult($refund['refund_no'], $wx->queryRefundByOutRefundNo($refund['refund_no'])); } public static function send($id) { $lock = 'yjyf_recharge_refund_' . (int)$id; $rows = Db::query('SELECT GET_LOCK(?, 2) AS acquired', [$lock]); if (empty($rows) || (int)$rows[0]['acquired'] !== 1) throw new \RuntimeException('退款正在处理中'); try { $refund = Db::name('recharge_refund')->where('id', (int)$id)->find(); if (!$refund || !in_array($refund['status'], ['submitting','unknown'], true)) throw new \InvalidArgumentException('当前状态不支持提交'); $pay = Db::name('pay_order')->where('id', (int)$refund['pay_order_id'])->find(); if (!$pay || $pay['scene'] !== 'recharge') throw new \RuntimeException('充值订单不存在'); $wx = new WxPayV3Service(); if ($refund['status'] === 'unknown') { try { return self::applyResult($refund['refund_no'], $wx->queryRefundByOutRefundNo($refund['refund_no'])); } catch (\Throwable $e) { $failure = WxPayV3Service::extractFailInfo($e); if (($failure['code'] ?? '') !== 'RESOURCE_NOT_EXISTS') throw $e; } } try { $data = $wx->refund(['out_trade_no'=>$pay['out_trade_no'],'out_refund_no'=>$refund['refund_no'],'refund_amount'=>$refund['amount'],'total_amount'=>$pay['amount'],'reason'=>$refund['reason']]); } catch (\Throwable $e) { Db::name('recharge_refund')->where('id', (int)$id)->whereIn('status', ['submitting','unknown'])->update(['status'=>'unknown','error'=>mb_substr($e->getMessage(),0,500),'updatetime'=>time()]); throw $e; } return self::applyResult($refund['refund_no'], $data); } finally { Db::query('SELECT RELEASE_LOCK(?)', [$lock]); } } public static function reject($refundId, $reviewerId, $note) { $note = trim((string)$note); if ($note === '' || mb_strlen($note) > 255 || (int)$reviewerId <= 0) throw new \InvalidArgumentException('请填写驳回原因'); $initial = Db::name('recharge_refund')->where('id', (int)$refundId)->find(); if (!$initial) throw new \InvalidArgumentException('退款申请不存在'); Db::startTrans(); try { $user = Db::name('user')->where('id', (int)$initial['user_id'])->lock(true)->find(); $refund = Db::name('recharge_refund')->where('id', (int)$refundId)->lock(true)->find(); if (!$user || !$refund || $refund['status'] !== 'pending') throw new \InvalidArgumentException('当前状态不允许驳回'); $balance = number_format(((int)round((float)$user['money'] * 100) + (int)round((float)$refund['amount'] * 100)) / 100, 2, '.', ''); $now = time(); Db::name('user')->where('id', (int)$user['id'])->update(['money'=>$balance,'updatetime'=>$now]); Db::name('wallet_log')->insert(['user_type'=>'user','user_id'=>(int)$user['id'],'type'=>'recharge_refund_release','amount'=>$refund['amount'],'balance'=>$balance,'order_id'=>0,'remark'=>'充值退款驳回释放余额(退款单 '.$refund['refund_no'].')','createtime'=>$now]); Db::name('recharge_refund')->where('id', (int)$refundId)->update(['status'=>'rejected','reviewer_id'=>(int)$reviewerId,'audit_note'=>$note,'updatetime'=>$now]); Db::commit(); } catch (\Throwable $e) { Db::rollback(); throw $e; } } }