feat: 新增师傅入驻审核与接单状态联动功能

- 新增师傅资质审核模块及权限
- 未审核通过的师傅默认禁用接单状态
- 新增售后退款申诉功能与相关界面
- 新增用户钱包管理及充值功能
- 更新服务定价矩阵相关数据库结构
- 修复微信支付证书验证问题
这个提交包含在:
2026-11-17 10:28:01 +08:00
父节点 ad73da1db4
当前提交 0370cb9bd6
共有 107 个文件被更改,包括 13666 次插入 和 1447 次删除

查看文件

@@ -65,6 +65,17 @@ class FinanceConfigService
'wx_job_type' => '上门安装维修师傅',
'wx_reward_desc' => '平台工单安装维修劳务报酬',
'wx_transfer_remark' => '工单安装维修服务劳务报酬',
// 用户钱包充值配置与展示规则
'recharge_enabled' => '1',
'recharge_close_tip' => '平台充值通道维护升级中,暂不支持充值,请直接使用微信支付下单',
'recharge_presets' => '50,100,200,500,1000,2000',
'recharge_default_preset' => '100',
'recharge_min_amount' => '0.01',
'recharge_max_amount' => '50000.00',
'recharge_daily_limit' => '100000.00',
'recharge_sub_tip' => '余额可用于平台所有家居卫浴、灯具家电等上门安装与维修工单支付,资金安全实时到账。',
'recharge_rule_text' => "【资金用途与性质】\n本充值款项系用于预付平台各项上门家居安装、维修、测量及拆旧等线下实体生活服务劳务款,不属于任何形式的网络虚拟货币或数字代币。\n\n【资金安全与到账】\n充值款项通过微信官方安全支付,支付成功后实时计入账户可用余额,资金流向透明合规。\n\n【工单抵扣与结算】\n账户余额全平台通用,支持抵扣一口价安装工单、上门核价尾款及现场服务增项补差价。\n\n【工单退款保障】\n使用余额支付的工单,如发生协商取消或售后退款,款项将在完结后原路全额退回至您的账户可用余额。\n\n【发票开具说明】\n账户预存充值行为本身不直接开具发票;待实际工单完工消费后,您可随时在「发票管理」按真实消费金额申请开具增值税电子普通发票。\n\n【合规服务承诺】\n平台严格遵守《中华人民共和国消费者权益保护法》及商业预付消费监管相关规定,账户余额不设有效期,保障用户合法权益。",
];
}
@@ -120,6 +131,42 @@ class FinanceConfigService
];
}
/**
* 获取结构化的用户钱包充值与规则配置
*/
public static function getRechargeConfig(): array
{
$all = self::getAll();
$rawPresets = array_filter(array_map('floatval', explode(',', (string)($all['recharge_presets'] ?? '50,100,200,500,1000,2000'))));
$presets = [];
foreach ($rawPresets as $p) {
if ($p > 0 && !in_array($p, $presets, true)) {
$presets[] = round($p, 2);
}
}
if (empty($presets)) {
$presets = [50, 100, 200, 500, 1000, 2000];
}
$defaultPreset = (float)($all['recharge_default_preset'] ?? 100);
if (!in_array($defaultPreset, $presets, true) && !empty($presets)) {
$defaultPreset = $presets[0];
}
return [
'enabled' => (int)($all['recharge_enabled'] ?? 1) === 1,
'close_tip' => (string)($all['recharge_close_tip'] ?? '平台充值通道维护升级中,暂不支持充值,请直接使用微信支付下单'),
'presets' => $presets,
'presets_str' => implode(',', $presets),
'default_preset' => $defaultPreset,
'min_amount' => round(max(0.01, (float)($all['recharge_min_amount'] ?? 0.01)), 2),
'max_amount' => round(max(1.00, (float)($all['recharge_max_amount'] ?? 50000.00)), 2),
'daily_limit' => round(max(0.00, (float)($all['recharge_daily_limit'] ?? 100000.00)), 2),
'sub_tip' => (string)($all['recharge_sub_tip'] ?? '余额可用于平台所有家居卫浴、灯具家电等上门安装与维修工单支付,资金安全实时到账。'),
'rule_text' => (string)($all['recharge_rule_text'] ?? "【资金用途与性质】\n本充值款项系用于预付平台各项上门家居安装、维修、测量及拆旧等线下实体生活服务劳务款,不属于任何形式的网络虚拟货币或数字代币。\n\n【资金安全与到账】\n充值款项通过微信官方安全支付,支付成功后实时计入账户可用余额,资金流向透明合规。\n\n【工单抵扣与结算】\n账户余额全平台通用,支持抵扣一口价安装工单、上门核价尾款及现场服务增项补差价。\n\n【工单退款保障】\n使用余额支付的工单,如发生协商取消或售后退款,款项将在完结后原路全额退回至您的账户可用余额。\n\n【发票开具说明】\n账户预存充值行为本身不直接开具发票;待实际工单完工消费后,您可随时在「发票管理」按真实消费金额申请开具增值税电子普通发票。\n\n【合规服务承诺】\n平台严格遵守《中华人民共和国消费者权益保护法》及商业预付消费监管相关规定,账户余额不设有效期,保障用户合法权益。"),
];
}
/**
* 获取结构化的提现与微信小程序转账配置
*/
@@ -644,6 +691,63 @@ class FinanceConfigService
}
}
// 3. 校验用户钱包充值与规则配置
if (isset($input['recharge_enabled'])) {
$clean['recharge_enabled'] = (int)$input['recharge_enabled'] === 1 ? '1' : '0';
}
if (isset($input['recharge_close_tip'])) {
$clean['recharge_close_tip'] = mb_substr(trim((string)$input['recharge_close_tip']), 0, 100);
}
if (isset($input['recharge_presets'])) {
$rawPresets = array_filter(array_map('floatval', explode(',', (string)$input['recharge_presets'])));
$cleanPresets = [];
foreach ($rawPresets as $p) {
if ($p > 0 && !in_array($p, $cleanPresets, true)) {
$cleanPresets[] = round($p, 2);
}
}
if (empty($cleanPresets)) {
throw new \InvalidArgumentException('请至少填写一个充值快捷面额');
}
$clean['recharge_presets'] = implode(',', $cleanPresets);
}
if (isset($input['recharge_default_preset'])) {
$defAmt = round((float)$input['recharge_default_preset'], 2);
if ($defAmt < 0.01) {
throw new \InvalidArgumentException('默认选中充值面额必须大于 ¥0.00');
}
$clean['recharge_default_preset'] = number_format($defAmt, 2, '.', '');
}
if (isset($input['recharge_min_amount'])) {
$minA = round((float)$input['recharge_min_amount'], 2);
if ($minA < 0.01) {
throw new \InvalidArgumentException('单笔最低充值金额不能低于 ¥0.01');
}
$clean['recharge_min_amount'] = number_format($minA, 2, '.', '');
}
if (isset($input['recharge_max_amount'])) {
$maxA = round((float)$input['recharge_max_amount'], 2);
if ($maxA < 1.00) {
throw new \InvalidArgumentException('单笔最高充值金额不能低于 ¥1.00');
}
$clean['recharge_max_amount'] = number_format($maxA, 2, '.', '');
}
if (isset($clean['recharge_min_amount'], $clean['recharge_max_amount'])) {
if ((float)$clean['recharge_min_amount'] > (float)$clean['recharge_max_amount']) {
throw new \InvalidArgumentException('单笔最低充值金额不能大于最高充值金额');
}
}
if (isset($input['recharge_daily_limit'])) {
$dl = round((float)$input['recharge_daily_limit'], 2);
$clean['recharge_daily_limit'] = number_format(max(0, $dl), 2, '.', '');
}
if (isset($input['recharge_sub_tip'])) {
$clean['recharge_sub_tip'] = mb_substr(trim((string)$input['recharge_sub_tip']), 0, 200);
}
if (isset($input['recharge_rule_text'])) {
$clean['recharge_rule_text'] = mb_substr(trim((string)$input['recharge_rule_text']), 0, 1000);
}
$now = time();
Db::startTrans();
try {
@@ -651,7 +755,7 @@ class FinanceConfigService
if (!array_key_exists($name, $defaults)) {
continue;
}
$group = strpos($name, 'default_') === 0 || $name === 'include_diff_in_commission' ? 'commission' : 'withdraw';
$group = strpos($name, 'recharge_') === 0 ? 'recharge' : (strpos($name, 'default_') === 0 || $name === 'include_diff_in_commission' ? 'commission' : 'withdraw');
$exists = Db::name('finance_config')->where('name', $name)->find();
if ($exists) {
Db::name('finance_config')->where('id', (int)$exists['id'])->update([

查看文件

@@ -674,6 +674,7 @@ class PaymentService
$totalRefunded = 0.00;
foreach ($effectiveRows as $po) {
if ($po['status'] === 'refunded') {
// 已退满:直接累计已退金额(含此前部分退款累计)
$totalRefunded = round($totalRefunded + (float)$po['refund_amount'], 2);
continue;
}
@@ -682,10 +683,11 @@ class PaymentService
if ($synced['status'] === 'refund_failed') {
throw new \RuntimeException('历史退款单(' . $synced['refund_no'] . ')微信侧退款异常:' . $synced['fail_reason']);
}
$totalRefunded = round($totalRefunded + (float)$synced['amount'], 2);
// 以同步后流水的累计已退金额为准(准确支持部分退款累计)
$totalRefunded = round($totalRefunded + (float)$synced['refund_amount'], 2);
continue;
}
// paid 或 refund_failed 均发起/重试原路退款
// paid 或 refund_failed 均发起/重试原路退款(自动退该笔流水全部剩余可退金额)
$after = self::refundSinglePayOrder((int)$po['id'], $reason);
$totalRefunded = round($totalRefunded + (float)($after['refund_amount'] ?: $po['amount']), 2);
}
@@ -693,12 +695,127 @@ class PaymentService
return $totalRefunded;
}
/**
* 售后部分退款:按指定退款总额在订单名下有效支付流水间依次原路退回(必须在事务外部调用)
*
* 分配规则:优先退早期流水,单笔流水内先补足此前未退满的余额;
* 若目标金额为空/0 或 ≥ 全部可退余额,则等价于全额退款(退所有剩余)。
*
* @param int $orderId 业务订单 ID
* @param float|null $targetAmount 本次售后退款总额(null/0 = 全额退款)
* @param string $reason 退款原因
* @return array ['refunded_total'=>本次实际退款金额, 'order_refunded'=>订单累计已退金额]
*/
public static function refundOrderPartial($orderId, $targetAmount = null, $reason = '平台售后原路退款')
{
$orderId = (int)$orderId;
$order = Db::name('order')->where('id', $orderId)->find();
if (!$order) {
throw new \InvalidArgumentException('业务订单不存在,无法核对退款流水');
}
if ((int)$order['pay_status'] !== 1) {
throw new \InvalidArgumentException('该订单不是已支付状态(当前支付状态:' . ((int)$order['pay_status'] === 2 ? '已退款' : '未支付') . '),无需退款');
}
if ((int)$order['settle_status'] === 1) {
throw new \InvalidArgumentException('该工单已完成向师傅结算分账,不允许售后退款(请先与师傅线下协商追回)');
}
$allPayOrders = Db::name('pay_order')
->where('order_id', $orderId)
->order('id asc')
->select();
// 有效已付款流水(与 refundOrder 同口径)
$effectiveRows = [];
foreach ($allPayOrders as $po) {
if (in_array($po['status'], ['paid', 'refunding', 'refunded', 'refund_failed'], true)) {
$effectiveRows[] = $po;
}
}
$orderPayAmount = round((float)$order['pay_amount'], 2);
$orderPayType = trim((string)$order['pay_type']);
$orderTxId = trim((string)$order['transaction_id']);
if (empty($effectiveRows)) {
if ($orderPayType === 'mock' || $orderPayType === 'monthly'
|| strpos($orderTxId, 'MOCK') === 0 || strpos($orderTxId, 'MONTHLY') === 0) {
throw new \InvalidArgumentException('该订单为非微信支付渠道(' . ($orderPayType ?: 'mock') . ')订单,无需也无法通过微信原路退款,请线下人工处理');
}
$errMsg = '订单状态为已支付(支付渠道:' . ($orderPayType ?: '未记录') . ',实付 ¥' . $orderPayAmount . '),但在支付流水表 fa_pay_order 中未查询到有效的微信支付交易单,为严防未向微信退款导致资金未原路退回,系统已拦截本次退款,请管理员先核查微信商户平台交易记录';
self::addOrderLog($orderId, (int)$order['status'], '【拦截假退款】' . $errMsg, 'system', 0);
Log::error("[PaymentService::refundOrderPartial] 缺少微信支付流水拦截退款 order_id={$orderId}, pay_type={$orderPayType}");
throw new \RuntimeException($errMsg);
}
// 计算订单级可退余额(各有效流水可退余额之和)
$orderRefundable = 0.00;
$orderRefunded = 0.00;
foreach ($effectiveRows as $po) {
$orderRefundable = round($orderRefundable + round((float)$po['amount'] - (float)$po['refund_amount'], 2), 2);
$orderRefunded = round($orderRefunded + (float)$po['refund_amount'], 2);
}
if ($orderRefundable <= 0) {
throw new \InvalidArgumentException('该订单的支付流水已全部退款,无可退余额');
}
$target = $targetAmount === null ? 0 : round((float)$targetAmount, 2);
if ($target < 0) {
throw new \InvalidArgumentException('退款金额不能为负数');
}
// 目标为 0 或 ≥ 可退余额时按全额剩余退款处理
$remainingTarget = ($target > 0 && $target < $orderRefundable) ? $target : $orderRefundable;
if ($remainingTarget < 0.01) {
throw new \InvalidArgumentException('退款金额不能低于 ¥0.01');
}
$thisRefunded = 0.00;
foreach ($effectiveRows as $po) {
if (round($remainingTarget, 2) <= 0) {
break;
}
if ($po['status'] === 'refunded') {
continue;
}
if ($po['status'] === 'refunding') {
// 在途退款单先同步微信侧状态,避免重复发起;同步后若仍异常则终止并提示人工核查
$synced = self::syncRefundPayOrder((int)$po['id']);
if (in_array($synced['status'], ['paid', 'refund_failed'], true)) {
$po = $synced;
} else {
$orderRefunded = round($orderRefunded + (float)$synced['refund_amount'], 2);
continue;
}
}
$refundable = round((float)$po['amount'] - (float)$po['refund_amount'], 2);
if ($refundable <= 0) {
continue;
}
$part = round(min($remainingTarget, $refundable), 2);
if ($part < 0.01) {
continue;
}
$after = self::refundSinglePayOrder((int)$po['id'], $reason, $part);
$thisRefunded = round($thisRefunded + ((float)$after['refund_amount'] - (float)$po['refund_amount']), 2);
$orderRefunded = round($orderRefunded + ((float)$after['refund_amount'] - (float)$po['refund_amount']), 2);
$remainingTarget = round($remainingTarget - ((float)$after['refund_amount'] - (float)$po['refund_amount']), 2);
}
return [
'refunded_total' => round($thisRefunded, 2),
'order_refunded' => round($orderRefunded, 2),
];
}
/**
* 对单笔 fa_pay_order 执行微信 V3 原路退款(事务外远程调用 + 状态/失败原因持久落库)
*
* @param int $payOrderId 支付流水 ID
* @param string $reason 退款原因
* @param float|null $partialAmount 本次退款金额(null/0 = 退该笔流水的全部剩余可退金额)
* @return array 更新后的 pay_order 记录
*/
public static function refundSinglePayOrder($payOrderId, $reason = '订单取消原路退款')
public static function refundSinglePayOrder($payOrderId, $reason = '订单取消原路退款', $partialAmount = null)
{
$po = Db::name('pay_order')->where('id', (int)$payOrderId)->find();
if (!$po) {
@@ -714,17 +831,37 @@ class PaymentService
throw new \InvalidArgumentException('当前支付单状态(' . self::payOrderStatusLabel($po['status']) . ')不允许发起退款');
}
$amount = round((float)$po['amount'], 2);
if ($amount <= 0) {
throw new \InvalidArgumentException('退款金额必须大于 0');
// 可退余额 = 流水支付总额 - 已累计成功退款金额(支持一笔流水多次部分退款)
$payTotal = round((float)$po['amount'], 2);
$refundable = round($payTotal - round((float)$po['refund_amount'], 2), 2);
if ($refundable <= 0) {
throw new \InvalidArgumentException('该支付流水的可退余额为 0,无需再次退款');
}
$partialAmount = $partialAmount === null ? 0 : round((float)$partialAmount, 2);
if ($partialAmount < 0) {
throw new \InvalidArgumentException('退款金额不能为负数');
}
// 本次退款金额:指定部分金额(不得超过可退余额)或全部剩余
$amount = $partialAmount > 0 ? round(min($partialAmount, $refundable), 2) : $refundable;
if ($amount < 0.01) {
throw new \InvalidArgumentException('退款金额不能低于 ¥0.01(微信商家转账硬性规定实退最低 ¥0.10,请核对金额)');
}
// 若为纯余额支付单据(openid 为 BALANCE 或 out_trade_no 为 BAL 开头),执行账户余额原路退还闭环,严禁向微信发起退款
if ($po['openid'] === 'BALANCE' || strpos((string)$po['out_trade_no'], 'BAL') === 0) {
return self::refundBalancePayOrder($po, $amount, $reason);
}
$wxSvc = new WxPayV3Service();
$refundNo = trim((string)$po['refund_no']);
$now = time();
// 若上一笔单据微信侧已返回明确终态异常/关闭(abnormal/closed),或此前退款失败,先核实微信侧旧单状态再决定复用或换号重退
if ($refundNo !== '' && in_array($po['refund_status'], ['abnormal', 'closed'], true)) {
// 需要换新退款单号的场景:
// 1) 上一笔退款单微信侧已返回明确终态异常/关闭(abnormal/closed),或此前退款失败;
// 2) 该流水已发生过部分退款且成功(refund_amount>0 且仍为 paid),必须生成递增新号,严禁复用旧退款单号
$needNewNo = ($refundNo !== '' && in_array($po['refund_status'], ['abnormal', 'closed'], true))
|| ($refundNo !== '' && round((float)$po['refund_amount'], 2) > 0 && $po['status'] === 'paid');
if ($needNewNo) {
$suffixPos = strrpos($refundNo, 'R');
$nextVer = 1;
$baseNo = $refundNo;
@@ -756,7 +893,7 @@ class PaymentService
'out_trade_no' => (string)$po['out_trade_no'],
'out_refund_no' => $refundNo,
'refund_amount' => $amount,
'total_amount' => $amount,
'total_amount' => $payTotal,
'reason' => $reason,
]);
} catch (\Throwable $e) {
@@ -810,6 +947,10 @@ class PaymentService
/**
* 统一应用微信退款查单 / 申请 / 异步回调结果(准确区分 SUCCESS / PROCESSING / ABNORMAL / CLOSED)
*
* 退款金额语义:refund_amount 字段始终记录该流水"累计已成功退款金额"。
* 一笔支付流水支持多次部分退款:每次 SUCCESS 时按报文退款金额累加,
* 累计退满后流水状态置为 refunded,未退满则保持 paid 可继续发起退款。
*/
public static function applyWxRefundResult(array $po, array $wxRefundData, $fallbackAmount = 0.00)
{
@@ -820,27 +961,37 @@ class PaymentService
$refundId = trim((string)($wxRefundData['refund_id'] ?? $po['refund_id']));
$now = time();
$amount = round((float)$po['amount'], 2) ?: round((float)$fallbackAmount, 2);
if (isset($wxRefundData['amount']['refund']) && (int)$wxRefundData['amount']['refund'] > 0) {
$amount = round(((int)$wxRefundData['amount']['refund']) / 100, 2);
$payTotal = round((float)$po['amount'], 2);
// 本次微信退款单的退款金额(优先取微信报文,缺失时用申请时金额兜底)
$thisRefund = round(((int)($wxRefundData['amount']['refund'] ?? 0)) / 100, 2);
if ($thisRefund <= 0) {
$thisRefund = round((float)$fallbackAmount, 2);
}
// 此前已完成的部分退款累计(PROCESSING 阶段不写入本次金额,避免同步到账后重复累计)
$prevRefunded = round((float)$po['refund_amount'], 2);
if ($wxStatus === 'SUCCESS') {
$succTime = !empty($wxRefundData['success_time'])
? (strtotime((string)$wxRefundData['success_time']) ?: $now)
: $now;
// 累计本次到账退款金额,判断是否已退满整笔流水
$refundedTotal = round($prevRefunded + $thisRefund, 2);
$isFullyRefunded = $refundedTotal >= ($payTotal - 0.005);
Db::name('pay_order')->where('id', (int)$po['id'])->update([
'status' => 'refunded',
'status' => $isFullyRefunded ? 'refunded' : 'paid',
'refund_status' => 'success',
'refund_id' => $refundId,
'refund_amount' => $amount,
'refund_amount' => $refundedTotal,
'refund_time' => $succTime,
'fail_code' => '',
'fail_reason' => '',
'last_sync_time' => $now,
'updatetime' => $now,
]);
self::addOrderLog((int)$po['order_id'], 0, '微信原路退款已到账(退款单 ' . $po['refund_no'] . ',金额 ¥' . $amount . ')', 'system', 0);
$refundTip = $isFullyRefunded
? '微信原路退款已到账(退款单 ' . $po['refund_no'] . ',本次 ¥' . $thisRefund . ',累计 ¥' . $refundedTotal . ',已退满)'
: '微信原路部分退款已到账(退款单 ' . $po['refund_no'] . ',本次 ¥' . $thisRefund . ',累计 ¥' . $refundedTotal . '/¥' . $payTotal . ',剩余 ¥' . round($payTotal - $refundedTotal, 2) . ' 可退)';
self::addOrderLog((int)$po['order_id'], 0, $refundTip, 'system', 0);
return Db::name('pay_order')->where('id', (int)$po['id'])->find();
}
@@ -849,7 +1000,7 @@ class PaymentService
'status' => 'refunding',
'refund_status' => 'processing',
'refund_id' => $refundId,
'refund_amount' => $amount,
'refund_amount' => $prevRefunded,
'fail_code' => '',
'fail_reason' => '',
'last_sync_time' => $now,
@@ -1920,4 +2071,468 @@ class PaymentService
Db::name('message')->insertAll($rows);
}
}
/**
* 创建用户端微信支付充值单(APIv3 JSAPI)
*
* @param int $userId 用户ID
* @param float $amount 充值金额
* @param string $wxCode 微信登录凭证 code
* @return array
*/
public static function createRechargeJsapiPay($userId, $amount, $wxCode = '')
{
$userId = (int)$userId;
$amount = round((float)$amount, 2);
if ($userId <= 0) {
throw new \InvalidArgumentException('用户未登录或用户ID无效');
}
$rcCfg = FinanceConfigService::getRechargeConfig();
if (!$rcCfg['enabled']) {
throw new \InvalidArgumentException($rcCfg['close_tip'] ?: '充值通道维护中,暂不支持充值');
}
if ($amount < $rcCfg['min_amount']) {
throw new \InvalidArgumentException('单笔充值金额不能低于 ¥' . number_format($rcCfg['min_amount'], 2, '.', ''));
}
if ($amount > $rcCfg['max_amount']) {
throw new \InvalidArgumentException('单笔充值金额不能高于 ¥' . number_format($rcCfg['max_amount'], 2, '.', ''));
}
$openid = self::resolveUserOpenid($userId, $wxCode);
$wxSvc = new WxPayV3Service();
$now = time();
$outTradeNo = 'RC' . date('YmdHis', $now) . str_pad((string)mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
$payOrderId = Db::name('pay_order')->insertGetId([
'out_trade_no' => $outTradeNo,
'order_id' => 0,
'order_no' => '',
'batch_no' => '',
'user_id' => $userId,
'scene' => 'recharge',
'quote_id' => 0,
'openid' => $openid,
'amount' => $amount,
'status' => 'pending',
'createtime' => $now,
'updatetime' => $now,
]);
$description = '优匠优服-服务款在线充值';
try {
$wxResp = $wxSvc->createJsapiOrder([
'out_trade_no' => $outTradeNo,
'description' => $description,
'amount' => $amount,
'openid' => $openid,
'attach' => json_encode([
'scene' => 'recharge',
'user_id' => $userId,
], JSON_UNESCAPED_UNICODE),
]);
$prepayId = trim((string)($wxResp['prepay_id'] ?? ''));
if ($prepayId === '') {
throw new \RuntimeException('微信统一下单未返回有效 prepay_id');
}
Db::name('pay_order')->where('id', $payOrderId)->update([
'prepay_id' => $prepayId,
'updatetime' => time(),
]);
return [
'out_trade_no' => $outTradeNo,
'amount' => $amount,
'pay_params' => $wxResp['pay_params'],
'need_wxpay' => true,
'paid' => false,
];
} catch (\Throwable $e) {
$fail = WxPayV3Service::extractFailInfo($e);
Db::name('pay_order')->where('id', $payOrderId)->update([
'status' => 'pay_failed',
'fail_code' => $fail['code'],
'fail_reason' => $fail['reason'],
'updatetime' => time(),
]);
Log::error("[PaymentService::createRechargeJsapiPay] 统一下单失败 out_trade_no={$outTradeNo}, err=" . $e->getMessage());
throw $e;
}
}
/**
* 确认并核销微信充值单(支持小程序端主动查单与微信回调异步通知,保证幂等)
*
* @param string $outTradeNo
* @param array|null $wxTxData
* @return array
*/
public static function confirmRechargePay($outTradeNo, ?array $wxTxData = null)
{
$outTradeNo = trim((string)$outTradeNo);
if ($outTradeNo === '') {
throw new \InvalidArgumentException('缺少充值单号 out_trade_no');
}
$payOrder = Db::name('pay_order')->where('out_trade_no', $outTradeNo)->find();
if (!$payOrder) {
throw new \InvalidArgumentException('充值支付单不存在');
}
if ($payOrder['status'] === 'paid') {
return [
'paid' => true,
'already_processed' => true,
'amount' => (float)$payOrder['amount'],
'user_id' => (int)$payOrder['user_id'],
];
}
$wxSvc = new WxPayV3Service();
if ($wxTxData === null) {
$wxTxData = $wxSvc->queryOrderByOutTradeNo($outTradeNo);
}
$tradeState = strtoupper((string)($wxTxData['trade_state'] ?? ''));
if ($tradeState !== 'SUCCESS') {
$stateDesc = self::tradeStateLabel($tradeState, (string)($wxTxData['trade_state_desc'] ?? ''));
throw new \RuntimeException('微信侧支付未完成,当前状态:' . $stateDesc);
}
$wxTotalFen = (int)($wxTxData['amount']['total'] ?? 0);
$expectedFen = (int)round((float)$payOrder['amount'] * 100);
if ($wxTotalFen !== $expectedFen) {
throw new \RuntimeException('微信实付金额与充值单金额不一致,拦截充值加款');
}
$now = time();
$txId = (string)($wxTxData['transaction_id'] ?? '');
Db::startTrans();
try {
$lockedPay = Db::name('pay_order')->where('id', (int)$payOrder['id'])->lock(true)->find();
if ($lockedPay['status'] === 'paid') {
Db::commit();
return ['paid' => true, 'already_processed' => true, 'amount' => (float)$lockedPay['amount']];
}
$uid = (int)$lockedPay['user_id'];
$lockedUser = Db::name('user')->where('id', $uid)->lock(true)->find();
if (!$lockedUser) {
throw new \RuntimeException('充值目标用户不存在');
}
$rechargeAmt = round((float)$lockedPay['amount'], 2);
$newBalance = round((float)$lockedUser['money'] + $rechargeAmt, 2);
// 1. 增加用户余额
Db::name('user')->where('id', $uid)->update([
'money' => $newBalance,
'updatetime' => $now,
]);
// 2. 写入资金流水
Db::name('wallet_log')->insert([
'user_type' => 'user',
'user_id' => $uid,
'type' => 'recharge',
'amount' => $rechargeAmt,
'balance' => $newBalance,
'order_id' => 0,
'remark' => '微信在线充值 (单号: ' . $outTradeNo . ')',
'createtime' => $now,
]);
// 3. 更新支付单状态
Db::name('pay_order')->where('id', (int)$lockedPay['id'])->update([
'status' => 'paid',
'transaction_id' => $txId,
'pay_time' => $now,
'last_sync_time' => $now,
'updatetime' => $now,
]);
// 4. 发送系统通知
self::sendNotify('user', $uid, '充值成功', '您的账户成功在线充值 ¥' . number_format($rechargeAmt, 2, '.', '') . ',当前可用余额为 ¥' . number_format($newBalance, 2, '.', '') . '。', 'system', 0);
Db::commit();
return [
'paid' => true,
'amount' => $rechargeAmt,
'balance' => $newBalance,
'out_trade_no' => $outTradeNo,
];
} catch (\Throwable $e) {
Db::rollback();
Log::error("[PaymentService::confirmRechargePay] 核销失败 out_trade_no={$outTradeNo}, err=" . $e->getMessage());
throw $e;
}
}
/**
* 用户使用账户可用余额全额支付工单(首付款 / 选报价 / 增项补差价)
*/
public static function payOrderByBalance(array $order, $operatorUid, $scene = 'order', $quoteId = 0)
{
$orderId = (int)$order['id'];
$operatorUid = (int)$operatorUid;
$quoteId = (int)$quoteId;
$now = time();
if (!in_array($scene, ['order', 'quote', 'diff'], true)) {
throw new \InvalidArgumentException('不支持的余额支付场景');
}
$payAmount = 0.00;
$remark = '';
$quote = null;
$masterId = 0;
if ($scene === 'order') {
if ((int)$order['pay_status'] === 1) {
throw new \InvalidArgumentException('订单已支付,请勿重复支付');
}
if ((int)$order['status'] !== OrderStatus::PENDING_PAY) {
throw new \InvalidArgumentException('当前订单状态不允许支付');
}
$payAmount = round((float)$order['pay_amount'], 2);
$remark = '订单余额支付 (单号: ' . $order['order_no'] . ')';
} elseif ($scene === 'quote') {
if ($order['price_type'] !== 'quote') {
throw new \InvalidArgumentException('该订单不是师傅报价订单');
}
if ((int)$order['status'] !== OrderStatus::QUOTING) {
throw new \InvalidArgumentException('当前状态不可选择报价');
}
if ((int)$order['master_id'] > 0) {
throw new \InvalidArgumentException('该订单已选定师傅,请勿重复选择');
}
$quote = Db::name('order_quote')->where('id', $quoteId)->where('order_id', $orderId)->find();
if (!$quote || $quote['status'] !== 'wait') {
throw new \InvalidArgumentException('报价已失效,请重新选择');
}
$quoteAmount = round((float)$quote['amount'], 2);
$targetTotalPay = max(0, round($quoteAmount - (float)$order['discount_amount'], 2));
$alreadyPaid = (int)$order['pay_status'] === 1 ? (float)$order['pay_amount'] : 0.00;
$payAmount = max(0, round($targetTotalPay - $alreadyPaid, 2));
$remark = '选定师傅报价余额支付 (单号: ' . $order['order_no'] . ')';
$masterId = (int)$quote['master_id'];
} elseif ($scene === 'diff') {
if ((int)$order['diff_status'] !== 1 || (float)$order['diff_amount'] <= 0) {
throw new \InvalidArgumentException('当前订单无待支付的增项补差价');
}
$payAmount = round((float)$order['diff_amount'], 2);
$remark = '施工增项补差价余额支付 (单号: ' . $order['order_no'] . ')';
}
// 若无需支付(例如0元差额),直接走0元核销逻辑
if ($payAmount <= 0) {
if ($scene === 'quote') {
return self::completeZeroQuoteChoose($orderId, $quoteId, $operatorUid);
}
return self::completeZeroOrderPay($orderId, $operatorUid);
}
$outTradeNo = 'BAL' . date('YmdHis', $now) . str_pad((string)mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
Db::startTrans();
try {
$lockedUser = Db::name('user')->where('id', $operatorUid)->lock(true)->find();
if (!$lockedUser) {
throw new \RuntimeException('付款用户不存在');
}
$userMoney = (float)$lockedUser['money'];
if ($userMoney < $payAmount) {
throw new \InvalidArgumentException('账户可用余额不足(当前余额 ¥' . number_format($userMoney, 2, '.', '') . ',需支付 ¥' . number_format($payAmount, 2, '.', '') . '),请先充值或切换微信支付');
}
$lockedOrder = Db::name('order')->where('id', $orderId)->lock(true)->find();
if (!$lockedOrder) {
throw new \RuntimeException('订单不存在');
}
$newBalance = round($userMoney - $payAmount, 2);
// 1. 扣减用户余额
Db::name('user')->where('id', $operatorUid)->update([
'money' => $newBalance,
'updatetime' => $now,
]);
// 2. 写入全局资金流水
Db::name('wallet_log')->insert([
'user_type' => 'user',
'user_id' => $operatorUid,
'type' => 'consume',
'amount' => -$payAmount,
'balance' => $newBalance,
'order_id' => $orderId,
'remark' => $remark,
'createtime' => $now,
]);
// 3. 写入支付单记录(标记 openid = 'BALANCE' 便于对账与原路退还)
Db::name('pay_order')->insert([
'out_trade_no' => $outTradeNo,
'order_id' => $orderId,
'order_no' => $lockedOrder['order_no'],
'batch_no' => '',
'user_id' => $operatorUid,
'scene' => $scene,
'quote_id' => $quoteId,
'openid' => 'BALANCE',
'amount' => $payAmount,
'status' => 'paid',
'transaction_id' => $outTradeNo,
'pay_time' => $now,
'createtime' => $now,
'updatetime' => $now,
]);
// 4. 推进订单状态
if ($scene === 'order') {
self::lockAndConsumeOrderCoupon($lockedOrder, $now);
$isDirect = ($lockedOrder['master_id'] > 0);
$nextStatus = $isDirect ? OrderStatus::SCHEDULED : OrderStatus::PENDING_ACCEPT;
Db::name('order')->where('id', $orderId)->update([
'pay_status' => 1,
'pay_type' => 'balance',
'transaction_id' => $outTradeNo,
'pay_time' => $now,
'status' => $nextStatus,
'updatetime' => $now,
]);
self::addOrderLog($orderId, $nextStatus, '买家使用账户余额支付成功 ¥' . number_format($payAmount, 2, '.', ''), 'user', $operatorUid);
if (!$isDirect) {
self::broadcastNewOrderToMasters($lockedOrder);
}
} elseif ($scene === 'quote') {
Db::name('order_quote')->where('id', $quoteId)->update(['status' => 'selected']);
Db::name('order_quote')->where('order_id', $orderId)->where('id', '<>', $quoteId)->where('status', 'wait')->update(['status' => 'reject']);
$newPayTotal = round((float)$lockedOrder['pay_amount'] + $payAmount, 2);
Db::name('order')->where('id', $orderId)->update([
'master_id' => $masterId,
'pay_status' => 1,
'pay_type' => 'balance',
'transaction_id' => $outTradeNo,
'pay_time' => $now,
'pay_amount' => $newPayTotal,
'total_amount' => (float)$quote['amount'],
'status' => OrderStatus::SCHEDULED,
'updatetime' => $now,
]);
self::addOrderLog($orderId, OrderStatus::SCHEDULED, '买家选定师傅报价并使用余额支付差价 ¥' . number_format($payAmount, 2, '.', ''), 'user', $operatorUid);
self::sendMasterAndUserMessage($masterId, $operatorUid, '师傅已被选定', '客户已选定您的报价并完成支付,请及时预约上门');
} elseif ($scene === 'diff') {
$newPayTotal = round((float)$lockedOrder['pay_amount'] + $payAmount, 2);
$newTotalAmount = round((float)$lockedOrder['total_amount'] + $payAmount, 2);
Db::name('order')->where('id', $orderId)->update([
'diff_status' => 2,
'pay_amount' => $newPayTotal,
'total_amount' => $newTotalAmount,
'updatetime' => $now,
]);
self::addOrderLog($orderId, (int)$lockedOrder['status'], '买家使用账户余额支付增项补差价 ¥' . number_format($payAmount, 2, '.', ''), 'user', $operatorUid);
if ((int)$lockedOrder['master_id'] > 0) {
self::sendNotify('master', (int)$lockedOrder['master_id'], '增项差价已支付', '买家已通过余额支付施工现场增项补差价 ¥' . number_format($payAmount, 2, '.', ''), 'order', $orderId);
}
}
self::sendNotify('user', $operatorUid, '余额支付成功', '您已使用账户余额成功支付 ¥' . number_format($payAmount, 2, '.', '') . ',剩余可用余额为 ¥' . number_format($newBalance, 2, '.', '') . '。', 'order', $orderId);
Db::commit();
return [
'paid' => true,
'need_wxpay' => false,
'pay_type' => 'balance',
'amount' => $payAmount,
'balance' => $newBalance,
'out_trade_no' => $outTradeNo,
'order_id' => $orderId,
];
} catch (\Throwable $e) {
Db::rollback();
Log::error("[PaymentService::payOrderByBalance] 余额支付失败 order_id={$orderId}, err=" . $e->getMessage());
throw $e;
}
}
/**
* 纯余额支付单原路退回至用户账户余额
*/
protected static function refundBalancePayOrder(array $po, $amount, $reason = '订单取消/售后原路退款')
{
$amount = round((float)$amount, 2);
$payId = (int)$po['id'];
$uid = (int)$po['user_id'];
$now = time();
$refundNo = 'RF' . date('YmdHis', $now) . str_pad((string)$payId, 8, '0', STR_PAD_LEFT);
Db::startTrans();
try {
$lockedPo = Db::name('pay_order')->where('id', $payId)->lock(true)->find();
if (!$lockedPo) {
throw new \InvalidArgumentException('支付单记录不存在');
}
if ($lockedPo['status'] === 'refunded') {
Db::commit();
return $lockedPo;
}
$lockedUser = Db::name('user')->where('id', $uid)->lock(true)->find();
if (!$lockedUser) {
throw new \RuntimeException('退款目标用户不存在');
}
$currentRefunded = round((float)$lockedPo['refund_amount'], 2);
$newRefunded = round($currentRefunded + $amount, 2);
$payTotal = round((float)$lockedPo['amount'], 2);
$isFullyRefunded = ($newRefunded >= $payTotal);
// 1. 资金退回用户账户
$newBalance = round((float)$lockedUser['money'] + $amount, 2);
Db::name('user')->where('id', $uid)->update([
'money' => $newBalance,
'updatetime' => $now,
]);
// 2. 写入全局资金流水账本
$orderNo = $po['order_no'] ? (' (单号: ' . $po['order_no'] . ')') : '';
Db::name('wallet_log')->insert([
'user_type' => 'user',
'user_id' => $uid,
'type' => 'refund',
'amount' => $amount,
'balance' => $newBalance,
'order_id' => (int)$po['order_id'],
'remark' => '订单售后/取消原路退款' . $orderNo,
'createtime' => $now,
]);
// 3. 更新支付单状态
$updPo = [
'status' => $isFullyRefunded ? 'refunded' : 'paid',
'refund_no' => $refundNo,
'refund_id' => $refundNo,
'refund_amount' => $newRefunded,
'refund_status' => 'success',
'refund_time' => $now,
'updatetime' => $now,
];
Db::name('pay_order')->where('id', $payId)->update($updPo);
// 4. 发送退款入账系统通知
self::sendNotify('user', $uid, '退款到账通知', '您的订单已完成原路退款 ¥' . number_format($amount, 2, '.', '') . ',款项已实时返还至您的账户余额,当前可用余额为 ¥' . number_format($newBalance, 2, '.', '') . '。', 'order', (int)$po['order_id']);
Db::commit();
return array_merge($lockedPo, $updPo);
} catch (\Throwable $e) {
Db::rollback();
Log::error("[PaymentService::refundBalancePayOrder] 退回余额失败 pay_id={$payId}, err=" . $e->getMessage());
throw $e;
}
}
}

查看文件

@@ -30,9 +30,16 @@ class WxLogin
. '&secret=' . urlencode($secret)
. '&js_code=' . urlencode($code)
. '&grant_type=authorization_code';
$sslOpts = ['verify_peer' => true, 'verify_peer_name' => true];
$caFile = dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'addons' . DIRECTORY_SEPARATOR . 'epay' . DIRECTORY_SEPARATOR . 'certs' . DIRECTORY_SEPARATOR . 'cacert.pem';
if (@is_file($caFile)) {
$sslOpts['cafile'] = $caFile;
} elseif (@is_file('D:/Softwares/Git/usr/ssl/certs/ca-bundle.crt')) {
$sslOpts['cafile'] = 'D:/Softwares/Git/usr/ssl/certs/ca-bundle.crt';
}
$ctx = stream_context_create([
'http' => ['timeout' => 8, 'ignore_errors' => true],
'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
'ssl' => $sslOpts,
]);
$resp = @file_get_contents($url, false, $ctx);
if ($resp === false) {

查看文件

@@ -568,6 +568,11 @@ class WxPayV3Service
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$caPath = $this->resolveCaCertPath();
if ($caPath !== '') {
curl_setopt($ch, CURLOPT_CAINFO, $caPath);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $headerLine) use (&$respHeaders) {
$len = strlen($headerLine);
@@ -1078,4 +1083,40 @@ class WxPayV3Service
}
return $candidate;
}
/**
* 解析根 CA 证书路径(自愈 Windows / 服务器环境下 cURL 缺失根证书信任链导致 cURL 60 的问题)
*
* @return string 有效可读的 cacert.pem 绝对路径,未找到时返回空字符串
*/
protected function resolveCaCertPath()
{
$root = defined('ROOT_PATH') ? rtrim(ROOT_PATH, '/\\') : dirname(__DIR__, 3);
// 1. 优先加载项目内置官方 Mozilla CA 根证书包(addons/epay/certs/cacert.pem)
$local = $root . DIRECTORY_SEPARATOR . 'addons' . DIRECTORY_SEPARATOR . 'epay' . DIRECTORY_SEPARATOR . 'certs' . DIRECTORY_SEPARATOR . 'cacert.pem';
if (@is_file($local) && @is_readable($local)) {
return $local;
}
// 2. Windows 常见 Git 安装自带 CA 根证书包
$gitCa = 'D:/Softwares/Git/usr/ssl/certs/ca-bundle.crt';
if (@is_file($gitCa) && @is_readable($gitCa)) {
return $gitCa;
}
// 3. php.ini 中配置的 curl.cainfo
$iniCa = (string)ini_get('curl.cainfo');
if ($iniCa !== '' && @is_file($iniCa) && @is_readable($iniCa)) {
return $iniCa;
}
// 4. php.ini 中配置的 openssl.cafile
$sslCa = (string)ini_get('openssl.cafile');
if ($sslCa !== '' && @is_file($sslCa) && @is_readable($sslCa)) {
return $sslCa;
}
return '';
}
}