feat: 完善协议管理、师傅资质认证、分账配置并完成测试环境全量部署与同步
这个提交包含在:
文件差异内容过多而无法显示
加载差异
@@ -0,0 +1,558 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Db;
|
||||
|
||||
/**
|
||||
* 订单多维抽佣规则匹配与订单级快照核算服务
|
||||
*
|
||||
* 核心原则:
|
||||
* 1. 按订单维度灵活匹配:支持按【订单模式(一口价/报价/自主定价/区间) + 发单客群(个人/商家) + 服务类目 + 加急属性 + 订单金额阶梯】匹配 fa_commission_rule,支持按比例(%)、按单固定额(¥)、混合计佣及单笔保底/封顶。
|
||||
* 2. 创单完整快照隔离:订单创建时同时写入 fa_order.commission_rate 与 fa_order.commission_snapshot(JSON 快照,报价单同步固化创单时刻的金额阶梯候选快照 candidate_tiers)。
|
||||
* 3. 历史订单零干扰:选报价定档、施工增项结算、核销分账全部 100% 读取订单自身锁定的快照计算,后续后台增删改任何抽佣规则绝不影响历史已创订单。
|
||||
*/
|
||||
class CommissionService
|
||||
{
|
||||
const DEFAULT_RATE = 10.00;
|
||||
|
||||
/** @var array|null 请求内启用规则静态缓存 */
|
||||
protected static $activeRulesCache = null;
|
||||
|
||||
/**
|
||||
* 清空请求内规则缓存
|
||||
*/
|
||||
public static function clearCache(): void
|
||||
{
|
||||
self::$activeRulesCache = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化百分比数值至 [0.00, 100.00]
|
||||
*
|
||||
* @param mixed $rate
|
||||
* @return float
|
||||
*/
|
||||
public static function normalizeRate($rate): float
|
||||
{
|
||||
$val = round((float)$rate, 2);
|
||||
if ($val < 0.00) {
|
||||
return 0.00;
|
||||
}
|
||||
if ($val > 100.00) {
|
||||
return 100.00;
|
||||
}
|
||||
return $val;
|
||||
}
|
||||
|
||||
/**
|
||||
* 强校验百分比输入(0 ~ 100)
|
||||
*
|
||||
* @param mixed $raw
|
||||
* @return float
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function validateRateInput($raw): float
|
||||
{
|
||||
$str = trim((string)$raw);
|
||||
if ($str === '' || !is_numeric($str)) {
|
||||
throw new \InvalidArgumentException('请填写有效的抽佣比例数字(0 ~ 100)');
|
||||
}
|
||||
$val = (float)$str;
|
||||
if ($val < 0 || $val > 100) {
|
||||
throw new \InvalidArgumentException('抽佣比例必须在 0% ~ 100% 之间');
|
||||
}
|
||||
return round($val, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取全局默认兜底抽佣比例(%)
|
||||
*/
|
||||
public static function getGlobalRate(): float
|
||||
{
|
||||
$defaults = FinanceConfigService::getCommissionDefaults();
|
||||
return self::normalizeRate($defaults['commission_rate'] ?? self::DEFAULT_RATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算单条规则的条件精确度得分(相同权重 weigh 时,条件越具体越优先命中)
|
||||
*/
|
||||
protected static function calcSpecificity(array $rule): int
|
||||
{
|
||||
$score = 0;
|
||||
if ((int)($rule['cat_id'] ?? 0) > 0) {
|
||||
$score += 16;
|
||||
}
|
||||
if (($rule['customer_type'] ?? 'all') !== 'all') {
|
||||
$score += 8;
|
||||
}
|
||||
if (($rule['order_mode'] ?? 'all') !== 'all') {
|
||||
$score += 4;
|
||||
}
|
||||
if (($rule['urgent_mode'] ?? 'all') !== 'all') {
|
||||
$score += 2;
|
||||
}
|
||||
if ((float)($rule['min_amount'] ?? 0) > 0 || (float)($rule['max_amount'] ?? 0) > 0) {
|
||||
$score += 1;
|
||||
}
|
||||
return $score;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前全部启用中的订单抽佣规则(按 weigh DESC -> 精确度 DESC -> id DESC 排序)
|
||||
*/
|
||||
public static function getActiveRules(bool $forceRefresh = false): array
|
||||
{
|
||||
if (self::$activeRulesCache === null || $forceRefresh) {
|
||||
$rows = [];
|
||||
try {
|
||||
$rows = Db::name('commission_rule')
|
||||
->where('status', 'normal')
|
||||
->order('weigh desc, id desc')
|
||||
->select();
|
||||
if (!is_array($rows)) {
|
||||
$rows = [];
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$rows = [];
|
||||
}
|
||||
|
||||
foreach ($rows as &$r) {
|
||||
$r['id'] = (int)$r['id'];
|
||||
$r['cat_id'] = (int)($r['cat_id'] ?? 0);
|
||||
$r['weigh'] = (int)($r['weigh'] ?? 0);
|
||||
$r['min_amount'] = round(max(0.00, (float)($r['min_amount'] ?? 0)), 2);
|
||||
$r['max_amount'] = round(max(0.00, (float)($r['max_amount'] ?? 0)), 2);
|
||||
$r['commission_rate'] = self::normalizeRate($r['commission_rate'] ?? 0);
|
||||
$r['fixed_fee'] = round(max(0.00, (float)($r['fixed_fee'] ?? 0)), 2);
|
||||
$r['min_commission'] = round(max(0.00, (float)($r['min_commission'] ?? 0)), 2);
|
||||
$r['max_commission'] = round(max(0.00, (float)($r['max_commission'] ?? 0)), 2);
|
||||
$r['_specificity'] = self::calcSpecificity($r);
|
||||
}
|
||||
unset($r);
|
||||
|
||||
usort($rows, function (array $a, array $b) {
|
||||
if ($a['weigh'] !== $b['weigh']) {
|
||||
return $b['weigh'] <=> $a['weigh'];
|
||||
}
|
||||
if ($a['_specificity'] !== $b['_specificity']) {
|
||||
return $b['_specificity'] <=> $a['_specificity'];
|
||||
}
|
||||
return $b['id'] <=> $a['id'];
|
||||
});
|
||||
|
||||
self::$activeRulesCache = $rows;
|
||||
}
|
||||
return self::$activeRulesCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断订单静态维度(不含金额区间)是否匹配规则
|
||||
*/
|
||||
protected static function matchStaticDimensions(array $rule, string $priceType, string $customerType, int $catId, int $urgent): bool
|
||||
{
|
||||
$rMode = (string)($rule['order_mode'] ?? 'all');
|
||||
if ($rMode !== 'all' && $rMode !== $priceType) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$rCust = (string)($rule['customer_type'] ?? 'all');
|
||||
if ($rCust !== 'all' && $rCust !== $customerType) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$rCat = (int)($rule['cat_id'] ?? 0);
|
||||
if ($rCat > 0 && $rCat !== $catId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$rUrgent = (string)($rule['urgent_mode'] ?? 'all');
|
||||
if ($rUrgent === 'urgent' && $urgent !== 1) {
|
||||
return false;
|
||||
}
|
||||
if ($rUrgent === 'normal' && $urgent !== 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断订单金额是否命中规则的金额区间
|
||||
*/
|
||||
protected static function matchAmountRange(array $rule, float $amount): bool
|
||||
{
|
||||
$minAmt = (float)($rule['min_amount'] ?? 0);
|
||||
$maxAmt = (float)($rule['max_amount'] ?? 0);
|
||||
$amt = round(max(0.00, $amount), 2);
|
||||
|
||||
if ($amt < $minAmt) {
|
||||
return false;
|
||||
}
|
||||
if ($maxAmt > 0 && $amt > $maxAmt) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取规则核心计佣描述结构(用于写入订单快照)
|
||||
*/
|
||||
protected static function extractRuleItem(array $rule): array
|
||||
{
|
||||
$calcMode = in_array($rule['calc_mode'] ?? 'percent', ['percent', 'fixed', 'mixed'], true)
|
||||
? $rule['calc_mode']
|
||||
: 'percent';
|
||||
|
||||
return [
|
||||
'rule_id' => (int)($rule['id'] ?? 0),
|
||||
'rule_name' => (string)($rule['name'] ?? '全局默认抽佣规则'),
|
||||
'min_amount' => round((float)($rule['min_amount'] ?? 0), 2),
|
||||
'max_amount' => round((float)($rule['max_amount'] ?? 0), 2),
|
||||
'calc_mode' => $calcMode,
|
||||
'commission_rate' => self::normalizeRate($rule['commission_rate'] ?? 0),
|
||||
'fixed_fee' => round(max(0.00, (float)($rule['fixed_fee'] ?? 0)), 2),
|
||||
'min_commission' => round(max(0.00, (float)($rule['min_commission'] ?? 0)), 2),
|
||||
'max_commission' => round(max(0.00, (float)($rule['max_commission'] ?? 0)), 2),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 创单阶段:根据订单多维上下文匹配生效抽佣规则并生成完整快照
|
||||
*
|
||||
* @param array $ctx ['price_type' => string, 'customer_type' => 'personal'|'merchant', 'cat_id' => int, 'urgent' => int, 'order_amount' => float]
|
||||
* @param array|null $rules 可选预加载规则列表(批量导单防重复查库)
|
||||
* @param array|null $defaults 可选预加载默认兜底配置
|
||||
* @return array ['commission_rate' => float, 'commission_snapshot' => string(JSON), 'rule_name' => string]
|
||||
*/
|
||||
public static function matchOrderSnapshot(array $ctx, ?array $rules = null, ?array $defaults = null): array
|
||||
{
|
||||
$rules = $rules !== null ? $rules : self::getActiveRules();
|
||||
$defaults = $defaults !== null ? $defaults : FinanceConfigService::getCommissionDefaults();
|
||||
|
||||
$priceType = trim((string)($ctx['price_type'] ?? 'fixed')) ?: 'fixed';
|
||||
$customerType = in_array($ctx['customer_type'] ?? 'personal', ['personal', 'merchant'], true)
|
||||
? $ctx['customer_type']
|
||||
: 'personal';
|
||||
$catId = max(0, (int)($ctx['cat_id'] ?? 0));
|
||||
$urgent = (int)($ctx['urgent'] ?? 0) === 1 ? 1 : 0;
|
||||
$orderAmount = round(max(0.00, (float)($ctx['order_amount'] ?? 0)), 2);
|
||||
|
||||
$fallbackItem = [
|
||||
'rule_id' => 0,
|
||||
'rule_name' => '全局默认兜底规则',
|
||||
'min_amount' => 0.00,
|
||||
'max_amount' => 0.00,
|
||||
'calc_mode' => $defaults['calc_mode'],
|
||||
'commission_rate' => self::normalizeRate($defaults['commission_rate']),
|
||||
'fixed_fee' => round((float)$defaults['fixed_fee'], 2),
|
||||
'min_commission' => round((float)$defaults['min_commission'], 2),
|
||||
'max_commission' => round((float)$defaults['max_commission'], 2),
|
||||
];
|
||||
|
||||
$staticMatched = [];
|
||||
$matchedItem = null;
|
||||
|
||||
foreach ($rules as $rule) {
|
||||
if (!self::matchStaticDimensions($rule, $priceType, $customerType, $catId, $urgent)) {
|
||||
continue;
|
||||
}
|
||||
$item = self::extractRuleItem($rule);
|
||||
$staticMatched[] = $item;
|
||||
if ($matchedItem === null && self::matchAmountRange($rule, $orderAmount)) {
|
||||
$matchedItem = $item;
|
||||
}
|
||||
}
|
||||
|
||||
// 若报价单创单金额为 0,且存在起始金额 > 0 的报价阶梯但暂无 0 元阶梯,优先取第一条无金额限制规则,否则暂挂兜底并保留全部阶梯候选
|
||||
if ($matchedItem === null) {
|
||||
$matchedItem = $fallbackItem;
|
||||
}
|
||||
|
||||
$snapshot = [
|
||||
'version' => 1,
|
||||
'snapshot_time' => time(),
|
||||
'context' => [
|
||||
'price_type' => $priceType,
|
||||
'customer_type' => $customerType,
|
||||
'cat_id' => $catId,
|
||||
'urgent' => $urgent,
|
||||
'init_amount' => $orderAmount,
|
||||
],
|
||||
'include_diff_in_commission' => (int)$defaults['include_diff_in_commission'] === 1 ? 1 : 0,
|
||||
'active_rule' => $matchedItem,
|
||||
'fallback_rule' => $fallbackItem,
|
||||
];
|
||||
|
||||
// 报价单创单时金额通常为 0,固化创单时刻符合静态条件的全部金额阶梯,供后续选定报价时在快照内部闭环定档
|
||||
if ($priceType === 'quote' && !empty($staticMatched)) {
|
||||
$snapshot['candidate_tiers'] = $staticMatched;
|
||||
}
|
||||
|
||||
$effectiveRate = self::calcDisplayRateForAmount($orderAmount, $matchedItem);
|
||||
|
||||
return [
|
||||
'commission_rate' => $effectiveRate,
|
||||
'commission_snapshot' => json_encode($snapshot, JSON_UNESCAPED_UNICODE),
|
||||
'rule_name' => $matchedItem['rule_name'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 报价单选定师傅报价并确认金额时:仅在订单自身的创单快照 candidate_tiers 内部重新定档(严禁读取后台新规则)
|
||||
*
|
||||
* @param float $finalAmount 选定报价后的订单金额
|
||||
* @param mixed $existingSnapshotJson 订单表已有的 commission_snapshot
|
||||
* @param mixed $existingRate 订单表已有的 commission_rate
|
||||
* @return array ['commission_rate' => float, 'commission_snapshot' => string|null]
|
||||
*/
|
||||
public static function refreshQuoteOrderSnapshotOnAmountConfirmed(float $finalAmount, $existingSnapshotJson, $existingRate): array
|
||||
{
|
||||
$fallbackRate = ($existingRate !== null && trim((string)$existingRate) !== '' && is_numeric($existingRate))
|
||||
? self::normalizeRate($existingRate)
|
||||
: self::DEFAULT_RATE;
|
||||
|
||||
if (!is_string($existingSnapshotJson) || trim($existingSnapshotJson) === '') {
|
||||
return [
|
||||
'commission_rate' => $fallbackRate,
|
||||
'commission_snapshot' => null,
|
||||
];
|
||||
}
|
||||
|
||||
$snap = json_decode($existingSnapshotJson, true);
|
||||
if (!is_array($snap)) {
|
||||
return [
|
||||
'commission_rate' => $fallbackRate,
|
||||
'commission_snapshot' => $existingSnapshotJson,
|
||||
];
|
||||
}
|
||||
|
||||
$chosen = null;
|
||||
if (!empty($snap['candidate_tiers']) && is_array($snap['candidate_tiers'])) {
|
||||
foreach ($snap['candidate_tiers'] as $tier) {
|
||||
if (is_array($tier) && self::matchAmountRange($tier, $finalAmount)) {
|
||||
$chosen = $tier;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($chosen === null) {
|
||||
if (!empty($snap['fallback_rule']) && is_array($snap['fallback_rule'])) {
|
||||
$chosen = $snap['fallback_rule'];
|
||||
} elseif (!empty($snap['active_rule']) && is_array($snap['active_rule'])) {
|
||||
$chosen = $snap['active_rule'];
|
||||
}
|
||||
}
|
||||
|
||||
if (is_array($chosen)) {
|
||||
$snap['active_rule'] = $chosen;
|
||||
$snap['confirmed_quote_amount'] = round(max(0.00, $finalAmount), 2);
|
||||
$snap['confirmed_time'] = time();
|
||||
$newRate = self::calcDisplayRateForAmount($finalAmount, $chosen);
|
||||
return [
|
||||
'commission_rate' => $newRate,
|
||||
'commission_snapshot' => json_encode($snap, JSON_UNESCAPED_UNICODE),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'commission_rate' => $fallbackRate,
|
||||
'commission_snapshot' => $existingSnapshotJson,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算给定金额与规则项下的展示/快照百分比
|
||||
*/
|
||||
protected static function calcDisplayRateForAmount(float $amount, array $ruleItem): float
|
||||
{
|
||||
$mode = $ruleItem['calc_mode'] ?? 'percent';
|
||||
$rate = self::normalizeRate($ruleItem['commission_rate'] ?? 0);
|
||||
if ($mode === 'percent' && (float)($ruleItem['min_commission'] ?? 0) <= 0 && (float)($ruleItem['max_commission'] ?? 0) <= 0) {
|
||||
return $rate;
|
||||
}
|
||||
if ($amount <= 0) {
|
||||
return $rate;
|
||||
}
|
||||
$res = self::computeCommissionByRuleItem($amount, $amount, $ruleItem);
|
||||
return $res['commission_rate'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 核心纯函数:按规则项核算抽佣与实结金额
|
||||
*
|
||||
* @param float $totalPayAmount 订单总实付金额(主单实付/应付总额,师傅结算总额上限)
|
||||
* @param float $calcBaseAmount 参与抽佣计算的基数金额(若增项免抽佣则已剔除增项差价)
|
||||
* @param array $ruleItem 规则快照结构
|
||||
* @return array
|
||||
*/
|
||||
protected static function computeCommissionByRuleItem(float $totalPayAmount, float $calcBaseAmount, array $ruleItem): array
|
||||
{
|
||||
$total = max(0.00, round($totalPayAmount, 2));
|
||||
$base = max(0.00, min($total, round($calcBaseAmount, 2)));
|
||||
$mode = in_array($ruleItem['calc_mode'] ?? 'percent', ['percent', 'fixed', 'mixed'], true)
|
||||
? $ruleItem['calc_mode']
|
||||
: 'percent';
|
||||
$rate = self::normalizeRate($ruleItem['commission_rate'] ?? 0);
|
||||
$fixed = round(max(0.00, (float)($ruleItem['fixed_fee'] ?? 0)), 2);
|
||||
$minC = round(max(0.00, (float)($ruleItem['min_commission'] ?? 0)), 2);
|
||||
$maxC = round(max(0.00, (float)($ruleItem['max_commission'] ?? 0)), 2);
|
||||
|
||||
if ($total <= 0 || $base <= 0) {
|
||||
return [
|
||||
'commission_rate' => $mode === 'percent' ? $rate : 0.00,
|
||||
'commission' => 0.00,
|
||||
'settle_amount' => $total,
|
||||
'calc_mode' => $mode,
|
||||
'rule_name' => (string)($ruleItem['rule_name'] ?? '历史比例快照'),
|
||||
'calc_base_amount' => $base,
|
||||
];
|
||||
}
|
||||
|
||||
if ($mode === 'fixed') {
|
||||
$rawComm = $fixed;
|
||||
} elseif ($mode === 'mixed') {
|
||||
$rawComm = round($base * $rate / 100 + $fixed, 2);
|
||||
} else {
|
||||
$rawComm = round($base * $rate / 100, 2);
|
||||
}
|
||||
|
||||
$comm = $rawComm;
|
||||
if ($minC > 0 && $comm < $minC) {
|
||||
$comm = $minC;
|
||||
}
|
||||
if ($maxC > 0 && $comm > $maxC) {
|
||||
$comm = $maxC;
|
||||
}
|
||||
// 抽佣额绝不可超过计佣基数或总实付额
|
||||
$comm = round(min($base, max(0.00, $comm)), 2);
|
||||
$settle = round(max(0.00, $total - $comm), 2);
|
||||
|
||||
// 若为纯比例且未触发保底/封顶与增项剔除,保留原配置比例;否则折算实际综合抽佣率供结算单归档对账
|
||||
if ($mode === 'percent' && $comm === $rawComm && abs($total - $base) < 0.001) {
|
||||
$effectiveRate = $rate;
|
||||
} else {
|
||||
$effectiveRate = $total > 0 ? self::normalizeRate(round($comm / $total * 100, 2)) : $rate;
|
||||
}
|
||||
|
||||
return [
|
||||
'commission_rate' => $effectiveRate,
|
||||
'commission' => $comm,
|
||||
'settle_amount' => $settle,
|
||||
'calc_mode' => $mode,
|
||||
'rule_name' => (string)($ruleItem['rule_name'] ?? '历史比例快照'),
|
||||
'calc_base_amount' => $base,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于完整订单行记录(fa_order)锁定的快照计算平台抽佣与师傅实结金额
|
||||
*
|
||||
* @param array $order fa_order 行数据(含 pay_amount/total_amount, diff_amount, diff_status, commission_rate, commission_snapshot)
|
||||
* @param float|null $overrideAmount 可选指定结算总金额(如订单大厅预估展示时传入基准价)
|
||||
* @return array ['commission_rate' => float, 'commission' => float, 'settle_amount' => float, 'calc_mode' => string, 'rule_name' => string, 'calc_base_amount' => float]
|
||||
*/
|
||||
public static function calcByOrder(array $order, ?float $overrideAmount = null): array
|
||||
{
|
||||
if ($overrideAmount !== null) {
|
||||
$totalAmount = max(0.00, round($overrideAmount, 2));
|
||||
} else {
|
||||
$payAmt = (float)($order['pay_amount'] ?? 0);
|
||||
$totAmt = (float)($order['total_amount'] ?? 0);
|
||||
$totalAmount = max(0.00, round($payAmt > 0 ? $payAmt : $totAmt, 2));
|
||||
}
|
||||
|
||||
$snapshotRate = $order['commission_rate'] ?? null;
|
||||
$snapshotJson = $order['commission_snapshot'] ?? null;
|
||||
|
||||
if (is_string($snapshotJson) && trim($snapshotJson) !== '') {
|
||||
$snap = json_decode($snapshotJson, true);
|
||||
if (is_array($snap) && !empty($snap['active_rule']) && is_array($snap['active_rule'])) {
|
||||
$calcBase = $totalAmount;
|
||||
$includeDiff = isset($snap['include_diff_in_commission']) ? (int)$snap['include_diff_in_commission'] : 1;
|
||||
if ($overrideAmount === null && $includeDiff === 0 && (int)($order['diff_status'] ?? 0) === 2) {
|
||||
$diffAmt = round(max(0.00, (float)($order['diff_amount'] ?? 0)), 2);
|
||||
if ($diffAmt > 0 && $calcBase >= $diffAmt) {
|
||||
$calcBase = round($calcBase - $diffAmt, 2);
|
||||
}
|
||||
}
|
||||
return self::computeCommissionByRuleItem($totalAmount, $calcBase, $snap['active_rule']);
|
||||
}
|
||||
}
|
||||
|
||||
return self::calcByOrderSnapshot($totalAmount, $snapshotRate);
|
||||
}
|
||||
|
||||
/**
|
||||
* 兼容历史仅含 commission_rate 字段或传入快照 JSON 的核算调用
|
||||
*
|
||||
* @param float $orderAmount 订单实付结算基数
|
||||
* @param mixed $snapshotRate fa_order.commission_rate 快照值
|
||||
* @param string|null $snapshotJson 可选 fa_order.commission_snapshot JSON
|
||||
* @return array ['commission_rate' => float, 'commission' => float, 'settle_amount' => float, 'calc_mode' => string, 'rule_name' => string, 'calc_base_amount' => float]
|
||||
*/
|
||||
public static function calcByOrderSnapshot(float $orderAmount, $snapshotRate, ?string $snapshotJson = null): array
|
||||
{
|
||||
if ($snapshotJson !== null && trim($snapshotJson) !== '') {
|
||||
return self::calcByOrder([
|
||||
'pay_amount' => $orderAmount,
|
||||
'total_amount' => $orderAmount,
|
||||
'commission_rate' => $snapshotRate,
|
||||
'commission_snapshot' => $snapshotJson,
|
||||
]);
|
||||
}
|
||||
|
||||
$rate = ($snapshotRate !== null && trim((string)$snapshotRate) !== '' && is_numeric($snapshotRate))
|
||||
? self::normalizeRate($snapshotRate)
|
||||
: self::DEFAULT_RATE;
|
||||
|
||||
return self::computeCommissionByRuleItem($orderAmount, $orderAmount, [
|
||||
'rule_name' => '比例快照(' . number_format($rate, 2, '.', '') . '%)',
|
||||
'calc_mode' => 'percent',
|
||||
'commission_rate' => $rate,
|
||||
'fixed_fee' => 0.00,
|
||||
'min_commission' => 0.00,
|
||||
'max_commission' => 0.00,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 fa_config 同步至 application/extra/site.php,并保留文件中非数据库托管的扩展密钥
|
||||
*
|
||||
* @param string $removedKey 刚被删除的配置键名
|
||||
* @return void
|
||||
*/
|
||||
public static function syncSiteConfigFile(string $removedKey = ''): void
|
||||
{
|
||||
$siteFile = CONF_PATH . 'extra' . DS . 'site.php';
|
||||
$existing = [];
|
||||
if (is_file($siteFile)) {
|
||||
$loaded = include $siteFile;
|
||||
if (is_array($loaded)) {
|
||||
$existing = $loaded;
|
||||
}
|
||||
}
|
||||
if ($removedKey !== '' && array_key_exists($removedKey, $existing)) {
|
||||
unset($existing[$removedKey]);
|
||||
}
|
||||
|
||||
$dbConfig = [];
|
||||
$rows = Db::name('config')->select();
|
||||
foreach ($rows as $value) {
|
||||
$val = $value['value'];
|
||||
if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'], true)) {
|
||||
$val = $val === '' ? [] : explode(',', (string)$val);
|
||||
} elseif ($value['type'] === 'array') {
|
||||
$val = (array)json_decode((string)$val, true);
|
||||
}
|
||||
$dbConfig[$value['name']] = $val;
|
||||
}
|
||||
|
||||
$merged = array_merge($existing, $dbConfig);
|
||||
file_put_contents(
|
||||
$siteFile,
|
||||
'<?php' . "\n\nreturn " . var_export($merged, true) . ";\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,680 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Db;
|
||||
|
||||
/**
|
||||
* 财务结算与提现规则配置中心服务
|
||||
*
|
||||
* 职责:
|
||||
* 1. 统一管理独立配置中心表 fa_finance_config(订单默认抽佣兜底 + 提现风控 + 微信小程序商家转账 1005 规范参数)
|
||||
* 2. 提供提现手续费灵活计算(按比例 / 按笔固定 / 免费 + 单笔保底与封顶)
|
||||
* 3. 执行符合微信支付 APIv3 新版「商家转账(用户确认模式)」与微信小程序规范的提现前置校验与配置下发
|
||||
*/
|
||||
class FinanceConfigService
|
||||
{
|
||||
/** 微信新版商家转账官方单笔最低到账净额(0.10元 = 10分) */
|
||||
const WX_TRANSFER_MIN_ARRIVE = 0.10;
|
||||
|
||||
/** 微信新版商家转账官方单笔硬上限(20000.00元) */
|
||||
const WX_TRANSFER_HARD_MAX = 20000.00;
|
||||
|
||||
/** 微信新版商家转账强制加密校验真实姓名阈值(2000.00元) */
|
||||
const WX_TRANSFER_REALNAME_THRESHOLD = 2000.00;
|
||||
|
||||
/** @var array|null 请求内静态缓存 */
|
||||
protected static $cache = null;
|
||||
|
||||
/**
|
||||
* 默认配置字典(当数据库尚未初始化某项时的安全兜底)
|
||||
*/
|
||||
public static function defaults(): array
|
||||
{
|
||||
return [
|
||||
// 订单抽佣全局兜底
|
||||
'default_calc_mode' => 'percent',
|
||||
'default_commission_rate' => '10.00',
|
||||
'default_fixed_fee' => '0.00',
|
||||
'default_min_commission' => '0.00',
|
||||
'default_max_commission' => '0.00',
|
||||
'include_diff_in_commission' => '1',
|
||||
|
||||
// 提现与微信小程序商家转账配置
|
||||
'withdraw_enabled' => '1',
|
||||
'withdraw_close_tip' => '系统正在进行财务结算维护,请稍后再发起提现',
|
||||
'withdraw_channels' => 'wechat',
|
||||
'withdraw_require_realname' => '1',
|
||||
'withdraw_min_amount' => '10.00',
|
||||
'withdraw_max_amount' => '200.00',
|
||||
'withdraw_daily_amount' => '2000.00',
|
||||
'withdraw_daily_count' => '3',
|
||||
'withdraw_allow_weekdays' => '1,2,3,4,5,6,7',
|
||||
'withdraw_time_start' => '00:00',
|
||||
'withdraw_time_end' => '23:59',
|
||||
'withdraw_fee_mode' => 'percent',
|
||||
'withdraw_fee_rate' => '0.60',
|
||||
'withdraw_fee_fixed' => '0.00',
|
||||
'withdraw_fee_min' => '0.00',
|
||||
'withdraw_fee_max' => '0.00',
|
||||
'withdraw_transfer_mode' => 'wx_mch_transfer',
|
||||
'withdraw_audit_mode' => 'manual',
|
||||
'withdraw_auto_max_amount' => '50.00',
|
||||
'wx_transfer_scene_id' => '1005',
|
||||
'wx_recv_perception' => '劳务报酬',
|
||||
'wx_job_type' => '上门安装维修师傅',
|
||||
'wx_reward_desc' => '平台工单安装维修劳务报酬',
|
||||
'wx_transfer_remark' => '工单安装维修服务劳务报酬',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空请求内静态缓存
|
||||
*/
|
||||
public static function clearCache(): void
|
||||
{
|
||||
self::$cache = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取全部原始配置键值数组
|
||||
*/
|
||||
public static function getAll(bool $forceRefresh = false): array
|
||||
{
|
||||
if (self::$cache === null || $forceRefresh) {
|
||||
$base = self::defaults();
|
||||
try {
|
||||
$dbMap = Db::name('finance_config')->column('value', 'name');
|
||||
if (is_array($dbMap) && !empty($dbMap)) {
|
||||
foreach ($dbMap as $k => $v) {
|
||||
if ($v !== null) {
|
||||
$base[$k] = (string)$v;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// 表未就绪时平滑回退默认字典
|
||||
}
|
||||
self::$cache = $base;
|
||||
}
|
||||
return self::$cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取订单默认兜底抽佣配置
|
||||
*/
|
||||
public static function getCommissionDefaults(): array
|
||||
{
|
||||
$all = self::getAll();
|
||||
$mode = in_array($all['default_calc_mode'], ['percent', 'fixed', 'mixed'], true)
|
||||
? $all['default_calc_mode']
|
||||
: 'percent';
|
||||
|
||||
return [
|
||||
'calc_mode' => $mode,
|
||||
'commission_rate' => round(min(100.00, max(0.00, (float)$all['default_commission_rate'])), 2),
|
||||
'fixed_fee' => round(max(0.00, (float)$all['default_fixed_fee']), 2),
|
||||
'min_commission' => round(max(0.00, (float)$all['default_min_commission']), 2),
|
||||
'max_commission' => round(max(0.00, (float)$all['default_max_commission']), 2),
|
||||
'include_diff_in_commission' => (int)$all['include_diff_in_commission'] === 1 ? 1 : 0,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取结构化的提现与微信小程序转账配置
|
||||
*/
|
||||
public static function getWithdrawConfig(): array
|
||||
{
|
||||
$all = self::getAll();
|
||||
$rawChannels = array_filter(array_map('trim', explode(',', (string)$all['withdraw_channels'])));
|
||||
$channels = [];
|
||||
foreach ($rawChannels as $ch) {
|
||||
if (in_array($ch, ['wechat', 'bank'], true) && !in_array($ch, $channels, true)) {
|
||||
$channels[] = $ch;
|
||||
}
|
||||
}
|
||||
if (empty($channels)) {
|
||||
$channels = ['wechat'];
|
||||
}
|
||||
|
||||
$rawDays = array_filter(array_map('intval', explode(',', (string)$all['withdraw_allow_weekdays'])));
|
||||
$weekdays = [];
|
||||
foreach ($rawDays as $d) {
|
||||
if ($d >= 1 && $d <= 7 && !in_array($d, $weekdays, true)) {
|
||||
$weekdays[] = $d;
|
||||
}
|
||||
}
|
||||
sort($weekdays);
|
||||
if (empty($weekdays)) {
|
||||
$weekdays = [1, 2, 3, 4, 5, 6, 7];
|
||||
}
|
||||
|
||||
$minAmt = round(max(0.10, (float)$all['withdraw_min_amount']), 2);
|
||||
$maxAmt = round(min(self::WX_TRANSFER_HARD_MAX, max($minAmt, (float)$all['withdraw_max_amount'])), 2);
|
||||
$dailyAmt = round(max(0.00, (float)$all['withdraw_daily_amount']), 2);
|
||||
if ($dailyAmt > 0 && $dailyAmt < $minAmt) {
|
||||
$dailyAmt = $maxAmt;
|
||||
}
|
||||
|
||||
$feeMode = in_array($all['withdraw_fee_mode'], ['percent', 'fixed', 'free'], true)
|
||||
? $all['withdraw_fee_mode']
|
||||
: 'percent';
|
||||
|
||||
$transferMode = in_array($all['withdraw_transfer_mode'], ['wx_mch_transfer', 'offline_manual'], true)
|
||||
? $all['withdraw_transfer_mode']
|
||||
: 'wx_mch_transfer';
|
||||
|
||||
$auditMode = in_array($all['withdraw_audit_mode'], ['manual', 'auto_small'], true)
|
||||
? $all['withdraw_audit_mode']
|
||||
: 'manual';
|
||||
|
||||
return [
|
||||
'enabled' => (int)$all['withdraw_enabled'] === 1 ? 1 : 0,
|
||||
'close_tip' => trim((string)$all['withdraw_close_tip']) ?: '当前暂未开放提现,请稍后再试',
|
||||
'channels' => $channels,
|
||||
'require_realname' => (int)$all['withdraw_require_realname'] === 1 ? 1 : 0,
|
||||
'min_amount' => $minAmt,
|
||||
'max_amount' => $maxAmt,
|
||||
'daily_amount' => $dailyAmt,
|
||||
'daily_count' => max(0, (int)$all['withdraw_daily_count']),
|
||||
'allow_weekdays' => $weekdays,
|
||||
'time_start' => preg_match('/^\d{2}:\d{2}$/', (string)$all['withdraw_time_start']) ? $all['withdraw_time_start'] : '00:00',
|
||||
'time_end' => preg_match('/^\d{2}:\d{2}$/', (string)$all['withdraw_time_end']) ? $all['withdraw_time_end'] : '23:59',
|
||||
'fee_mode' => $feeMode,
|
||||
'fee_rate' => round(min(50.00, max(0.00, (float)$all['withdraw_fee_rate'])), 2),
|
||||
'fee_fixed' => round(max(0.00, (float)$all['withdraw_fee_fixed']), 2),
|
||||
'fee_min' => round(max(0.00, (float)$all['withdraw_fee_min']), 2),
|
||||
'fee_max' => round(max(0.00, (float)$all['withdraw_fee_max']), 2),
|
||||
'transfer_mode' => $transferMode,
|
||||
'audit_mode' => $auditMode,
|
||||
'auto_max_amount' => round(max(0.00, (float)$all['withdraw_auto_max_amount']), 2),
|
||||
'wx_scene_id' => trim((string)$all['wx_transfer_scene_id']) ?: '1005',
|
||||
'wx_perception' => mb_substr(trim((string)$all['wx_recv_perception']) ?: '劳务报酬', 0, 32),
|
||||
'wx_job_type' => mb_substr(trim((string)$all['wx_job_type']) ?: '上门安装维修师傅', 0, 32),
|
||||
'wx_reward_desc' => mb_substr(trim((string)$all['wx_reward_desc']) ?: '平台工单安装维修劳务报酬', 0, 32),
|
||||
'wx_remark' => mb_substr(trim((string)$all['wx_transfer_remark']) ?: '工单安装维修服务劳务报酬', 0, 32),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算单笔提现的手续费与实际到账净额
|
||||
*/
|
||||
public static function calcWithdrawFee(float $amount, ?array $cfg = null): array
|
||||
{
|
||||
$cfg = $cfg ?: self::getWithdrawConfig();
|
||||
$amt = max(0.00, round($amount, 2));
|
||||
$fee = 0.00;
|
||||
|
||||
if ($amt > 0) {
|
||||
if ($cfg['fee_mode'] === 'percent') {
|
||||
$fee = round($amt * ((float)$cfg['fee_rate']) / 100, 2);
|
||||
if ($cfg['fee_min'] > 0 && $fee < $cfg['fee_min']) {
|
||||
$fee = $cfg['fee_min'];
|
||||
}
|
||||
if ($cfg['fee_max'] > 0 && $fee > $cfg['fee_max']) {
|
||||
$fee = $cfg['fee_max'];
|
||||
}
|
||||
} elseif ($cfg['fee_mode'] === 'fixed') {
|
||||
$fee = round((float)$cfg['fee_fixed'], 2);
|
||||
} else {
|
||||
$fee = 0.00;
|
||||
}
|
||||
}
|
||||
|
||||
if ($fee >= $amt && $amt > 0) {
|
||||
$fee = max(0.00, round($amt - self::WX_TRANSFER_MIN_ARRIVE, 2));
|
||||
}
|
||||
|
||||
$arrive = round(max(0.00, $amt - $fee), 2);
|
||||
return [
|
||||
'amount' => $amt,
|
||||
'fee' => $fee,
|
||||
'arrive_amount' => $arrive,
|
||||
'fee_mode' => $cfg['fee_mode'],
|
||||
'fee_rate' => $cfg['fee_rate'],
|
||||
'fee_fixed' => $cfg['fee_fixed'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计师傅今日已申请提现次数与金额(排除已驳回单)
|
||||
*/
|
||||
public static function getMasterTodayWithdrawStats(int $masterId): array
|
||||
{
|
||||
$todayStart = strtotime(date('Y-m-d 00:00:00'));
|
||||
$rows = Db::name('withdraw')
|
||||
->field('amount')
|
||||
->where('master_id', $masterId)
|
||||
->where('status', '<>', 'reject')
|
||||
->where('createtime', '>=', $todayStart)
|
||||
->select();
|
||||
|
||||
$cnt = count($rows);
|
||||
$sum = 0.00;
|
||||
foreach ($rows as $r) {
|
||||
$sum += (float)$r['amount'];
|
||||
}
|
||||
return [
|
||||
'today_count' => $cnt,
|
||||
'today_amount' => round($sum, 2),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成下发给小程序「我的钱包」页面的动态提现配置与规则说明
|
||||
*/
|
||||
public static function buildMasterWithdrawClientPayload(array $master): array
|
||||
{
|
||||
$cfg = self::getWithdrawConfig();
|
||||
$stats = self::getMasterTodayWithdrawStats((int)$master['id']);
|
||||
|
||||
$remainDailyAmount = $cfg['daily_amount'] > 0
|
||||
? round(max(0.00, $cfg['daily_amount'] - $stats['today_amount']), 2)
|
||||
: -1;
|
||||
$remainDailyCount = $cfg['daily_count'] > 0
|
||||
? max(0, $cfg['daily_count'] - $stats['today_count'])
|
||||
: -1;
|
||||
|
||||
if ($cfg['fee_mode'] === 'free' || ($cfg['fee_mode'] === 'percent' && $cfg['fee_rate'] <= 0) || ($cfg['fee_mode'] === 'fixed' && $cfg['fee_fixed'] <= 0)) {
|
||||
$feeText = '免通道手续费';
|
||||
} elseif ($cfg['fee_mode'] === 'fixed') {
|
||||
$feeText = '手续费 ¥' . number_format($cfg['fee_fixed'], 2, '.', '') . '/笔';
|
||||
} else {
|
||||
$feeText = '通道费率 ' . rtrim(rtrim(number_format($cfg['fee_rate'], 2, '.', ''), '0'), '.') . '%';
|
||||
if ($cfg['fee_min'] > 0 || $cfg['fee_max'] > 0) {
|
||||
$parts = [];
|
||||
if ($cfg['fee_min'] > 0) {
|
||||
$parts[] = '最低¥' . number_format($cfg['fee_min'], 2, '.', '');
|
||||
}
|
||||
if ($cfg['fee_max'] > 0) {
|
||||
$parts[] = '封顶¥' . number_format($cfg['fee_max'], 2, '.', '');
|
||||
}
|
||||
$feeText .= '(' . implode(',', $parts) . ')';
|
||||
}
|
||||
}
|
||||
|
||||
$minTxt = rtrim(rtrim(number_format($cfg['min_amount'], 2, '.', ''), '0'), '.');
|
||||
$maxTxt = rtrim(rtrim(number_format($cfg['max_amount'], 2, '.', ''), '0'), '.');
|
||||
$ruleTip = "完工核销后工费即刻入账;单笔 ¥{$minTxt}~¥{$maxTxt} 可提现,{$feeText}。";
|
||||
if (!$cfg['enabled']) {
|
||||
$ruleTip = $cfg['close_tip'];
|
||||
}
|
||||
|
||||
$arrivalDesc = $cfg['transfer_mode'] === 'wx_mch_transfer'
|
||||
? ($cfg['audit_mode'] === 'auto_small' ? '微信零钱(小额免审,确认收款即到账)' : '微信零钱(审核后小程序确认收款即到账)')
|
||||
: '微信零钱 / 人工财务打款';
|
||||
|
||||
return [
|
||||
'enabled' => (bool)$cfg['enabled'],
|
||||
'close_tip' => $cfg['close_tip'],
|
||||
'channels' => $cfg['channels'],
|
||||
'require_realname' => (bool)$cfg['require_realname'],
|
||||
'min_amount' => $cfg['min_amount'],
|
||||
'max_amount' => $cfg['max_amount'],
|
||||
'daily_amount' => $cfg['daily_amount'],
|
||||
'daily_count' => $cfg['daily_count'],
|
||||
'today_amount' => $stats['today_amount'],
|
||||
'today_count' => $stats['today_count'],
|
||||
'remain_daily_amount' => $remainDailyAmount,
|
||||
'remain_daily_count' => $remainDailyCount,
|
||||
'allow_weekdays' => $cfg['allow_weekdays'],
|
||||
'time_start' => $cfg['time_start'],
|
||||
'time_end' => $cfg['time_end'],
|
||||
'fee_mode' => $cfg['fee_mode'],
|
||||
'fee_rate' => $cfg['fee_rate'],
|
||||
'fee_fixed' => $cfg['fee_fixed'],
|
||||
'fee_min' => $cfg['fee_min'],
|
||||
'fee_max' => $cfg['fee_max'],
|
||||
'fee_text' => $feeText,
|
||||
'transfer_mode' => $cfg['transfer_mode'],
|
||||
'audit_mode' => $cfg['audit_mode'],
|
||||
'auto_max_amount' => $cfg['auto_max_amount'],
|
||||
'arrival_desc' => $arrivalDesc,
|
||||
'rule_tip' => $ruleTip,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验师傅发起的提现请求(全量业务规则 + 微信小程序商家转账硬规范)
|
||||
*
|
||||
* @param array $master fa_master 行记录
|
||||
* @param float $amount 申请提现金额
|
||||
* @param string $channel 申请提现渠道 wechat | bank
|
||||
* @param string $account 银行卡等收款账号信息
|
||||
* @return array ['fee' => float, 'arrive_amount' => float, 'cfg' => array, 'rule_snapshot' => string]
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function validateWithdrawRequest(array $master, float $amount, string $channel, string $account = ''): array
|
||||
{
|
||||
$cfg = self::getWithdrawConfig();
|
||||
|
||||
if (!$cfg['enabled']) {
|
||||
throw new \InvalidArgumentException($cfg['close_tip']);
|
||||
}
|
||||
|
||||
if (!in_array($channel, $cfg['channels'], true)) {
|
||||
$chLabel = $channel === 'bank' ? '银行储蓄卡' : '微信零钱';
|
||||
throw new \InvalidArgumentException("当前暂未开放【{$chLabel}】提现渠道");
|
||||
}
|
||||
|
||||
if ($channel === 'bank' && trim($account) === '') {
|
||||
throw new \InvalidArgumentException('请填写收款银行卡号与开户行信息');
|
||||
}
|
||||
|
||||
// 校验允许提现星期与每日时段
|
||||
$curWeekday = (int)date('N'); // 1(周一) ~ 7(周日)
|
||||
if (!in_array($curWeekday, $cfg['allow_weekdays'], true)) {
|
||||
$dayNames = [1 => '周一', 2 => '周二', 3 => '周三', 4 => '周四', 5 => '周五', 6 => '周六', 7 => '周日'];
|
||||
$allowLabels = array_map(function ($d) use ($dayNames) {
|
||||
return $dayNames[$d] ?? '';
|
||||
}, $cfg['allow_weekdays']);
|
||||
throw new \InvalidArgumentException('当前不在提现开放日(开放时间:' . implode('、', array_filter($allowLabels)) . ')');
|
||||
}
|
||||
|
||||
$nowHm = date('H:i');
|
||||
if ($nowHm < $cfg['time_start'] || $nowHm > $cfg['time_end']) {
|
||||
throw new \InvalidArgumentException("当前不在每日提现开放时段({$cfg['time_start']} ~ {$cfg['time_end']})");
|
||||
}
|
||||
|
||||
// 实名认证合规校验(后台开启强制实名,或微信单笔 >= 2000 元微信官方强制实名)
|
||||
$isRealnameVerified = (($master['verify_status'] ?? '') === 'pass') && trim((string)($master['realname'] ?? '')) !== '';
|
||||
if ($cfg['require_realname'] && !$isRealnameVerified) {
|
||||
throw new \InvalidArgumentException('根据资金合规要求,请先完成师傅实名认证审核通过后再申请提现');
|
||||
}
|
||||
|
||||
$amt = round($amount, 2);
|
||||
if ($amt <= 0) {
|
||||
throw new \InvalidArgumentException('请输入有效的提现金额');
|
||||
}
|
||||
if ($amt < $cfg['min_amount']) {
|
||||
throw new \InvalidArgumentException('单笔提现金额不能低于 ¥' . number_format($cfg['min_amount'], 2, '.', ''));
|
||||
}
|
||||
if ($amt > $cfg['max_amount']) {
|
||||
throw new \InvalidArgumentException('单笔提现金额不能超过 ¥' . number_format($cfg['max_amount'], 2, '.', ''));
|
||||
}
|
||||
if ($channel === 'wechat' && $amt > self::WX_TRANSFER_HARD_MAX) {
|
||||
throw new \InvalidArgumentException('微信零钱单笔提现不能超过官方上限 ¥20,000.00');
|
||||
}
|
||||
|
||||
$feeCalc = self::calcWithdrawFee($amt, $cfg);
|
||||
$arrive = $feeCalc['arrive_amount'];
|
||||
|
||||
if ($channel === 'wechat') {
|
||||
if ($arrive < self::WX_TRANSFER_MIN_ARRIVE) {
|
||||
throw new \InvalidArgumentException('扣除手续费后实际到账金额不能低于 ¥0.10(微信转账最低限额)');
|
||||
}
|
||||
if ($arrive >= self::WX_TRANSFER_REALNAME_THRESHOLD && !$isRealnameVerified) {
|
||||
throw new \InvalidArgumentException('微信官方规定单笔转账满 ¥2,000.00 必须校验真实姓名,请先完成实名认证');
|
||||
}
|
||||
}
|
||||
|
||||
// 单日次数与累计额度校验
|
||||
$stats = self::getMasterTodayWithdrawStats((int)$master['id']);
|
||||
if ($cfg['daily_count'] > 0 && $stats['today_count'] >= $cfg['daily_count']) {
|
||||
throw new \InvalidArgumentException("今日提现次数已达上限(每日最多 {$cfg['daily_count']} 次),请明日再试");
|
||||
}
|
||||
if ($cfg['daily_amount'] > 0 && round($stats['today_amount'] + $amt, 2) > $cfg['daily_amount']) {
|
||||
$remain = max(0.00, round($cfg['daily_amount'] - $stats['today_amount'], 2));
|
||||
throw new \InvalidArgumentException('超出单日累计提现上限(今日剩余可提额度 ¥' . number_format($remain, 2, '.', '') . ')');
|
||||
}
|
||||
|
||||
$snapshot = [
|
||||
'fee_mode' => $cfg['fee_mode'],
|
||||
'fee_rate' => $cfg['fee_rate'],
|
||||
'fee_fixed' => $cfg['fee_fixed'],
|
||||
'fee_min' => $cfg['fee_min'],
|
||||
'fee_max' => $cfg['fee_max'],
|
||||
'fee' => $feeCalc['fee'],
|
||||
'arrive_amount' => $arrive,
|
||||
'transfer_mode' => $cfg['transfer_mode'],
|
||||
'audit_mode' => $cfg['audit_mode'],
|
||||
'snapshot_time' => time(),
|
||||
];
|
||||
|
||||
return [
|
||||
'fee' => $feeCalc['fee'],
|
||||
'arrive_amount' => $arrive,
|
||||
'cfg' => $cfg,
|
||||
'rule_snapshot' => json_encode($snapshot, JSON_UNESCAPED_UNICODE),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台配置中心保存并严格校验全量配置项
|
||||
*
|
||||
* @param array $input
|
||||
* @return void
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function saveConfigs(array $input): void
|
||||
{
|
||||
$defaults = self::defaults();
|
||||
$clean = [];
|
||||
|
||||
// 1. 校验订单默认抽佣兜底配置
|
||||
if (isset($input['default_calc_mode'])) {
|
||||
if (!in_array($input['default_calc_mode'], ['percent', 'fixed', 'mixed'], true)) {
|
||||
throw new \InvalidArgumentException('请选择有效的默认抽佣计费方式');
|
||||
}
|
||||
$clean['default_calc_mode'] = $input['default_calc_mode'];
|
||||
}
|
||||
if (isset($input['default_commission_rate'])) {
|
||||
if (!is_numeric($input['default_commission_rate']) || (float)$input['default_commission_rate'] < 0 || (float)$input['default_commission_rate'] > 100) {
|
||||
throw new \InvalidArgumentException('默认抽佣比例必须在 0% ~ 100% 之间');
|
||||
}
|
||||
$clean['default_commission_rate'] = number_format(round((float)$input['default_commission_rate'], 2), 2, '.', '');
|
||||
}
|
||||
foreach (['default_fixed_fee' => '默认单笔固定抽佣', 'default_min_commission' => '默认单笔保底抽佣', 'default_max_commission' => '默认单笔封顶抽佣'] as $k => $label) {
|
||||
if (isset($input[$k])) {
|
||||
if (!is_numeric($input[$k]) || (float)$input[$k] < 0) {
|
||||
throw new \InvalidArgumentException($label . '不能为负数');
|
||||
}
|
||||
$clean[$k] = number_format(round((float)$input[$k], 2), 2, '.', '');
|
||||
}
|
||||
}
|
||||
if (isset($clean['default_min_commission'], $clean['default_max_commission'])) {
|
||||
$minC = (float)$clean['default_min_commission'];
|
||||
$maxC = (float)$clean['default_max_commission'];
|
||||
if ($minC > 0 && $maxC > 0 && $minC > $maxC) {
|
||||
throw new \InvalidArgumentException('默认单笔保底抽佣不能大于单笔封顶抽佣');
|
||||
}
|
||||
}
|
||||
if (isset($input['include_diff_in_commission'])) {
|
||||
$clean['include_diff_in_commission'] = (int)$input['include_diff_in_commission'] === 1 ? '1' : '0';
|
||||
}
|
||||
|
||||
// 2. 校验提现与微信小程序商家转账配置
|
||||
if (isset($input['withdraw_enabled'])) {
|
||||
$clean['withdraw_enabled'] = (int)$input['withdraw_enabled'] === 1 ? '1' : '0';
|
||||
}
|
||||
if (isset($input['withdraw_close_tip'])) {
|
||||
$clean['withdraw_close_tip'] = mb_substr(trim((string)$input['withdraw_close_tip']), 0, 200);
|
||||
}
|
||||
if (isset($input['withdraw_channels'])) {
|
||||
$chArr = is_array($input['withdraw_channels']) ? $input['withdraw_channels'] : explode(',', (string)$input['withdraw_channels']);
|
||||
$validCh = [];
|
||||
foreach ($chArr as $c) {
|
||||
$c = trim((string)$c);
|
||||
if (in_array($c, ['wechat', 'bank'], true) && !in_array($c, $validCh, true)) {
|
||||
$validCh[] = $c;
|
||||
}
|
||||
}
|
||||
if (empty($validCh)) {
|
||||
throw new \InvalidArgumentException('请至少勾选一种开放提现渠道');
|
||||
}
|
||||
$clean['withdraw_channels'] = implode(',', $validCh);
|
||||
}
|
||||
if (isset($input['withdraw_require_realname'])) {
|
||||
$clean['withdraw_require_realname'] = (int)$input['withdraw_require_realname'] === 1 ? '1' : '0';
|
||||
}
|
||||
|
||||
if (isset($input['withdraw_min_amount'])) {
|
||||
if (!is_numeric($input['withdraw_min_amount']) || (float)$input['withdraw_min_amount'] < 0.10) {
|
||||
throw new \InvalidArgumentException('符合微信小程序商家转账规范,单笔最低提现金额不得低于 ¥0.10');
|
||||
}
|
||||
$clean['withdraw_min_amount'] = number_format(round((float)$input['withdraw_min_amount'], 2), 2, '.', '');
|
||||
}
|
||||
if (isset($input['withdraw_max_amount'])) {
|
||||
if (!is_numeric($input['withdraw_max_amount']) || (float)$input['withdraw_max_amount'] > self::WX_TRANSFER_HARD_MAX) {
|
||||
throw new \InvalidArgumentException('微信商家转账官方规定单笔最高金额不得超过 ¥20,000.00');
|
||||
}
|
||||
$clean['withdraw_max_amount'] = number_format(round((float)$input['withdraw_max_amount'], 2), 2, '.', '');
|
||||
}
|
||||
if (isset($clean['withdraw_min_amount'], $clean['withdraw_max_amount']) && (float)$clean['withdraw_min_amount'] > (float)$clean['withdraw_max_amount']) {
|
||||
throw new \InvalidArgumentException('单笔最低提现金额不能大于单笔最高提现金额');
|
||||
}
|
||||
|
||||
if (isset($input['withdraw_daily_amount'])) {
|
||||
if (!is_numeric($input['withdraw_daily_amount']) || (float)$input['withdraw_daily_amount'] < 0) {
|
||||
throw new \InvalidArgumentException('单人单日累计提现上限不能为负数');
|
||||
}
|
||||
$clean['withdraw_daily_amount'] = number_format(round((float)$input['withdraw_daily_amount'], 2), 2, '.', '');
|
||||
if ((float)$clean['withdraw_daily_amount'] > 0 && isset($clean['withdraw_min_amount']) && (float)$clean['withdraw_daily_amount'] < (float)$clean['withdraw_min_amount']) {
|
||||
throw new \InvalidArgumentException('单人单日累计上限不能低于单笔最低提现金额');
|
||||
}
|
||||
}
|
||||
if (isset($input['withdraw_daily_count'])) {
|
||||
$clean['withdraw_daily_count'] = (string)max(0, (int)$input['withdraw_daily_count']);
|
||||
}
|
||||
|
||||
if (isset($input['withdraw_allow_weekdays'])) {
|
||||
$dayArr = is_array($input['withdraw_allow_weekdays']) ? $input['withdraw_allow_weekdays'] : explode(',', (string)$input['withdraw_allow_weekdays']);
|
||||
$validDays = [];
|
||||
foreach ($dayArr as $d) {
|
||||
$di = (int)$d;
|
||||
if ($di >= 1 && $di <= 7 && !in_array($di, $validDays, true)) {
|
||||
$validDays[] = $di;
|
||||
}
|
||||
}
|
||||
if (empty($validDays)) {
|
||||
throw new \InvalidArgumentException('请至少选择一天允许提现的周期');
|
||||
}
|
||||
sort($validDays);
|
||||
$clean['withdraw_allow_weekdays'] = implode(',', $validDays);
|
||||
}
|
||||
|
||||
if (isset($input['withdraw_time_start'])) {
|
||||
$ts = trim((string)$input['withdraw_time_start']);
|
||||
if (!preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $ts)) {
|
||||
throw new \InvalidArgumentException('每日开始时间格式须为 HH:mm(如 00:00)');
|
||||
}
|
||||
$clean['withdraw_time_start'] = $ts;
|
||||
}
|
||||
if (isset($input['withdraw_time_end'])) {
|
||||
$te = trim((string)$input['withdraw_time_end']);
|
||||
if (!preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $te)) {
|
||||
throw new \InvalidArgumentException('每日结束时间格式须为 HH:mm(如 23:59)');
|
||||
}
|
||||
$clean['withdraw_time_end'] = $te;
|
||||
}
|
||||
if (isset($clean['withdraw_time_start'], $clean['withdraw_time_end']) && $clean['withdraw_time_start'] >= $clean['withdraw_time_end']) {
|
||||
throw new \InvalidArgumentException('每日允许提现开始时间必须早于结束时间');
|
||||
}
|
||||
|
||||
if (isset($input['withdraw_fee_mode'])) {
|
||||
if (!in_array($input['withdraw_fee_mode'], ['percent', 'fixed', 'free'], true)) {
|
||||
throw new \InvalidArgumentException('请选择有效的手续费计收方式');
|
||||
}
|
||||
$clean['withdraw_fee_mode'] = $input['withdraw_fee_mode'];
|
||||
}
|
||||
if (isset($input['withdraw_fee_rate'])) {
|
||||
if (!is_numeric($input['withdraw_fee_rate']) || (float)$input['withdraw_fee_rate'] < 0 || (float)$input['withdraw_fee_rate'] > 50) {
|
||||
throw new \InvalidArgumentException('提现手续费率须在 0% ~ 50% 之间');
|
||||
}
|
||||
$clean['withdraw_fee_rate'] = number_format(round((float)$input['withdraw_fee_rate'], 2), 2, '.', '');
|
||||
}
|
||||
foreach (['withdraw_fee_fixed' => '单笔固定手续费', 'withdraw_fee_min' => '单笔最低保底手续费', 'withdraw_fee_max' => '单笔最高封顶手续费'] as $k => $label) {
|
||||
if (isset($input[$k])) {
|
||||
if (!is_numeric($input[$k]) || (float)$input[$k] < 0) {
|
||||
throw new \InvalidArgumentException($label . '不能为负数');
|
||||
}
|
||||
$clean[$k] = number_format(round((float)$input[$k], 2), 2, '.', '');
|
||||
}
|
||||
}
|
||||
if (isset($clean['withdraw_fee_min'], $clean['withdraw_fee_max'])) {
|
||||
$fMin = (float)$clean['withdraw_fee_min'];
|
||||
$fMax = (float)$clean['withdraw_fee_max'];
|
||||
if ($fMin > 0 && $fMax > 0 && $fMin > $fMax) {
|
||||
throw new \InvalidArgumentException('单笔最低保底手续费不能大于最高封顶手续费');
|
||||
}
|
||||
}
|
||||
|
||||
// 校验最低提现额扣除手续费后不低于微信官方 0.10 元底线
|
||||
$mergedPreview = array_merge(self::getAll(), $clean);
|
||||
$minTestAmt = (float)$mergedPreview['withdraw_min_amount'];
|
||||
if (($mergedPreview['withdraw_fee_mode'] ?? 'percent') === 'fixed' && $minTestAmt - (float)$mergedPreview['withdraw_fee_fixed'] < self::WX_TRANSFER_MIN_ARRIVE) {
|
||||
throw new \InvalidArgumentException('单笔最低提现金额扣除固定手续费后实际到账低于 ¥0.10,请调高最低提现额或调低固定手续费');
|
||||
}
|
||||
|
||||
if (isset($input['withdraw_transfer_mode'])) {
|
||||
if (!in_array($input['withdraw_transfer_mode'], ['wx_mch_transfer', 'offline_manual'], true)) {
|
||||
throw new \InvalidArgumentException('无效的微信渠道打款执行方式');
|
||||
}
|
||||
$clean['withdraw_transfer_mode'] = $input['withdraw_transfer_mode'];
|
||||
}
|
||||
if (isset($input['withdraw_audit_mode'])) {
|
||||
if (!in_array($input['withdraw_audit_mode'], ['manual', 'auto_small'], true)) {
|
||||
throw new \InvalidArgumentException('无效的提现审核模式');
|
||||
}
|
||||
$clean['withdraw_audit_mode'] = $input['withdraw_audit_mode'];
|
||||
}
|
||||
if (isset($input['withdraw_auto_max_amount'])) {
|
||||
if (!is_numeric($input['withdraw_auto_max_amount']) || (float)$input['withdraw_auto_max_amount'] < 0 || (float)$input['withdraw_auto_max_amount'] > self::WX_TRANSFER_HARD_MAX) {
|
||||
throw new \InvalidArgumentException('小额免审自动转账上限须在 ¥0 ~ ¥20,000 之间');
|
||||
}
|
||||
$clean['withdraw_auto_max_amount'] = number_format(round((float)$input['withdraw_auto_max_amount'], 2), 2, '.', '');
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'wx_transfer_scene_id' => ['label' => '微信转账场景ID', 'max' => 16],
|
||||
'wx_recv_perception' => ['label' => '微信收款用户感知', 'max' => 32],
|
||||
'wx_job_type' => ['label' => '微信场景报备-岗位类型', 'max' => 32],
|
||||
'wx_reward_desc' => ['label' => '微信场景报备-报酬说明', 'max' => 32],
|
||||
'wx_transfer_remark' => ['label' => '微信零钱转账备注', 'max' => 32],
|
||||
] as $k => $meta) {
|
||||
if (isset($input[$k])) {
|
||||
$val = trim((string)$input[$k]);
|
||||
if ($val === '') {
|
||||
throw new \InvalidArgumentException($meta['label'] . '不能为空(微信支付 APIv3 商家转账必填项)');
|
||||
}
|
||||
if (mb_strlen($val) > $meta['max']) {
|
||||
throw new \InvalidArgumentException($meta['label'] . '不能超过 ' . $meta['max'] . ' 个字符(微信接口长度限制)');
|
||||
}
|
||||
$clean[$k] = $val;
|
||||
}
|
||||
}
|
||||
|
||||
$now = time();
|
||||
Db::startTrans();
|
||||
try {
|
||||
foreach ($clean as $name => $val) {
|
||||
if (!array_key_exists($name, $defaults)) {
|
||||
continue;
|
||||
}
|
||||
$group = 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([
|
||||
'value' => $val,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
} else {
|
||||
Db::name('finance_config')->insert([
|
||||
'name' => $name,
|
||||
'group' => $group,
|
||||
'title' => $name,
|
||||
'value' => $val,
|
||||
'remark' => '',
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Db::commit();
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
self::clearCache();
|
||||
}
|
||||
}
|
||||
文件差异内容过多而无法显示
加载差异
@@ -1,130 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Config;
|
||||
use think\Db;
|
||||
use think\Log;
|
||||
|
||||
/**
|
||||
* 业务短信触达服务驱动组件
|
||||
* 覆盖:完工6位核销码下发、2小时首联时效预警、派单通知
|
||||
* 具备自动适配环境驱动(阿里云 / 腾讯云 / 本地日志安全兜底)
|
||||
*/
|
||||
class SmsService
|
||||
{
|
||||
/**
|
||||
* 发送订单完工 6 位核销验证码
|
||||
* @param string $mobile 客户手机号
|
||||
* @param string $verifyCode 6位验证码
|
||||
* @param string $orderNo 订单号
|
||||
* @return bool
|
||||
*/
|
||||
public static function sendVerifyCode($mobile, $verifyCode, $orderNo)
|
||||
{
|
||||
$content = "【优匠优服】您的工单 {$orderNo} 师傅已申请完工,验收验证码为:{$verifyCode}。请确认施工无误后将验证码告知师傅完成核销,切勿提前告知。";
|
||||
return self::dispatch($mobile, 'verify_code', [
|
||||
'code' => $verifyCode,
|
||||
'order_no' => $orderNo
|
||||
], $content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送师傅 2 小时首联时效超时预警短信
|
||||
* @param string $mobile 师傅手机号
|
||||
* @param string $orderNo 订单号
|
||||
* @param int $remainMinutes 剩余分钟数
|
||||
* @return bool
|
||||
*/
|
||||
public static function sendFirstContactWarning($mobile, $orderNo, $remainMinutes = 30)
|
||||
{
|
||||
$content = "【优匠优服】您承接的工单 {$orderNo} 距离2小时首联考核截止仅剩 {$remainMinutes} 分钟,请尽快电话联系客户确认上门时间并在线打卡,超时将自动回收大厅并扣减信誉分!";
|
||||
return self::dispatch($mobile, 'contact_warning', [
|
||||
'order_no' => $orderNo,
|
||||
'remain' => $remainMinutes
|
||||
], $content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送新工单接单/派单通知
|
||||
* @param string $mobile 师傅手机号
|
||||
* @param string $orderNo 订单号
|
||||
* @param string $serviceName 服务名称
|
||||
* @return bool
|
||||
*/
|
||||
public static function sendNewOrderNotice($mobile, $orderNo, $serviceName)
|
||||
{
|
||||
$content = "【优匠优服】您有新的待接工单 {$orderNo}({$serviceName}),请尽快前往师傅工作台查看并接单。";
|
||||
return self::dispatch($mobile, 'new_order', [
|
||||
'order_no' => $orderNo,
|
||||
'service_name' => $serviceName
|
||||
], $content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一短信分发网关
|
||||
* @param string $mobile 手机号
|
||||
* @param string $event 事件
|
||||
* @param array $params 变量参数
|
||||
* @param string $content 完整文本内容
|
||||
* @return bool
|
||||
*/
|
||||
public static function dispatch($mobile, $event, array $params, $content)
|
||||
{
|
||||
$mobile = trim((string)$mobile);
|
||||
if (strlen($mobile) !== 11) {
|
||||
Log::record("[SmsService] 无效手机号: {$mobile}", 'warning');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 记录到本地 fa_sms 短信流水表,保证可追溯性
|
||||
try {
|
||||
Db::name('sms')->insert([
|
||||
'event' => $event,
|
||||
'mobile' => $mobile,
|
||||
'code' => isset($params['code']) ? (string)$params['code'] : '',
|
||||
'times' => 0,
|
||||
'ip' => request() ? request()->ip() : '127.0.0.1',
|
||||
'createtime' => time()
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
// 忽略重复或日志写入异常
|
||||
}
|
||||
|
||||
// 获取当前配置驱动(默认为 local 本地安全开发模式)
|
||||
$driver = Config::get('site.sms_driver');
|
||||
if (empty($driver)) {
|
||||
$driver = 'local';
|
||||
}
|
||||
|
||||
if ($driver === 'aliyun') {
|
||||
return self::sendAliyun($mobile, $event, $params);
|
||||
} elseif ($driver === 'qcloud') {
|
||||
return self::sendQcloud($mobile, $event, $params);
|
||||
}
|
||||
|
||||
// 默认开发/模拟环境驱动:将真实内容打印至日志与控制台,返回成功
|
||||
Log::record("[SmsService::{$driver}] 发送至 {$mobile} | 事件: {$event} | 内容: {$content}", 'info');
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 阿里云短信发送接口
|
||||
*/
|
||||
protected static function sendAliyun($mobile, $event, array $params)
|
||||
{
|
||||
// 生产接入阿里云官方 SDK 规范
|
||||
Log::record("[SmsService::Aliyun] 发送短信至 {$mobile} 模板参数: " . json_encode($params, JSON_UNESCAPED_UNICODE), 'info');
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 腾讯云短信发送接口
|
||||
*/
|
||||
protected static function sendQcloud($mobile, $event, array $params)
|
||||
{
|
||||
// 生产接入腾讯云官方 SDK 规范
|
||||
Log::record("[SmsService::Qcloud] 发送短信至 {$mobile} 模板参数: " . json_encode($params, JSON_UNESCAPED_UNICODE), 'info');
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Config;
|
||||
use think\Log;
|
||||
|
||||
/**
|
||||
* 腾讯云实名核验与 OCR 服务组件
|
||||
* 封装腾讯云 API 3.0 TC3-HMAC-SHA256 签名,支持纯 API 身份证二要素权威比对与身份证文字识别
|
||||
*/
|
||||
class TencentVerifyService
|
||||
{
|
||||
const DEFAULT_REGION = 'ap-guangzhou';
|
||||
|
||||
/**
|
||||
* 获取腾讯云 SecretId(严格读取站点配置或 .env,不在源码内硬编码密钥)
|
||||
*/
|
||||
public static function getSecretId()
|
||||
{
|
||||
$id = class_exists('\\think\\Config') ? \think\Config::get('site.tencent_secret_id') : null;
|
||||
if (empty($id) && class_exists('\\think\\Env')) {
|
||||
$id = \think\Env::get('tencent.secret_id', '');
|
||||
}
|
||||
return trim((string)$id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取腾讯云 SecretKey(严格读取站点配置或 .env,不在源码内硬编码密钥)
|
||||
*/
|
||||
public static function getSecretKey()
|
||||
{
|
||||
$key = class_exists('\\think\\Config') ? \think\Config::get('site.tencent_secret_key') : null;
|
||||
if (empty($key) && class_exists('\\think\\Env')) {
|
||||
$key = \think\Env::get('tencent.secret_key', '');
|
||||
}
|
||||
return trim((string)$key);
|
||||
}
|
||||
|
||||
protected static function log($msg, $type = 'info')
|
||||
{
|
||||
if (class_exists('\\think\\Log')) {
|
||||
\think\Log::record($msg, $type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 腾讯云 COS 数据万象动态防伪水印生成(方案1:URL规则实时加盖,不破坏原图)
|
||||
*
|
||||
* @param string $imageUrl 原图访问地址
|
||||
* @param string $text 水印文字(默认:仅用于身份信息认证)
|
||||
* @return string 带数据万象水印规则的安全访问地址
|
||||
*/
|
||||
public static function getWatermarkUrl($imageUrl, $text = '仅用于身份信息认证')
|
||||
{
|
||||
$imageUrl = trim((string)$imageUrl);
|
||||
if (empty($imageUrl)) {
|
||||
return '';
|
||||
}
|
||||
if (strpos($imageUrl, 'myqcloud.com') !== false || strpos($imageUrl, 'cos.') !== false) {
|
||||
if (strpos($imageUrl, 'watermark') !== false) {
|
||||
return $imageUrl;
|
||||
}
|
||||
$b64Text = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($text));
|
||||
$b64Color = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode('#FFFFFF'));
|
||||
$delimiter = strpos($imageUrl, '?') !== false ? '&' : '?';
|
||||
return "{$imageUrl}{$delimiter}watermark/2/text/{$b64Text}/fill/{$b64Color}/fontsize/40/dissolve/85/shadow/60/gravity/center/degree/340";
|
||||
}
|
||||
return $imageUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 身份证二要素核验(权威公安数据源比对)
|
||||
* 传入真实姓名与身份证号码,校验二者是否一致与真实有效
|
||||
*
|
||||
* @param string $realname 真实姓名(如“张三”)
|
||||
* @param string $idCardNo 18位身份证号码
|
||||
* @return array ['code' => int, 'pass' => bool, 'msg' => string, 'raw' => array]
|
||||
*/
|
||||
public static function verifyIdCard($realname, $idCardNo)
|
||||
{
|
||||
$realname = trim((string)$realname);
|
||||
$idCardNo = strtoupper(trim((string)$idCardNo));
|
||||
|
||||
if (empty($realname) || empty($idCardNo)) {
|
||||
return [
|
||||
'code' => -1,
|
||||
'pass' => false,
|
||||
'msg' => '姓名和身份证号不能为空',
|
||||
'raw' => []
|
||||
];
|
||||
}
|
||||
|
||||
// 基础格式校验(18位合法身份证号格式)
|
||||
if (!preg_match('/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$/', $idCardNo)) {
|
||||
return [
|
||||
'code' => -2,
|
||||
'pass' => false,
|
||||
'msg' => '身份证号码格式不正确',
|
||||
'raw' => []
|
||||
];
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'Name' => $realname,
|
||||
'IdCard' => $idCardNo
|
||||
];
|
||||
|
||||
try {
|
||||
$resp = self::request('faceid', '2018-03-01', 'IdCardVerification', $payload);
|
||||
if (!isset($resp['Response'])) {
|
||||
return [
|
||||
'code' => -99,
|
||||
'pass' => false,
|
||||
'msg' => '核验服务未返回有效响应',
|
||||
'raw' => $resp
|
||||
];
|
||||
}
|
||||
|
||||
$response = $resp['Response'];
|
||||
|
||||
// 存在错误信息
|
||||
if (isset($response['Error'])) {
|
||||
$errCode = $response['Error']['Code'] ?? '';
|
||||
$errMsg = $response['Error']['Message'] ?? '核验服务异常';
|
||||
self::log("[TencentVerify] IdCardVerification Error: {$errCode} - {$errMsg}", 'error');
|
||||
return [
|
||||
'code' => -9,
|
||||
'pass' => false,
|
||||
'msg' => '实名核验接口调用失败:' . $errMsg,
|
||||
'raw' => $response
|
||||
];
|
||||
}
|
||||
|
||||
$result = (string)($response['Result'] ?? '');
|
||||
$desc = (string)($response['Description'] ?? '');
|
||||
|
||||
// Result: 0 一致, -1 不一致, -2 非法身份证号, -3 非法姓名, -4 证件库服务异常, -5 证件库中无此身份证记录
|
||||
if ($result === '0') {
|
||||
return [
|
||||
'code' => 0,
|
||||
'pass' => true,
|
||||
'msg' => '实名核验一致',
|
||||
'raw' => $response
|
||||
];
|
||||
}
|
||||
|
||||
$msgMap = [
|
||||
'-1' => '姓名与身份证号不匹配,请核对后重试',
|
||||
'-2' => '身份证号码不合法,请检查输入',
|
||||
'-3' => '姓名格式不合法,请确认无误',
|
||||
'-4' => '全国公安公民身份库系统繁忙,请稍后重试',
|
||||
'-5' => '全国身份库中无此身份证记录,请核对信息'
|
||||
];
|
||||
$friendlyMsg = $msgMap[$result] ?? ($desc ?: '实名核验未通过,请核对信息');
|
||||
|
||||
return [
|
||||
'code' => (int)$result,
|
||||
'pass' => false,
|
||||
'msg' => $friendlyMsg,
|
||||
'raw' => $response
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
self::log("[TencentVerify] Exception in verifyIdCard: " . $e->getMessage(), 'error');
|
||||
return [
|
||||
'code' => -999,
|
||||
'pass' => false,
|
||||
'msg' => '实名核验系统通信异常:' . $e->getMessage(),
|
||||
'raw' => []
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 身份证 OCR 文字识别
|
||||
* 支持公网 ImageUrl、本地文件路径自动 Base64 转换以及原始 Base64 编码
|
||||
*
|
||||
* @param string $image 图片 URL 或本地文件相对路径/Base64
|
||||
* @param string $cardSide FRONT:人像面, BACK:国徽面
|
||||
* @return array ['code' => int, 'success' => bool, 'data' => array, 'msg' => string]
|
||||
*/
|
||||
public static function idCardOcr($image, $cardSide = 'FRONT')
|
||||
{
|
||||
$image = trim((string)$image);
|
||||
$cardSide = strtoupper(trim((string)$cardSide)) === 'BACK' ? 'BACK' : 'FRONT';
|
||||
|
||||
if (empty($image)) {
|
||||
return [
|
||||
'code' => -1,
|
||||
'success' => false,
|
||||
'data' => [],
|
||||
'msg' => '图片地址不能为空'
|
||||
];
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'CardSide' => $cardSide
|
||||
];
|
||||
|
||||
// 识别输入类型:若为 Base64 或本地文件,优先使用 ImageBase64(保障内网或CDN延迟时依然100%识别成功)
|
||||
if (strpos($image, 'data:image') === 0) {
|
||||
$payload['ImageBase64'] = preg_replace('/^data:image\/\w+;base64,/', '', $image);
|
||||
} elseif (strlen($image) > 500 && strpos($image, 'http') !== 0) {
|
||||
$payload['ImageBase64'] = $image;
|
||||
} elseif (preg_match('/^https?:\/\//i', $image)) {
|
||||
$payload['ImageUrl'] = $image;
|
||||
} else {
|
||||
// 本地相对路径检查
|
||||
$publicPath = defined('ROOT_PATH') ? (ROOT_PATH . 'public') : (dirname(dirname(dirname(__DIR__))) . '/public');
|
||||
$localFile = $publicPath . (strpos($image, '/') === 0 ? '' : '/') . $image;
|
||||
if (file_exists($localFile) && is_readable($localFile)) {
|
||||
$payload['ImageBase64'] = base64_encode(file_get_contents($localFile));
|
||||
} else {
|
||||
$cdnUrl = class_exists('\\think\\Config') ? (\think\Config::get('upload.cdnurl') ?: \think\Config::get('site.cdnurl')) : '';
|
||||
$payload['ImageUrl'] = !empty($cdnUrl) ? (rtrim($cdnUrl, '/') . '/' . ltrim($image, '/')) : $image;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$resp = self::request('ocr', '2018-11-19', 'IDCardOCR', $payload);
|
||||
if (!isset($resp['Response'])) {
|
||||
return [
|
||||
'code' => -99,
|
||||
'success' => false,
|
||||
'data' => [],
|
||||
'msg' => 'OCR 服务无有效响应'
|
||||
];
|
||||
}
|
||||
|
||||
$response = $resp['Response'];
|
||||
if (isset($response['Error'])) {
|
||||
$errMsg = $response['Error']['Message'] ?? '识别失败';
|
||||
return [
|
||||
'code' => -2,
|
||||
'success' => false,
|
||||
'data' => [],
|
||||
'msg' => '身份证识别失败:' . $errMsg
|
||||
];
|
||||
}
|
||||
|
||||
$parsed = [
|
||||
'side' => $cardSide,
|
||||
];
|
||||
|
||||
if ($cardSide === 'FRONT') {
|
||||
$parsed['name'] = (string)($response['Name'] ?? '');
|
||||
$parsed['sex'] = (string)($response['Sex'] ?? '');
|
||||
$parsed['nation'] = (string)($response['Nation'] ?? '');
|
||||
$parsed['birth'] = (string)($response['Birth'] ?? '');
|
||||
$parsed['address'] = (string)($response['Address'] ?? '');
|
||||
$parsed['idcard_no'] = (string)($response['IdNum'] ?? '');
|
||||
} else {
|
||||
$authority = (string)($response['Authority'] ?? '');
|
||||
$validDate = (string)($response['ValidDate'] ?? '');
|
||||
$parsed['authority'] = $authority;
|
||||
$parsed['valid_date'] = $validDate;
|
||||
|
||||
// 智能检测身份证是否已过有效期
|
||||
$expireInfo = self::checkIdCardExpired($validDate);
|
||||
$parsed['is_expired'] = $expireInfo['is_expired'];
|
||||
$parsed['expire_info'] = $expireInfo;
|
||||
}
|
||||
|
||||
return [
|
||||
'code' => 0,
|
||||
'success' => true,
|
||||
'data' => $parsed,
|
||||
'msg' => '识别成功'
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
self::log("[TencentVerify] Exception in idCardOcr: " . $e->getMessage(), 'error');
|
||||
return [
|
||||
'code' => -999,
|
||||
'success' => false,
|
||||
'data' => [],
|
||||
'msg' => 'OCR 系统通信异常:' . $e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送腾讯云 API 3.0 请求 (TC3-HMAC-SHA256 签名)
|
||||
*
|
||||
* @param string $service 服务标识 (如 faceid, ocr)
|
||||
* @param string $version 接口版本 (如 2018-03-01)
|
||||
* @param string $action 接口动作 (如 IdCardVerification)
|
||||
* @param array $payload 请求体 JSON 字典
|
||||
* @param string $region 地域标识
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function request($service, $version, $action, array $payload, $region = '')
|
||||
{
|
||||
$secretId = self::getSecretId();
|
||||
$secretKey = self::getSecretKey();
|
||||
if ($secretId === '' || $secretKey === '') {
|
||||
throw new \Exception('腾讯云实名核验密钥未配置,请在后台站点配置或 .env 中设置 tencent_secret_id / tencent_secret_key');
|
||||
}
|
||||
$region = !empty($region) ? $region : self::DEFAULT_REGION;
|
||||
$host = "{$service}.tencentcloudapi.com";
|
||||
|
||||
$payloadJson = json_encode($payload, JSON_UNESCAPED_UNICODE);
|
||||
$timestamp = time();
|
||||
$date = gmdate("Y-m-d", $timestamp);
|
||||
|
||||
// 1. 规范请求串
|
||||
$httpRequestMethod = "POST";
|
||||
$canonicalUri = "/";
|
||||
$canonicalQueryString = "";
|
||||
$canonicalHeaders = "content-type:application/json; charset=utf-8\nhost:" . $host . "\nx-tc-action:" . strtolower($action) . "\n";
|
||||
$signedHeaders = "content-type;host;x-tc-action";
|
||||
$hashedRequestPayload = hash("sha256", $payloadJson);
|
||||
$canonicalRequest = $httpRequestMethod . "\n"
|
||||
. $canonicalUri . "\n"
|
||||
. $canonicalQueryString . "\n"
|
||||
. $canonicalHeaders . "\n"
|
||||
. $signedHeaders . "\n"
|
||||
. $hashedRequestPayload;
|
||||
|
||||
// 2. 待签名字符串
|
||||
$algorithm = "TC3-HMAC-SHA256";
|
||||
$credentialScope = $date . "/" . $service . "/tc3_request";
|
||||
$hashedCanonicalRequest = hash("sha256", $canonicalRequest);
|
||||
$stringToSign = $algorithm . "\n"
|
||||
. $timestamp . "\n"
|
||||
. $credentialScope . "\n"
|
||||
. $hashedCanonicalRequest;
|
||||
|
||||
// 3. 计算签名
|
||||
$secretDate = hash_hmac("sha256", $date, "TC3" . $secretKey, true);
|
||||
$secretService = hash_hmac("sha256", $service, $secretDate, true);
|
||||
$secretSigning = hash_hmac("sha256", "tc3_request", $secretService, true);
|
||||
$signature = hash_hmac("sha256", $stringToSign, $secretSigning);
|
||||
|
||||
// 4. 组装请求头
|
||||
$authorization = $algorithm . " "
|
||||
. "Credential=" . $secretId . "/" . $credentialScope . ", "
|
||||
. "SignedHeaders=" . $signedHeaders . ", "
|
||||
. "Signature=" . $signature;
|
||||
|
||||
$headers = [
|
||||
"Authorization: " . $authorization,
|
||||
"Content-Type: application/json; charset=utf-8",
|
||||
"Host: " . $host,
|
||||
"X-TC-Action: " . $action,
|
||||
"X-TC-Timestamp: " . $timestamp,
|
||||
"X-TC-Version: " . $version,
|
||||
"X-TC-Region: " . $region
|
||||
];
|
||||
|
||||
// 5. 执行 cURL 请求
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, "https://" . $host);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadJson);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$curlError = curl_error($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($curlError) {
|
||||
throw new \Exception("cURL 执行失败: " . $curlError);
|
||||
}
|
||||
|
||||
$decoded = json_decode($response, true);
|
||||
if ($decoded === null) {
|
||||
throw new \Exception("解析腾讯云响应 JSON 失败(HTTP {$httpCode}): {$response}");
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* 智能检测身份证是否已过有效期
|
||||
*
|
||||
* @param string $validDateStr 腾讯云 OCR 返回的有效期字符串,如 "2024.01.15-2044.01.15" 或 "2014.05.20-长期"
|
||||
* @return array ['has_date' => bool, 'is_expired' => bool, 'is_permanent' => bool, 'expire_date' => string, 'text' => string]
|
||||
*/
|
||||
public static function checkIdCardExpired($validDateStr)
|
||||
{
|
||||
$validDateStr = trim((string)$validDateStr);
|
||||
if (empty($validDateStr)) {
|
||||
return [
|
||||
'has_date' => false,
|
||||
'is_expired' => false,
|
||||
'is_permanent' => false,
|
||||
'expire_date' => '',
|
||||
'text' => '未检测到有效期限'
|
||||
];
|
||||
}
|
||||
|
||||
// 若包含“长期”字样,判定永久有效
|
||||
if (mb_strpos($validDateStr, '长期') !== false) {
|
||||
return [
|
||||
'has_date' => true,
|
||||
'is_expired' => false,
|
||||
'is_permanent' => true,
|
||||
'expire_date' => '长期',
|
||||
'text' => '长期有效'
|
||||
];
|
||||
}
|
||||
|
||||
// 正则提取所有符合 YYYY.MM.DD / YYYY-MM-DD / YYYYMMDD 的日期片段
|
||||
preg_match_all('/(\d{4})[\.\-\/年]?(\d{2})[\.\-\/月]?(\d{2})/', $validDateStr, $matches);
|
||||
if (!empty($matches[0])) {
|
||||
$lastIdx = count($matches[0]) - 1;
|
||||
$year = $matches[1][$lastIdx];
|
||||
$month = $matches[2][$lastIdx];
|
||||
$day = $matches[3][$lastIdx];
|
||||
$formatted = "{$year}-{$month}-{$day}";
|
||||
|
||||
$expireTs = strtotime("{$formatted} 23:59:59");
|
||||
$todayTs = strtotime(date('Y-m-d 00:00:00'));
|
||||
$isExpired = ($expireTs < $todayTs);
|
||||
|
||||
return [
|
||||
'has_date' => true,
|
||||
'is_expired' => $isExpired,
|
||||
'is_permanent' => false,
|
||||
'expire_date' => $formatted,
|
||||
'text' => $formatted . ($isExpired ? '(已过期)' : '(有效)')
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'has_date' => true,
|
||||
'is_expired' => false,
|
||||
'is_permanent' => false,
|
||||
'expire_date' => $validDateStr,
|
||||
'text' => $validDateStr
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -11,20 +11,17 @@ use think\Log;
|
||||
*/
|
||||
class TiandituService
|
||||
{
|
||||
/** 默认天地图服务 Key(可在 application/config.php 或后台全局配置覆盖) */
|
||||
const DEFAULT_KEY = '369ea1edc677b9e3746093f8d9dc4465';
|
||||
|
||||
/**
|
||||
* 获取天地图 Key
|
||||
* 获取天地图 Key(严格读取站点配置或 .env,不在源码内硬编码密钥)
|
||||
* @return string
|
||||
*/
|
||||
public static function getKey()
|
||||
{
|
||||
$key = Config::get('site.tianditu_key');
|
||||
if (empty($key)) {
|
||||
$key = self::DEFAULT_KEY;
|
||||
if (empty($key) && class_exists('\\think\\Env')) {
|
||||
$key = \think\Env::get('tianditu.key', '');
|
||||
}
|
||||
return $key;
|
||||
return trim((string)$key);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -40,6 +37,10 @@ class TiandituService
|
||||
}
|
||||
|
||||
$key = self::getKey();
|
||||
if ($key === '') {
|
||||
Log::record('[TiandituService] 天地图密钥 site.tianditu_key 未配置,无法执行正地理编码', 'error');
|
||||
return null;
|
||||
}
|
||||
$url = 'https://api.tianditu.gov.cn/geocoder?ds=' . urlencode(json_encode(['keyWord' => $address])) . '&tk=' . $key;
|
||||
|
||||
$response = self::httpGet($url);
|
||||
@@ -75,6 +76,10 @@ class TiandituService
|
||||
}
|
||||
|
||||
$key = self::getKey();
|
||||
if ($key === '') {
|
||||
Log::record('[TiandituService] 天地图密钥 site.tianditu_key 未配置,无法执行逆地理编码', 'error');
|
||||
return null;
|
||||
}
|
||||
$postData = [
|
||||
'postStr' => json_encode([
|
||||
'lon' => $lng,
|
||||
@@ -108,6 +113,298 @@ class TiandituService
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关键词地点检索(POI 搜索 + 正地理编码融合兜底)
|
||||
* @param string $keyword 地名/区域/小区关键词
|
||||
* @param int $limit 最多返回条数
|
||||
* @param string $city 可选限定城市名,提高同城检索命中率
|
||||
* @param float|null $nearLat 可选参考中心纬度(用于计算距离展示)
|
||||
* @param float|null $nearLng 可选参考中心经度
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public static function searchPlaces($keyword, $limit = 10, $city = '', $nearLat = null, $nearLng = null)
|
||||
{
|
||||
$keyword = trim((string)$keyword);
|
||||
if ($keyword === '') {
|
||||
return [];
|
||||
}
|
||||
$limit = min(20, max(1, (int)$limit));
|
||||
$key = self::getKey();
|
||||
if ($key === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$city = trim((string)$city);
|
||||
$effectiveQuery = $keyword;
|
||||
if ($city !== '' && mb_strpos($keyword, mb_substr($city, 0, 2)) === false) {
|
||||
$effectiveQuery = $city . ' ' . $keyword;
|
||||
}
|
||||
|
||||
$results = [];
|
||||
$seen = [];
|
||||
$hasNear = $nearLat !== null && $nearLng !== null && (abs((float)$nearLat) > 0.0001 || abs((float)$nearLng) > 0.0001);
|
||||
|
||||
$pois = self::requestPoiSearch([
|
||||
'keyWord' => $effectiveQuery,
|
||||
'level' => '12',
|
||||
'mapBound' => '73.0,3.0,136.0,54.0',
|
||||
'queryType' => '1',
|
||||
'count' => (string)$limit,
|
||||
'start' => '0',
|
||||
], $key);
|
||||
|
||||
// 若限定城市后结果为空,放宽至全国关键词再查一次
|
||||
if (empty($pois) && $effectiveQuery !== $keyword) {
|
||||
$pois = self::requestPoiSearch([
|
||||
'keyWord' => $keyword,
|
||||
'level' => '12',
|
||||
'mapBound' => '73.0,3.0,136.0,54.0',
|
||||
'queryType' => '1',
|
||||
'count' => (string)$limit,
|
||||
'start' => '0',
|
||||
], $key);
|
||||
}
|
||||
|
||||
foreach ($pois as $poi) {
|
||||
$item = self::formatPoiItem($poi, $keyword, '', $hasNear ? (float)$nearLat : null, $hasNear ? (float)$nearLng : null);
|
||||
if ($item === null) {
|
||||
continue;
|
||||
}
|
||||
$dedupKey = mb_strtolower($item['name']) . '|' . round($item['lat'], 4) . '|' . round($item['lng'], 4);
|
||||
if (isset($seen[$dedupKey])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$dedupKey] = true;
|
||||
$results[] = $item;
|
||||
}
|
||||
|
||||
// 若属于行政区划或短关键词且结果偏少,补充一次正地理编码结果置顶
|
||||
$geo = self::geocoder($effectiveQuery) ?: ($effectiveQuery !== $keyword ? self::geocoder($keyword) : null);
|
||||
if (is_array($geo) && (!empty($geo['lng']) && !empty($geo['lat']))) {
|
||||
$geoLng = round((float)$geo['lng'], 6);
|
||||
$geoLat = round((float)$geo['lat'], 6);
|
||||
$regeo = self::regeocoder($geoLat, $geoLng);
|
||||
$cityLabel = '';
|
||||
$districtLabel = '';
|
||||
$fullLabel = $keyword;
|
||||
if (is_array($regeo)) {
|
||||
$cityLabel = trim((string)($regeo['city'] ?: ($regeo['province'] ?? '')));
|
||||
$districtLabel = trim((string)($regeo['district'] ?? ''));
|
||||
$fullLabel = trim(($regeo['province'] ?? '') . ' ' . $cityLabel . ' ' . $districtLabel);
|
||||
if (!empty($regeo['formatted_address'])) {
|
||||
$fullLabel = $regeo['formatted_address'];
|
||||
}
|
||||
}
|
||||
$distM = $hasNear ? (int)round(self::distance((float)$nearLat, (float)$nearLng, $geoLat, $geoLng)) : null;
|
||||
$geoDedup = mb_strtolower($keyword) . '|' . round($geoLat, 4) . '|' . round($geoLng, 4);
|
||||
if (!isset($seen[$geoDedup])) {
|
||||
array_unshift($results, [
|
||||
'name' => $keyword,
|
||||
'address' => $fullLabel ?: $keyword,
|
||||
'city' => $cityLabel,
|
||||
'district' => $districtLabel,
|
||||
'lng' => $geoLng,
|
||||
'lat' => $geoLat,
|
||||
'distance_m' => $distM,
|
||||
'distance_text' => self::formatMetersText($distM),
|
||||
'category' => 'area',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return array_slice($results, 0, $limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于经纬度的周边真实 POI 地标检索(配合地图选点展示周边小区/大厦/广场)
|
||||
* @param float $lat 中心纬度
|
||||
* @param float $lng 中心经度
|
||||
* @param string $category all|residential|office|plaza
|
||||
* @param int $radius 搜索半径(米,默认 3000)
|
||||
* @param int $limit 最多返回条数
|
||||
* @return array{center: array<string,mixed>|null, list: array<int, array<string,mixed>>}
|
||||
*/
|
||||
public static function nearbyPlaces($lat, $lng, $category = 'all', $radius = 3000, $limit = 14)
|
||||
{
|
||||
$lat = round((float)$lat, 6);
|
||||
$lng = round((float)$lng, 6);
|
||||
$limit = min(20, max(1, (int)$limit));
|
||||
$radius = max(500, min(10000, (int)$radius));
|
||||
|
||||
if (abs($lat) < 0.0001 && abs($lng) < 0.0001) {
|
||||
return ['center' => null, 'list' => []];
|
||||
}
|
||||
|
||||
$regeo = self::regeocoder($lat, $lng);
|
||||
$centerCity = is_array($regeo) ? trim((string)($regeo['city'] ?: ($regeo['province'] ?? ''))) : '';
|
||||
$centerDistrict = is_array($regeo) ? trim((string)($regeo['district'] ?? '')) : '';
|
||||
$centerPoi = is_array($regeo) ? trim((string)($regeo['poi'] ?? '')) : '';
|
||||
$centerRoad = is_array($regeo) ? trim((string)($regeo['road'] ?? '')) : '';
|
||||
$centerFormatted = is_array($regeo) ? trim((string)($regeo['formatted_address'] ?? '')) : '';
|
||||
$centerName = $centerPoi !== '' ? $centerPoi : ($centerRoad !== '' ? $centerRoad : ($centerDistrict !== '' ? ($centerDistrict . '附近') : '当前地图中心'));
|
||||
$centerAddress = $centerFormatted !== '' ? $centerFormatted : trim($centerCity . $centerDistrict . $centerRoad);
|
||||
|
||||
$centerInfo = [
|
||||
'name' => $centerName,
|
||||
'address' => $centerAddress ?: '已选定坐标点位',
|
||||
'province' => is_array($regeo) ? trim((string)($regeo['province'] ?? '')) : '',
|
||||
'city' => $centerCity,
|
||||
'district' => $centerDistrict,
|
||||
'road' => $centerRoad,
|
||||
'poi' => $centerPoi,
|
||||
'formatted_address' => $centerFormatted,
|
||||
'lng' => $lng,
|
||||
'lat' => $lat,
|
||||
];
|
||||
|
||||
$list = [];
|
||||
$seen = [];
|
||||
|
||||
// 中心位置锚点本身固定作为首条
|
||||
$list[] = [
|
||||
'name' => $centerName,
|
||||
'address' => $centerAddress ?: '当前选定中心点',
|
||||
'city' => $centerCity,
|
||||
'district' => $centerDistrict,
|
||||
'lng' => $lng,
|
||||
'lat' => $lat,
|
||||
'distance_m' => 0,
|
||||
'distance_text' => '当前点',
|
||||
'category' => 'center',
|
||||
'is_center' => 1,
|
||||
];
|
||||
$seen[mb_strtolower($centerName)] = true;
|
||||
|
||||
$key = self::getKey();
|
||||
if ($key !== '') {
|
||||
$categoryKeywordMap = [
|
||||
'residential' => [['kw' => '小区', 'cat' => 'residential']],
|
||||
'office' => [['kw' => '大厦', 'cat' => 'office']],
|
||||
'plaza' => [['kw' => '广场', 'cat' => 'plaza']],
|
||||
'all' => [
|
||||
['kw' => '小区', 'cat' => 'residential'],
|
||||
['kw' => '大厦', 'cat' => 'office'],
|
||||
['kw' => '广场', 'cat' => 'plaza'],
|
||||
],
|
||||
];
|
||||
$queries = $categoryKeywordMap[$category] ?? $categoryKeywordMap['all'];
|
||||
$perCount = count($queries) > 1 ? 6 : $limit;
|
||||
$poiRows = [];
|
||||
|
||||
foreach ($queries as $qItem) {
|
||||
$rawPois = self::requestPoiSearch([
|
||||
'keyWord' => $qItem['kw'],
|
||||
'level' => '15',
|
||||
'queryType' => '3',
|
||||
'pointLonlat' => $lng . ',' . $lat,
|
||||
'queryRadius' => (string)$radius,
|
||||
'count' => (string)$perCount,
|
||||
'start' => '0',
|
||||
], $key);
|
||||
|
||||
foreach ($rawPois as $rp) {
|
||||
$item = self::formatPoiItem($rp, $qItem['kw'], $qItem['cat'], $lat, $lng, $centerCity, $centerDistrict);
|
||||
if ($item === null) {
|
||||
continue;
|
||||
}
|
||||
$nameKey = mb_strtolower($item['name']);
|
||||
if (isset($seen[$nameKey])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$nameKey] = true;
|
||||
$poiRows[] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
usort($poiRows, function ($a, $b) {
|
||||
return ((int)($a['distance_m'] ?? 999999)) <=> ((int)($b['distance_m'] ?? 999999));
|
||||
});
|
||||
|
||||
$list = array_merge($list, array_slice($poiRows, 0, max(0, $limit - 1)));
|
||||
}
|
||||
|
||||
return [
|
||||
'center' => $centerInfo,
|
||||
'list' => $list,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一请求天地图 v2/search 接口
|
||||
*/
|
||||
protected static function requestPoiSearch(array $postParams, $key)
|
||||
{
|
||||
$postStr = json_encode($postParams, JSON_UNESCAPED_UNICODE);
|
||||
$url = 'https://api.tianditu.gov.cn/v2/search?postStr=' . urlencode($postStr) . '&type=query&tk=' . $key;
|
||||
$resp = self::httpGet($url);
|
||||
if (!$resp) {
|
||||
return [];
|
||||
}
|
||||
$data = json_decode($resp, true);
|
||||
if (is_array($data) && !empty($data['pois']) && is_array($data['pois'])) {
|
||||
return $data['pois'];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一标准化 POI 输出项,避免搜索与周边查询逻辑重复
|
||||
*/
|
||||
protected static function formatPoiItem(array $poi, $fallbackName, $category = '', $refLat = null, $refLng = null, $defaultCity = '', $defaultDistrict = '')
|
||||
{
|
||||
if (empty($poi['lonlat'])) {
|
||||
return null;
|
||||
}
|
||||
$parts = explode(',', (string)$poi['lonlat']);
|
||||
if (count($parts) !== 2) {
|
||||
return null;
|
||||
}
|
||||
$lng = round((float)$parts[0], 6);
|
||||
$lat = round((float)$parts[1], 6);
|
||||
if (abs($lat) < 0.0001 && abs($lng) < 0.0001) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$distM = null;
|
||||
if ($refLat !== null && $refLng !== null) {
|
||||
$distM = (int)round(self::distance($refLat, $refLng, $lat, $lng));
|
||||
} elseif (!empty($poi['distance'])) {
|
||||
$rawDist = strtolower(trim((string)$poi['distance']));
|
||||
if (strpos($rawDist, 'km') !== false) {
|
||||
$distM = (int)round((float)str_replace('km', '', $rawDist) * 1000);
|
||||
} else {
|
||||
$distM = (int)round((float)str_replace('m', '', $rawDist));
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'name' => trim((string)($poi['name'] ?? $fallbackName)),
|
||||
'address' => trim((string)($poi['address'] ?? '')),
|
||||
'city' => trim((string)($poi['city'] ?? $defaultCity)),
|
||||
'district' => trim((string)($poi['county'] ?? $defaultDistrict)),
|
||||
'lng' => $lng,
|
||||
'lat' => $lat,
|
||||
'distance_m' => $distM,
|
||||
'distance_text' => self::formatMetersText($distM),
|
||||
'category' => $category,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 米数转紧凑展示距离
|
||||
*/
|
||||
protected static function formatMetersText($meters)
|
||||
{
|
||||
if ($meters === null) {
|
||||
return '';
|
||||
}
|
||||
$m = (int)$meters;
|
||||
if ($m < 1000) {
|
||||
return max(10, $m) . 'm';
|
||||
}
|
||||
return round($m / 1000, 2) . 'km';
|
||||
}
|
||||
|
||||
/**
|
||||
* 高精度两点大圆球面距离计算(Haversine Formula)
|
||||
* @param float $lat1 起点纬度
|
||||
@@ -179,10 +476,13 @@ class TiandituService
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
|
||||
$result = curl_exec($ch);
|
||||
if ($result === false) {
|
||||
Log::record('[TiandituService] curl_exec 失败: ' . curl_error($ch), 'warning');
|
||||
}
|
||||
curl_close($ch);
|
||||
return $result;
|
||||
}
|
||||
|
||||
@@ -17,31 +17,46 @@ class WxLogin
|
||||
*/
|
||||
public static function jscode2session($code)
|
||||
{
|
||||
$appid = \think\Env::get('wechat.appid');
|
||||
$secret = \think\Env::get('wechat.secret');
|
||||
if (!$appid || !$secret) {
|
||||
return ['error' => '微信登录未配置'];
|
||||
$appid = trim((string)\think\Env::get('wechat.appid', ''));
|
||||
$secret = trim((string)\think\Env::get('wechat.secret', ''));
|
||||
if ($appid === '' || $secret === '') {
|
||||
return ['error' => '微信登录参数未配置完整(请检查 server/.env 的 wechat.appid 与 wechat.secret)', 'errcode' => -1001];
|
||||
}
|
||||
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid
|
||||
. '&secret=' . $secret
|
||||
$code = trim((string)$code);
|
||||
if ($code === '') {
|
||||
return ['error' => '缺少微信登录临时凭证 code,请在微信小程序内重新打开重试', 'errcode' => -1002];
|
||||
}
|
||||
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . urlencode($appid)
|
||||
. '&secret=' . urlencode($secret)
|
||||
. '&js_code=' . urlencode($code)
|
||||
. '&grant_type=authorization_code';
|
||||
$ctx = stream_context_create(['http' => ['timeout' => 8, 'ignore_errors' => true]]);
|
||||
$ctx = stream_context_create([
|
||||
'http' => ['timeout' => 8, 'ignore_errors' => true],
|
||||
'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
|
||||
]);
|
||||
$resp = @file_get_contents($url, false, $ctx);
|
||||
if ($resp === false) {
|
||||
return ['error' => '微信服务不可达,请稍后重试'];
|
||||
$lastErr = error_get_last();
|
||||
$errHint = !empty($lastErr['message']) ? $lastErr['message'] : '网络超时或 SSL 证书校验失败';
|
||||
\think\Log::error('[WxLogin::jscode2session] HTTP请求失败: ' . $errHint);
|
||||
return ['error' => '连接微信授权接口失败(请检查服务器外网HTTPS与CA根证书配置)', 'errcode' => -1003];
|
||||
}
|
||||
$wx = json_decode($resp, true);
|
||||
if (empty($wx['openid'])) {
|
||||
$ec = isset($wx['errcode']) ? (int)$wx['errcode'] : 0;
|
||||
$em = isset($wx['errmsg']) ? $wx['errmsg'] : '未知错误';
|
||||
if (!is_array($wx) || empty($wx['openid'])) {
|
||||
$ec = isset($wx['errcode']) ? (int)$wx['errcode'] : -1004;
|
||||
$em = isset($wx['errmsg']) ? (string)$wx['errmsg'] : '接口返回报文无效';
|
||||
$hint = [
|
||||
40029 => '小程序 appid 与服务端配置不一致:请确认 manifest.json 的 mp-weixin.appid 为 ' . $appid,
|
||||
40125 => 'appsecret 配置错误,请检查 .env 的 [wechat] secret',
|
||||
45011 => '登录请求过于频繁,请稍后重试',
|
||||
40226 => '该微信账号被风控限制,请稍后再试',
|
||||
-1 => '微信登录服务暂时繁忙,请稍后重试',
|
||||
40029 => '微信临时登录凭证 code 无效或小程序 AppID 与服务端配置不一致(服务端配置为:' . $appid . ')',
|
||||
40125 => '微信小程序密钥 appsecret 配置错误,请检查 server/.env 的 [wechat] secret',
|
||||
40163 => '微信登录凭证 code 已被使用过一次,请重新点击操作获取新授权',
|
||||
41002 => '请求缺少小程序 AppID 参数',
|
||||
41004 => '请求缺少小程序密钥 appsecret 参数',
|
||||
45011 => '微信登录请求过于频繁触发限流,请稍后再试',
|
||||
40226 => '该微信账号触发微信安全风控拦截,暂时无法授权登录',
|
||||
];
|
||||
$msg = isset($hint[$ec]) ? $hint[$ec] : ('微信登录失败(' . $ec . '):' . $em);
|
||||
$msg = isset($hint[$ec]) ? $hint[$ec] : ('微信授权登录校验未通过(微信错误码:' . $ec . '),请核对小程序 AppID/Secret 配置或重试');
|
||||
\think\Log::error("[WxLogin::jscode2session] errcode={$ec}, errmsg={$em}");
|
||||
return ['error' => $msg, 'errcode' => $ec];
|
||||
}
|
||||
return $wx;
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
/**
|
||||
* 微信支付 APIv3 结构化业务与网关异常
|
||||
*
|
||||
* 用于向业务层准确传递微信错误码、HTTP 状态码、cURL 错误码、
|
||||
* 是否属于“超时/状态不确定需先查单”类故障以及供管理员阅读的中文诊断原因。
|
||||
*/
|
||||
class WxPayException extends \RuntimeException
|
||||
{
|
||||
/** @var string 结构化错误码(如 NOT_ENOUGH / NO_AUTH / CURL_28 / HTTP_502) */
|
||||
protected $wxCode = '';
|
||||
|
||||
/** @var int HTTP 响应状态码 */
|
||||
protected $httpCode = 0;
|
||||
|
||||
/** @var int cURL 错误码 */
|
||||
protected $curlErrno = 0;
|
||||
|
||||
/** @var bool 是否属于网络超时或网关 5xx 等“微信可能已受理”的不确定状态 */
|
||||
protected $isUncertain = false;
|
||||
|
||||
/** @var string 脱敏后的原始网关细节 */
|
||||
protected $rawDetail = '';
|
||||
|
||||
public function __construct(
|
||||
$message,
|
||||
$wxCode = '',
|
||||
$httpCode = 0,
|
||||
$curlErrno = 0,
|
||||
$isUncertain = false,
|
||||
$rawDetail = '',
|
||||
\Throwable $previous = null
|
||||
) {
|
||||
parent::__construct((string)$message, (int)($httpCode ?: $curlErrno), $previous);
|
||||
$this->wxCode = (string)$wxCode;
|
||||
$this->httpCode = (int)$httpCode;
|
||||
$this->curlErrno = (int)$curlErrno;
|
||||
$this->isUncertain = (bool)$isUncertain;
|
||||
$this->rawDetail = (string)$rawDetail;
|
||||
}
|
||||
|
||||
public function getWxCode()
|
||||
{
|
||||
return $this->wxCode;
|
||||
}
|
||||
|
||||
public function getHttpCode()
|
||||
{
|
||||
return $this->httpCode;
|
||||
}
|
||||
|
||||
public function getCurlErrno()
|
||||
{
|
||||
return $this->curlErrno;
|
||||
}
|
||||
|
||||
public function isUncertain()
|
||||
{
|
||||
return $this->isUncertain;
|
||||
}
|
||||
|
||||
public function getRawDetail()
|
||||
{
|
||||
return $this->rawDetail;
|
||||
}
|
||||
}
|
||||
文件差异内容过多而无法显示
加载差异
@@ -199,28 +199,13 @@ class Config extends Model
|
||||
/**
|
||||
* 刷新配置文件
|
||||
*/
|
||||
public static function refreshFile()
|
||||
public static function refreshFile($removedKey = '')
|
||||
{
|
||||
//如果没有配置权限无法进行修改
|
||||
if (!\app\admin\library\Auth::instance()->check('general/config/edit')) {
|
||||
return false;
|
||||
}
|
||||
$config = [];
|
||||
$configList = self::all();
|
||||
foreach ($configList as $k => $v) {
|
||||
$value = $v->toArray();
|
||||
if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
|
||||
$value['value'] = explode(',', $value['value']);
|
||||
}
|
||||
if ($value['type'] == 'array') {
|
||||
$value['value'] = (array)json_decode($value['value'], true);
|
||||
}
|
||||
$config[$value['name']] = $value['value'];
|
||||
}
|
||||
file_put_contents(
|
||||
CONF_PATH . 'extra' . DS . 'site.php',
|
||||
'<?php' . "\n\nreturn " . var_export($config, true) . ";\n"
|
||||
);
|
||||
\app\common\library\CommissionService::syncSiteConfigFile((string)$removedKey);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
在新工单中引用
屏蔽一个用户