feat: 完善协议管理、师傅资质认证、分账配置并完成测试环境全量部署与同步

这个提交包含在:
2026-11-12 17:19:49 +08:00
父节点 fafddceaf2
当前提交 72cea8445f
共有 179 个文件被更改,包括 29242 次插入 和 3340 次删除

查看文件

@@ -2,6 +2,7 @@
namespace app\api\controller;
use app\common\library\TiandituService;
use think\Db;
/**
@@ -63,6 +64,21 @@ class Address extends Base
$this->error('手机号格式不正确');
}
// 未携带有效经纬度时在写入前通过天地图自动补充坐标
if (($data['lng'] === '' || $data['lat'] === '' || abs((float)$data['lng']) < 0.0001 || abs((float)$data['lat']) < 0.0001)
&& $data['address'] !== ''
) {
$fullAddr = trim($data['province'] . $data['city'] . $data['district'] . $data['address']);
$geo = TiandituService::geocoder($fullAddr);
if (!$geo && $data['city'] !== '') {
$geo = TiandituService::geocoder(trim($data['city'] . $data['district'] . $data['address']));
}
if ($geo) {
$data['lng'] = (string)$geo['lng'];
$data['lat'] = (string)$geo['lat'];
}
}
if ($id > 0) {
$exist = Db::name('address')->where('id', $id)->where('user_id', $this->uid())->find();
if (!$exist) {

查看文件

@@ -2,7 +2,6 @@
namespace app\api\controller;
use fast\Random;
use think\Db;
use think\Validate;
@@ -14,9 +13,7 @@ class Auth extends Base
protected $noNeedLogin = ['login', 'wxlogin', 'wxPhoneLogin'];
/**
* 手机号 + 验证码登录(兜底通道)
* 验证码来源由 .env 的 [sms] 段控制:mock=1 时使用 mock_code(联调用),
* 接入真实短信后置 mock=0 并在此处改为 Sms::check($mobile, $code, 'mobilelogin')
* 手机号 + 密码登录(仅支持账号密码或微信一键登录,短信验证码通道已移除)
* @ApiMethod (POST)
*/
public function login()
@@ -26,76 +23,45 @@ class Auth extends Base
$password = (string)$this->request->post('password', '');
$code = trim((string)$this->request->post('code', ''));
// 1. 手机号 + 密码登录(直连真实数据库)
if ($password !== '' || ($mobile !== '' && $code === '')) {
if ($mobile === '') {
$this->error('请填写手机号');
}
if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
$this->error('手机号格式不正确');
}
if ($password === '') {
$this->error('请填写登录密码');
}
// 直接查询真实数据库 fa_user 表
$user = Db::name('user')->where('mobile', $mobile)->find();
if (!$user) {
// 若数据库中无此手机号:直连数据库插入注册新会员
$ret = $this->auth->register($mobile, $password, '', $mobile, []);
if (!$ret) {
$this->error($this->auth->getError() ?: '注册登录失败');
}
} else {
if ($user['status'] !== 'normal') {
$this->error('账号已被禁用');
}
if (empty($user['password'])) {
$this->error('该账号尚未设置登录密码,请使用验证码或微信登录后设置密码');
}
$encryptPassword = $this->auth->getEncryptPassword($password, $user['salt']);
if ($user['password'] !== $encryptPassword) {
$this->error('手机号或密码不正确');
}
$this->auth->direct($user['id']);
}
// 直查真实数据库返回用户完整信息
$this->success('登录成功', [
'token' => $this->auth->getToken(),
'expires' => 2592000,
'userinfo' => $this->profileData(),
]);
if ($password === '' && $code !== '') {
$this->error('短信验证码通道已移除,请使用手机号密码或微信一键登录', null, 2010);
}
// 2. 手机号 + 验证码登录(向下兼容)
if (!$mobile || !$code) {
$this->error('请填写手机号和验证码');
// 手机号 + 密码登录(直连真实数据库)
if ($mobile === '') {
$this->error('请填写手机号');
}
if (!Validate::regex($mobile, "^1\d{10}$")) {
if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
$this->error('手机号格式不正确');
}
$mockOn = (int)\think\Env::get('sms.mock', 1);
$mockCode = (string)\think\Env::get('sms.mock_code', '123456');
if (!($mockOn === 1 && $mockCode !== '' && (string)$code === $mockCode)) {
$this->error('短信通道尚未接入,请联系管理员开通', ['sms_ready' => 0], 2010);
if ($password === '') {
$this->error('请填写登录密码');
}
$user = \app\common\model\User::getByMobile($mobile);
if ($user) {
// 直接查询真实数据库 fa_user 表
$user = Db::name('user')->where('mobile', $mobile)->find();
if (!$user) {
// 若数据库中无此手机号:直连数据库插入注册新会员
$ret = $this->auth->register($mobile, $password, '', $mobile, []);
if (!$ret) {
$this->error($this->auth->getError() ?: '注册登录失败');
}
} else {
if ($user['status'] !== 'normal') {
$this->error('账号已被禁用');
}
$this->auth->direct($user['id']);
} else {
$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
if (!$ret) {
$this->error($this->auth->getError() ?: '注册失败');
if (empty($user['password'])) {
$this->error('该账号尚未设置登录密码,请使用微信一键登录后设置密码');
}
$encryptPassword = $this->auth->getEncryptPassword($password, $user['salt']);
if ($user['password'] !== $encryptPassword) {
$this->error('手机号或密码不正确');
}
$this->auth->direct($user['id']);
}
// 直查真实数据库返回用户完整信息
$this->success('登录成功', [
'token' => $this->auth->getToken(),
'expires' => 2592000,
@@ -357,17 +323,20 @@ class Auth extends Base
$this->error('解析手机号失败');
}
// 2. 如果传了 login_code,换取 openid
// 2. 如果传了 login_code,换取 openid;失败时严禁静默忽略,需如实报错防止后续支付/转账漏绑 OpenID
$openid = '';
$sessionKey = '';
$unionid = '';
if ($loginCode !== '') {
$wx = \app\common\library\WxLogin::jscode2session($loginCode);
if (!isset($wx['error']) && !empty($wx['openid'])) {
$openid = $wx['openid'];
$sessionKey = isset($wx['session_key']) ? $wx['session_key'] : '';
$unionid = isset($wx['unionid']) ? $wx['unionid'] : '';
if (isset($wx['error']) || empty($wx['openid'])) {
$errMsg = isset($wx['error']) && $wx['error'] !== '' ? (string)$wx['error'] : '微信登录凭证换取 OpenID 失败,请重进小程序再试';
\think\Log::error('[Auth::wxPhoneLogin] jscode2session 失败: ' . $errMsg);
$this->error($errMsg, ['wx_errcode' => isset($wx['errcode']) ? (int)$wx['errcode'] : 0]);
}
$openid = $wx['openid'];
$sessionKey = isset($wx['session_key']) ? $wx['session_key'] : '';
$unionid = isset($wx['unionid']) ? $wx['unionid'] : '';
}
// 3. 落库与关联登录

查看文件

@@ -276,9 +276,9 @@ class Base extends Api
}
}
// 师傅脱敏称呼与评分
$masterName = '优匠师傅';
$masterScore = 5.00;
// 师傅脱敏称呼与真实评分
$masterName = '';
$masterScore = 0.00;
if ((int)$order['master_id'] > 0) {
$m = Db::name('master')->where('id', (int)$order['master_id'])->find();
if ($m) {
@@ -288,13 +288,13 @@ class Base extends Api
} elseif ($rName !== '') {
$masterName = $rName;
}
$masterScore = (float)$m['score'] > 0 ? round((float)$m['score'], 2) : 5.00;
$masterScore = round((float)$m['score'], 2);
}
}
$score = $rev ? max(1, min(5, (int)$rev['score'])) : 5;
$tags = ($rev && !empty($rev['tags'])) ? (string)$rev['tags'] : '准时,专业,值得推荐';
$content = ($rev && !empty($rev['content'])) ? (string)$rev['content'] : '师傅准时上门,施工专业细致,安装效果很满意!';
$score = $rev ? max(1, min(5, (int)$rev['score'])) : 0;
$tags = ($rev && !empty($rev['tags'])) ? (string)$rev['tags'] : '';
$content = ($rev && !empty($rev['content'])) ? (string)$rev['content'] : '';
$payload = [
'order_id' => $orderId,
@@ -302,9 +302,9 @@ class Base extends Api
'user_name' => $userName,
'user_avatar' => $userAvatar,
'cat_id' => (int)$order['cat_id'],
'cat_name' => $cat ? (string)$cat['name'] : '上门服务',
'cat_name' => $cat ? (string)$cat['name'] : '',
'service_id' => (int)$order['service_id'],
'service_name' => $order['service_name'] ?: ($service ? (string)$service['name'] : '上门服务'),
'service_name' => $order['service_name'] ?: ($service ? (string)$service['name'] : ''),
'region' => $region,
'cover_image' => $cover,
'images' => !empty($imgList) ? json_encode(array_values($imgList), JSON_UNESCAPED_UNICODE) : '',

查看文件

@@ -10,6 +10,7 @@ use app\common\model\Version;
use fast\Random;
use think\captcha\Captcha;
use think\Config;
use think\Db;
use think\Hook;
/**
@@ -17,7 +18,7 @@ use think\Hook;
*/
class Common extends Api
{
protected $noNeedLogin = ['init', 'captcha'];
protected $noNeedLogin = ['init', 'captcha', 'areas', 'expressCompanies', 'dicts'];
protected $noNeedRight = '*';
public function _initialize()
@@ -146,4 +147,166 @@ class Common extends Api
$captcha = new Captcha((array)Config::get('captcha'));
return $captcha->entry($id);
}
/**
* 行政区划真实数据库查询接口(源自 fa_area)
* - mode=tree: 返回完整省-市-区三级联树
* - pid: 按父级ID逐级查询下级行政区
*/
public function areas()
{
$mode = trim((string)$this->request->param('mode', ''));
if ($mode === 'tree') {
$rows = Db::name('area')
->field('id,pid,name,shortname,level')
->where('level', 'in', [1, 2, 3])
->order('id asc')
->select();
if (empty($rows)) {
$this->error('行政区划基础数据尚未初始化');
}
$provinces = [];
$citiesByPid = [];
$districtsByPid = [];
foreach ($rows as $row) {
$lvl = (int)$row['level'];
$pid = (int)$row['pid'];
$id = (int)$row['id'];
if ($lvl === 1) {
$provinces[] = [
'id' => $id,
'name' => (string)$row['name'],
'cities' => [],
];
} elseif ($lvl === 2) {
if (!isset($citiesByPid[$pid])) {
$citiesByPid[$pid] = [];
}
$citiesByPid[$pid][] = [
'id' => $id,
'name' => (string)$row['name'],
'districts' => [],
];
} elseif ($lvl === 3) {
if (!isset($districtsByPid[$pid])) {
$districtsByPid[$pid] = [];
}
$districtsByPid[$pid][] = (string)$row['name'];
}
}
foreach ($provinces as &$prov) {
$cities = isset($citiesByPid[$prov['id']]) ? $citiesByPid[$prov['id']] : [];
foreach ($cities as &$city) {
$city['districts'] = isset($districtsByPid[$city['id']]) ? $districtsByPid[$city['id']] : [];
}
unset($city);
$prov['cities'] = $cities;
}
unset($prov);
$this->success('', ['tree' => $provinces]);
}
$pid = (int)$this->request->param('pid', 0);
$list = Db::name('area')
->field('id,pid,name,shortname,mergename,level')
->where('pid', $pid)
->order('id asc')
->select();
$this->success('', ['list' => $list]);
}
/**
* 物流公司真实字典(源自 fa_express_company,按首字母分组)
*/
public function expressCompanies()
{
$rows = Db::name('express_company')
->field('id,code,name,initial')
->where('status', 'normal')
->order('initial asc, weigh desc, id asc')
->select();
$groupMap = [];
foreach ($rows as $r) {
$letter = strtoupper(trim((string)$r['initial'])) ?: 'Q';
if (!isset($groupMap[$letter])) {
$groupMap[$letter] = [];
}
$groupMap[$letter][] = (string)$r['name'];
}
$groups = [];
foreach ($groupMap as $letter => $items) {
$groups[] = [
'letter' => $letter,
'items' => $items,
];
}
// 将“Q 其它”组调整到末尾
usort($groups, function ($a, $b) {
$isQa = ($a['letter'] === 'Q');
$isQb = ($b['letter'] === 'Q');
if ($isQa !== $isQb) {
return $isQa ? 1 : -1;
}
return strcmp($a['letter'], $b['letter']);
});
$this->success('', [
'groups' => $groups,
'list' => $rows,
]);
}
/**
* 平台通用业务字典接口(真实表与系统配置驱动)
*/
public function dicts()
{
$parseCsv = static function ($name) {
$val = Db::name('config')->where('name', $name)->value('value');
if ($val === null || trim((string)$val) === '') {
$val = Config::get('site.' . $name);
}
if (!$val) {
return [];
}
return array_values(array_filter(array_map('trim', explode(',', (string)$val))));
};
$reviewTags = $parseCsv('review_tags');
$orderSources = $parseCsv('order_source_options');
$rawQuoteHours = $parseCsv('auto_quote_hours_options');
$autoQuoteHours = [];
foreach ($rawQuoteHours as $h) {
$hi = (int)$h;
if ($hi > 0) {
$autoQuoteHours[] = $hi;
}
}
// 师傅资质要求列表直接读取真实证书字典表 fa_cert_dict
$certRows = Db::name('cert_dict')
->field('id,cert_code,cert_name,sample_type')
->where('status', 'normal')
->where('cert_code', '<>', 'other')
->order('weigh desc, id asc')
->select();
$qualReqs = [];
foreach ($certRows as $cr) {
if (!empty($cr['cert_name'])) {
$qualReqs[] = (string)$cr['cert_name'];
}
}
$this->success('', [
'review_tags' => $reviewTags,
'order_sources' => $orderSources,
'auto_quote_hours' => $autoQuoteHours,
'qual_reqs' => $qualReqs,
'cert_dict' => $certRows,
]);
}
}

查看文件

@@ -9,7 +9,7 @@ use think\Db;
*/
class Home extends Base
{
protected $noNeedLogin = ['index', 'feed', 'cats', 'services', 'detail', 'calc', 'specs', 'masterCount', 'orderCase', 'agreement', 'systemGallery'];
protected $noNeedLogin = ['index', 'feed', 'cats', 'services', 'detail', 'calc', 'specs', 'masterCount', 'orderCase', 'agreement', 'agreementRead', 'systemGallery'];
/**
* 首页聚合:类目 + 热门服务 + 我的角标
@@ -151,15 +151,69 @@ class Home extends Base
];
}
// 聚合在售服务的真实计价单位列表(彻底由数据库驱动,按商品数量降序)
$unitRows = Db::name('service')
->field('unit, COUNT(*) AS cnt, MIN(id) AS min_id')
->where('status', 'normal')
->where('cat_id', '<>', 15)
->where('unit', '<>', '')
->group('unit')
->order('cnt desc, min_id asc')
->select();
$filterUnits = [];
foreach ($unitRows as $ur) {
$uName = trim((string)($ur['unit'] ?? ''));
if ($uName !== '') {
$filterUnits[] = [
'label' => '按' . $uName . '计价',
'value' => $uName,
];
}
}
// 从 fa_config 读取价格筛选项 JSON 与晒单评价标签配置
$priceRangesRaw = Db::name('config')->where('name', 'home_price_ranges')->value('value');
if ($priceRangesRaw === null || trim((string)$priceRangesRaw) === '') {
$priceRangesRaw = \think\Config::get('site.home_price_ranges');
}
$filterPriceRanges = [];
if (is_string($priceRangesRaw) && trim($priceRangesRaw) !== '') {
$decodedPr = json_decode(htmlspecialchars_decode(trim($priceRangesRaw)), true);
if (is_array($decodedPr)) {
foreach ($decodedPr as $prItem) {
if (is_array($prItem) && !empty($prItem['label']) && !empty($prItem['value'])) {
$filterPriceRanges[] = [
'label' => (string)$prItem['label'],
'value' => (string)$prItem['value'],
];
}
}
}
}
$tagCfg = $this->configList('review_tags');
$filterCaseTags = [];
foreach ($tagCfg as $tc) {
$filterCaseTags[] = [
'label' => $tc,
'value' => $tc,
];
}
$data = [
'cats' => $cats,
'cat_services' => $catServices,
'showcase_services' => $showcaseServices,
'service_types_dict' => $serviceTypesDict,
'regions' => $regions,
'filter_options' => [
'units' => $filterUnits,
'price_ranges' => $filterPriceRanges,
'case_tags' => $filterCaseTags,
],
'hot' => $this->formatServices($hotList),
'banners' => $this->banners(),
'assures' => $this->configList('home_assure', '平台认证,先行赔付,极速上门,售后无忧'),
'assures' => $this->configList('home_assure'),
'tutorial' => $this->tutorial(),
'service_phone' => (string)(\think\Config::get('site.service_phone') ?: ''),
'badge' => ['coupon' => 0, 'unread' => 0],
@@ -190,16 +244,16 @@ class Home extends Base
$recentOrders[] = [
'id' => (int)$sc['id'],
'service_id' => (int)$sc['service_id'],
'service_name' => $sc['service_name'] ?: '上门服务',
'cat_name' => $sc['cat_name'] ?: '服务',
'service_name' => (string)$sc['service_name'],
'cat_name' => (string)$sc['cat_name'],
'cat_id' => (int)$sc['cat_id'],
'image_url' => $sc['cover_image'] ? cdnurl($sc['cover_image'], true) : '',
'status_text' => '业主晒单',
'location' => $sc['region'] ?: '同城服务',
'location' => (string)$sc['region'],
'time_ago' => $this->timeAgo((int)$sc['createtime']),
'user_name' => $sc['user_name'] ?: '匿名业主',
'review_score' => (int)$sc['score'] ?: 5,
'review_content' => $sc['content'] ?: '师傅准时上门,施工专业细致,安装效果很满意!',
'user_name' => (string)$sc['user_name'],
'review_score' => (int)$sc['score'],
'review_content' => (string)$sc['content'],
'review_tags' => array_slice($revTags, 0, 2),
];
}
@@ -299,16 +353,16 @@ class Home extends Base
$list[] = [
'id' => (int)$sc['id'],
'service_id' => (int)$sc['service_id'],
'service_name' => $sc['service_name'] ?: '上门服务',
'cat_name' => $sc['cat_name'] ?: '服务',
'service_name' => (string)$sc['service_name'],
'cat_name' => (string)$sc['cat_name'],
'cat_id' => (int)$sc['cat_id'],
'image_url' => $sc['cover_image'] ? cdnurl($sc['cover_image'], true) : '',
'status_text' => '业主晒单',
'location' => $sc['region'] ?: '同城服务',
'location' => (string)$sc['region'],
'time_ago' => $this->timeAgo((int)$sc['createtime']),
'user_name' => $sc['user_name'] ?: '匿名业主',
'review_score' => (int)$sc['score'] ?: 5,
'review_content' => $sc['content'] ?: '师傅准时上门,施工专业细致,安装效果很满意!',
'user_name' => (string)$sc['user_name'],
'review_score' => (int)$sc['score'],
'review_content' => (string)$sc['content'],
'review_tags' => array_slice($revTags, 0, 3),
];
}
@@ -970,8 +1024,8 @@ class Home extends Base
'discount_amount' => round($discount, 2),
'pay_amount' => max(0, round($total - $discount, 2)),
'coupon' => $couponInfo,
'free_floor' => $type === 'custom' ? 0 : ($service ? (int)$service['free_floor'] : 2),
'floor_fee' => $type === 'custom' ? 0 : round($service ? (float)$service['floor_fee'] : 10.0, 2),
'free_floor' => $type === 'custom' ? 0 : ($service ? (int)$service['free_floor'] : 0),
'floor_fee' => $type === 'custom' ? 0 : round($service ? (float)$service['floor_fee'] : 0.0, 2),
];
}
@@ -1048,13 +1102,16 @@ class Home extends Base
}
/**
* 读取 fa_config 中的逗号分隔列表
* 读取 fa_config 中的逗号分隔列表(完全由真实库配置与站点配置驱动)
*/
protected function configList($name, $default = '')
protected function configList($name)
{
$v = Db::name('config')->where('name', $name)->value('value');
if ($v === null || trim((string)$v) === '') {
$v = \think\Config::get('site.' . $name);
}
if (!$v) {
$v = $default;
return [];
}
return array_values(array_filter(array_map('trim', explode(',', (string)$v))));
}
@@ -1065,8 +1122,11 @@ class Home extends Base
protected function tutorial()
{
$v = Db::name('config')->where('name', 'home_tutorial')->value('value');
if ($v === null || trim((string)$v) === '') {
$v = \think\Config::get('site.home_tutorial');
}
if (!$v) {
return ['title' => '下单找师傅教程', 'sub' => '3 分钟看懂,下单不踩坑'];
return ['title' => '', 'sub' => ''];
}
$parts = explode('|', (string)$v);
return [
@@ -1274,7 +1334,7 @@ class Home extends Base
}
$service = Db::name('service')->where('id', (int)$sc['service_id'])->find();
$basePrice = ($service && (float)$service['base_price'] > 0) ? (float)$service['base_price'] : 50.00;
$basePrice = $service ? (float)$service['base_price'] : 0.00;
$imageUrl = $sc['cover_image'] ? cdnurl($sc['cover_image'], true) : '';
$tags = [];
@@ -1303,9 +1363,9 @@ class Home extends Base
}
}
$dateText = !empty($sc['createtime']) ? date('Y-m-d', (int)$sc['createtime']) : date('Y-m-d');
$catName = $sc['cat_name'] ?: '上门服务';
$serviceName = $sc['service_name'] ?: '上门服务';
$dateText = !empty($sc['createtime']) ? date('Y-m-d', (int)$sc['createtime']) : '';
$catName = (string)$sc['cat_name'];
$serviceName = (string)$sc['service_name'];
$this->success('', [
'order' => [
@@ -1316,21 +1376,21 @@ class Home extends Base
'cat_name' => $catName,
'image_url' => $imageUrl,
'status_text' => '业主晒单',
'location' => $sc['region'] ?: '同城服务',
'location' => (string)$sc['region'],
'finish_text' => $dateText,
'media' => $mediaList,
],
'master' => [
'realname' => $sc['master_name'] ?: '优匠师傅',
'score' => (float)($sc['master_score'] > 0 ? $sc['master_score'] : 5.0),
'realname' => (string)$sc['master_name'],
'score' => (float)$sc['master_score'],
],
'review' => [
'id' => (int)$sc['id'],
'score' => (int)$sc['score'] ?: 5,
'score' => (int)$sc['score'],
'tags' => $tags,
'content' => $sc['content'] ?: '师傅很专业,准时上门,施工规范细致,验收很满意!',
'content' => (string)$sc['content'],
'images' => $rImgs,
'user_name' => $sc['user_name'] ?: '匿名业主',
'user_name' => (string)$sc['user_name'],
'user_avatar' => $sc['user_avatar'] ? cdnurl($sc['user_avatar'], true) : '',
'time_text' => $dateText,
],
@@ -1346,52 +1406,35 @@ class Home extends Base
}
/**
* 平台协议与合规条款读取(支持后台站点配置覆盖)
* 平台协议与合规条款读取(优先读取后台「协议与隐私」实时配置,结合用户已读修订号返回首看变更标识)
*/
public function agreement()
{
$type = trim((string)$this->request->param('type', 'user_service'));
$map = [
'service' => [
'key' => 'agreement_service',
'title' => '优匠优服用户服务协议',
'content' => "1. 平台定位:优匠优服为客户与认证技能师傅提供上门安装、维修、拆旧及维保信息撮合与交易担保服务。\n\n2. 计费准则:一口价项目按公示标准计费;报价订单由师傅根据现场工况公开报价,经客户确认支付后生效。\n\n3. 验收与结算:订单资金由平台托管,师傅完工拍照并经客户确认(或提供6位核销码)后完成结算。\n\n4. 交易规范:为保障售后质保与资金安全,请勿脱离平台私下转账交易。",
],
'user_service' => [
'key' => 'agreement_service',
'title' => '优匠优服用户服务协议',
'content' => "1. 平台定位:优匠优服为客户与认证技能师傅提供上门安装、维修、拆旧及维保信息撮合与交易担保服务。\n\n2. 计费准则:一口价项目按公示标准计费;报价订单由师傅根据现场工况公开报价,经客户确认支付后生效。\n\n3. 验收与结算:订单资金由平台托管,师傅完工拍照并经客户确认(或提供6位核销码)后完成结算。\n\n4. 交易规范:为保障售后质保与资金安全,请勿脱离平台私下转账交易。",
],
'privacy' => [
'key' => 'agreement_privacy',
'title' => '优匠优服隐私保护指引',
'content' => "1. 信息收集范围:仅在您授权登录、预约上门地址及联系师傅等必要场景下收集手机号码与服务地址信息。\n\n2. 最小必要原则:客户真实联系信息仅对已接单履约的当单认证师傅可见,未接单前全程脱敏展示。\n\n3. 数据传输安全:全链路采用加密通信并严格管控访问权限,绝不向无关第三方共享或出售个人信息。\n\n4. 用户权利:您可随时在个人中心查询、修改账户资料及管理服务地址。",
],
'master' => [
'key' => 'agreement_master',
'title' => '师傅入驻与履约服务协议',
'content' => "1. 实名与技能核验:入驻师傅须提交本人真实有效身份证件及服务技能信息,严禁冒用他人资质。\n\n2. 履约时效:接单后须在平台规定时效内联系客户确认上门时间,准时到达现场并规范施工。\n\n3. 收费透明:如需现场增项补差,必须提前向客户说明并在工单内发起补差申请,严禁私自索要额外费用。\n\n4. 完工留痕与结算:施工完成后须上传真实清晰的现场完工照片,凭客户验收或核销码触发系统结算。",
],
'merchant' => [
'key' => 'agreement_merchant',
'title' => '企业商家入驻与协同服务协议',
'content' => "1. 资质真实性:申请入驻的企业或商户须提供真实有效的营业执照与主体信息。\n\n2. 成员协同管理:主账号可绑定企业协同成员共同发起批量工单与跟进履约,并对企业关联工单承担管理责任。\n\n3. 对账与开票:平台按实际支付与完工订单汇总企业月度账单,支持在线申请正规增值税普通发票或专用发票。",
],
];
$item = \app\common\library\AgreementService::getByType($type, $this->uid());
if (!$item) {
$this->error('协议内容暂未配置或已下线');
}
$item = isset($map[$type]) ? $map[$type] : $map['user_service'];
$cfgVal = \think\Config::get('site.' . $item['key']);
$content = (is_string($cfgVal) && trim($cfgVal) !== '') ? trim($cfgVal) : $item['content'];
$this->success('', [
'type' => $type,
'title' => $item['title'],
'content' => $content,
]);
$this->success('', $item);
}
/**
* 官方系统图库(二级商品分类侧边栏 + 款式参考图片双列网格)
* 记录用户已首次查看指定修订版本的协议(后续打开不再标背景色)
*/
public function agreementRead()
{
if (false === $this->request->isPost()) {
$this->error('请求方式错误');
}
$type = trim((string)$this->request->post('type', 'privacy'));
$revision = (int)$this->request->post('revision', 0);
$res = \app\common\library\AgreementService::markUserRead($this->uid(), $type, $revision);
$this->success('', $res);
}
/**
* 官方系统图库(受下单所选类目控制,仅展示对应类目下的商品及参考图片;同源聚合系统图库表 + 细分规格图 + 商品主缩略图)
*/
public function systemGallery()
{
@@ -1417,6 +1460,14 @@ class Home extends Base
$catId = (int)$cats[0]['id'];
}
$currentCatName = '';
foreach ($cats as $c) {
if ((int)$c['id'] === $catId) {
$currentCatName = (string)$c['name'];
break;
}
}
$svcQuery = Db::name('service')
->field('id,cat_id,name,image')
->where('status', 'normal')
@@ -1428,6 +1479,7 @@ class Home extends Base
$svcIds = array_column($svcRows, 'id');
$galleryMap = [];
$specMap = [];
if (!empty($svcIds)) {
$gQuery = Db::name('system_gallery')
->where('service_id', 'in', $svcIds)
@@ -1450,34 +1502,96 @@ class Home extends Base
'image_url' => strpos($rawImg, 'http') === 0 ? $rawImg : cdnurl($rawImg, true),
];
}
// 一次性批量查询所有关联商品的细分规格配图(严禁循环内查库)
$spRows = Db::name('service_spec')
->field('id,service_id,name,image')
->where('service_id', 'in', $svcIds)
->where('status', 'normal')
->order('weigh desc,id asc')
->select();
foreach ($spRows as $sp) {
$sid = (int)$sp['service_id'];
$specMap[$sid][] = $sp;
}
}
// 若个别服务尚未写入 fa_system_gallery,回退读取真实规格与服务主图
// 智能同源聚合:1. 系统图库表记录 -> 2. 细分规格独立配图 -> 3. 商品后台主缩略图兜底(单张不重复)
$services = [];
foreach ($svcRows as $sr) {
$sid = (int)$sr['id'];
$items = isset($galleryMap[$sid]) ? $galleryMap[$sid] : [];
$items = [];
$seenImgUrls = [];
$seenBasenames = [];
static $isValidGalleryUrl = null;
if ($isValidGalleryUrl === null) {
$isValidGalleryUrl = static function (string $url): bool {
$base = strstr($url, '?', true);
$clean = strtolower(trim($base !== false ? $base : $url));
if ($clean === '' || substr($clean, -4) === '.svg' || strpos($clean, '/icon/') !== false) {
return false;
}
return true;
};
}
$registerUniqueUrl = static function (string $url) use (&$seenImgUrls, &$seenBasenames, $isValidGalleryUrl): ?string {
$u = trim($url);
if ($u === '' || !$isValidGalleryUrl($u)) {
return null;
}
$pathOnly = parse_url($u, PHP_URL_PATH);
$fname = $pathOnly ? strtolower(basename($pathOnly)) : strtolower($u);
if (isset($seenImgUrls[$u]) || ($fname !== '' && isset($seenBasenames[$fname]))) {
return null;
}
$seenImgUrls[$u] = true;
if ($fname !== '') {
$seenBasenames[$fname] = true;
}
return $u;
};
if (!empty($galleryMap[$sid])) {
foreach ($galleryMap[$sid] as $gItem) {
$u = $registerUniqueUrl((string)($gItem['image_url'] ?? ''));
if ($u === null) {
continue;
}
$gItem['image_url'] = $u;
$items[] = $gItem;
}
}
// 仅当系统图库未单独配置该商品图集时,回退读取商品细分规格参考图
if (empty($items) && !empty($specMap[$sid])) {
foreach ($specMap[$sid] as $sp) {
$spImg = !empty($sp['image']) ? trim((string)$sp['image']) : '';
if ($spImg === '' || !$isValidGalleryUrl($spImg)) {
continue;
}
if ($keyword !== '' && mb_strpos((string)$sp['name'], $keyword) === false) {
continue;
}
$fullSpUrl = strpos($spImg, 'http') === 0 ? $spImg : cdnurl($spImg, true);
$u = $registerUniqueUrl($fullSpUrl);
if ($u !== null) {
$items[] = [
'id' => 100000 + (int)$sp['id'],
'service_id' => $sid,
'spec_id' => (int)$sp['id'],
'title' => (string)$sp['name'],
'image_url' => $u,
];
}
}
}
// 若后台仅在添加商品时上传了1张商品缩略图(未配额外图库与规格图),直接展示该商品主图
if (empty($items) && $keyword === '') {
$defaultImg = trim((string)$sr['image']);
if ($defaultImg !== '') {
if ($defaultImg !== '' && $isValidGalleryUrl($defaultImg)) {
$fullDef = strpos($defaultImg, 'http') === 0 ? $defaultImg : cdnurl($defaultImg, true);
$spList = Db::name('service_spec')
->where('service_id', $sid)
->where('status', 'normal')
->order('weigh desc,id asc')
->select();
if (!empty($spList)) {
foreach ($spList as $sp) {
$spImg = !empty($sp['image']) ? trim((string)$sp['image']) : '';
$items[] = [
'id' => 100000 + (int)$sp['id'],
'service_id' => $sid,
'spec_id' => (int)$sp['id'],
'title' => (string)$sp['name'],
'image_url' => $spImg !== '' ? (strpos($spImg, 'http') === 0 ? $spImg : cdnurl($spImg, true)) : $fullDef,
];
}
} else {
if ($isValidGalleryUrl($fullDef)) {
$items[] = [
'id' => 200000 + $sid,
'service_id' => $sid,
@@ -1488,6 +1602,7 @@ class Home extends Base
}
}
}
if ($keyword !== '' && empty($items) && mb_strpos((string)$sr['name'], $keyword) === false) {
continue;
}
@@ -1503,9 +1618,10 @@ class Home extends Base
}
$this->success('', [
'cats' => $cats,
'current_cat_id' => $catId,
'services' => $services,
'cats' => $cats,
'current_cat_id' => $catId,
'current_cat_name' => $currentCatName,
'services' => $services,
]);
}
}

文件差异内容过多而无法显示 加载差异

查看文件

@@ -2,6 +2,8 @@
namespace app\api\controller;
use app\common\library\CommissionService;
use app\common\library\FinanceConfigService;
use app\common\library\InvoiceService;
use app\common\library\OrderStatus;
use think\Db;
@@ -645,6 +647,12 @@ class Merchant extends Base
$this->error("第 {$rowNo} 条订单计算金额异常");
}
$resolvedProvince = mb_substr(trim((string)(isset($item['province']) && $item['province'] !== '' ? $item['province'] : ($merchant['province'] ?: ''))), 0, 50);
$resolvedCity = mb_substr(trim((string)(isset($item['city']) && $item['city'] !== '' ? $item['city'] : ($merchant['city'] ?: ''))), 0, 50);
if ($resolvedProvince === '' || $resolvedCity === '') {
$this->error("第 {$rowNo} 条订单缺少服务省份或城市信息,请在Excel或表格中填写后再提交");
}
$preparedRows[] = [
'svc' => $svc,
'service_id' => (int)$svc['id'],
@@ -655,8 +663,8 @@ class Merchant extends Base
'goods_num' => $goodsNum,
'contact' => mb_substr($contact ?: '买家', 0, 50),
'mobile' => $mobile,
'province' => mb_substr(trim((string)(isset($item['province']) && $item['province'] !== '' ? $item['province'] : ($merchant['province'] ?: '贵州省'))), 0, 50),
'city' => mb_substr(trim((string)(isset($item['city']) && $item['city'] !== '' ? $item['city'] : ($merchant['city'] ?: '贵阳市'))), 0, 50),
'province' => $resolvedProvince,
'city' => $resolvedCity,
'district' => mb_substr(trim((string)(isset($item['district']) ? $item['district'] : ($merchant['district'] ?: ''))), 0, 50),
'address' => mb_substr($address, 0, 255),
'floor' => $floor,
@@ -678,6 +686,9 @@ class Merchant extends Base
$isMonthly = false;
$batchNo = 'MB' . date('YmdHis') . mt_rand(1000, 9999);
$now = time();
// 事务外一次性预加载生效抽佣规则与默认兜底配置,循环内纯内存匹配快照(零额外 SQL)
$activeCommRules = CommissionService::getActiveRules();
$commDefaults = FinanceConfigService::getCommissionDefaults();
Db::startTrans();
try {
@@ -697,6 +708,13 @@ class Merchant extends Base
$calc = $pRow['calc'];
$payAmt = round((float)$calc['pay_amount'], 2);
$unitPrice = round((float)$calc['base_amount'] / max(1, (int)$pRow['goods_num']), 2);
$commMatch = CommissionService::matchOrderSnapshot([
'price_type' => 'fixed',
'customer_type' => 'merchant',
'cat_id' => (int)$pRow['cat_id'],
'urgent' => (int)$pRow['urgent'],
'order_amount' => $payAmt,
], $activeCommRules, $commDefaults);
$orderId = (int)Db::name('order')->insertGetId([
'order_no' => $orderNo,
@@ -724,9 +742,11 @@ class Merchant extends Base
'floor_amount' => $calc['floor_amount'],
'urgent_amount' => $calc['urgent_amount'],
'discount_amount' => 0.00,
'total_amount' => $calc['total_amount'],
'pay_amount' => $payAmt,
'status' => $initStatus,
'total_amount' => $calc['total_amount'],
'pay_amount' => $payAmt,
'commission_rate' => $commMatch['commission_rate'],
'commission_snapshot' => $commMatch['commission_snapshot'],
'status' => $initStatus,
'pay_status' => $initPayStatus,
'pay_type' => $initPayType,
'pay_time' => $initPayTime,
@@ -825,124 +845,13 @@ class Merchant extends Base
}
/**
* 商户端:预付商家按批次号支付待支付批量订单
* 商户端:预付商家按批次号支付待支付批量订单(严禁模拟免付兜底,预付订单须逐笔走真实微信支付)
* @ApiMethod (POST)
*/
public function payBatch()
{
$merchant = $this->requireMerchant();
$batchNo = trim((string)$this->request->post('batch_no', ''));
$payType = trim((string)$this->request->post('pay_type', 'wechat'));
if ($payType === '') {
$payType = 'mock';
}
if ($batchNo === '') {
$this->error('缺少批次号 batch_no');
}
$batchLinks = Db::name('merchant_order')->where('batch_no', $batchNo)->select();
if (empty($batchLinks)) {
$this->error('批次订单不存在');
}
$batchOrderIds = [];
foreach ($batchLinks as $link) {
if ((int)$link['merchant_id'] !== (int)$merchant['id']) {
$this->error('无权操作该批次订单', null, 403);
}
$oid = (int)$link['order_id'];
if ($oid > 0) {
$batchOrderIds[] = $oid;
}
}
$batchOrderIds = array_values(array_unique($batchOrderIds));
if (empty($batchOrderIds)) {
$this->error('该批次下无有效订单');
}
$paidCount = 0;
$paidTotal = 0.00;
$paidOrderIds = [];
$now = time();
Db::startTrans();
try {
$lockedMerchant = Db::name('merchant')->where('id', (int)$merchant['id'])->lock(true)->find();
$orders = Db::name('order')
->where('id', 'in', $batchOrderIds)
->lock(true)
->select();
foreach ($orders as $ord) {
if ((int)$ord['pay_status'] === 1 || (int)$ord['status'] !== OrderStatus::PENDING_PAY) {
continue;
}
$oid = (int)$ord['id'];
$amt = round((float)$ord['pay_amount'], 2);
$txId = 'BATCH' . date('YmdHis', $now) . mt_rand(1000, 9999);
Db::name('order')->where('id', $oid)->update([
'status' => OrderStatus::PENDING_ACCEPT,
'pay_status' => 1,
'pay_type' => $payType,
'pay_time' => $now,
'transaction_id' => $txId,
'updatetime' => $now,
]);
$this->addLog($oid, OrderStatus::PENDING_ACCEPT, "企业批次支付完成(批次 {$batchNo}),订单已进入接单大厅", 'user', $this->uid());
$paidCount++;
$paidTotal = round($paidTotal + $amt, 2);
$paidOrderIds[] = $oid;
}
if ($paidCount === 0) {
throw new \InvalidArgumentException('该批次没有待支付的订单,请勿重复支付');
}
if ($lockedMerchant) {
Db::name('merchant')->where('id', (int)$lockedMerchant['id'])->update([
'order_count' => (int)$lockedMerchant['order_count'] + $paidCount,
'total_amount' => round((float)$lockedMerchant['total_amount'] + $paidTotal, 2),
'updatetime' => $now,
]);
}
Db::commit();
} catch (\think\exception\HttpResponseException $e) {
Db::rollback();
throw $e;
} catch (\InvalidArgumentException $e) {
Db::rollback();
$this->error($e->getMessage());
return;
} catch (\Exception $e) {
Db::rollback();
\think\Log::error('[Merchant::payBatch] ' . $e->getMessage());
$this->error('批次支付失败:' . $e->getMessage());
return;
}
try {
$masters = Db::name('master')
->where('verify_status', 'pass')
->where('work_status', 'on')
->where('user_id', '<>', $this->uid())
->limit(20)
->select();
foreach ($masters as $m) {
$this->notify('master', (int)$m['id'], '企业批量新工单就绪', "同城有 {$paidCount} 笔企业批量工单进入接单大厅,请尽快前往查看抢单!", 'order', (int)$paidOrderIds[0]);
}
} catch (\Exception $e) {
\think\Log::error('[Merchant::payBatch broadcast] ' . $e->getMessage());
}
$this->success('批次支付成功,订单已进入接单大厅', [
'batch_no' => $batchNo,
'count' => $paidCount,
'paid_count' => $paidCount,
'total_amount' => round($paidTotal, 2),
'order_ids' => $paidOrderIds,
]);
$this->requireMerchant();
$this->error('系统已全面禁用模拟支付通道,企业预付工单请逐笔使用真实微信支付完成付款(月结授信企业导单时已直接授信进入大厅)');
}
protected function merchantInfo()

查看文件

@@ -2,7 +2,11 @@
namespace app\api\controller;
use app\common\library\CommissionService;
use app\common\library\FinanceConfigService;
use app\common\library\OrderStatus;
use app\common\library\PaymentService;
use app\common\library\TiandituService;
use think\Db;
/**
@@ -21,7 +25,7 @@ class Order extends Base
}
/**
* 物流单号智能识别物流公司(支持线上快递100识别 + 本地单号特征规则库双保险)
* 物流单号识别物流公司(依据 fa_express_company 精准前缀规则 + 快递100接口;不唯一识别时不瞎猜)
*/
public function detectExpress()
{
@@ -31,68 +35,32 @@ class Order extends Base
$this->error('请输入正确的物流单号');
}
$codeMap = [
'shunfeng' => '顺丰速运',
'debangwuliu' => '德邦快递',
'debangkuaidi' => '德邦快递',
'jd' => '京东快递',
'kuayue' => '跨越速运',
'shentong' => '申通快递',
'yuantong' => '圆通速递',
'zhongtong' => '中通快递',
'yunda' => '韵达',
'huitongkuaidi' => '百世快递',
'baishiwuliu' => '百世快递',
'tiantian' => '天天快递',
'ems' => '邮政特快专递',
'youzhengguonei' => '中国邮政',
'youzhengbk' => '中国邮政',
'zhaijisong' => '宅急送',
'jtexpress' => '极兔速递',
'annengwuliu' => '安能物流',
];
$expressRows = Db::name('express_company')
->field('code,name,prefix_regex')
->where('code', '<>', 'other')
->order('weigh desc, id asc')
->select();
$codeMap = [];
$companyName = '';
// 1. 优先匹配高确定性的标准物流单号前缀规则
if (strpos($no, 'SF') === 0) {
$companyName = '顺丰速运';
} elseif (strpos($no, 'DP') === 0 || strpos($no, 'DB') === 0) {
$companyName = '德邦快递';
} elseif (strpos($no, 'JD') === 0 || strpos($no, 'KK') === 0) {
$companyName = '京东快递';
} elseif (strpos($no, 'KY') === 0) {
$companyName = '跨越速运';
} elseif (strpos($no, 'YT') === 0) {
$companyName = '圆通速递';
} elseif (strpos($no, 'ST') === 0 || strpos($no, '77') === 0) {
$companyName = '申通快递';
} elseif (strpos($no, 'ZT') === 0 || preg_match('/^(73|75|76|78)\d{10,12}$/', $no)) {
$companyName = '中通快递';
} elseif (strpos($no, 'YD') === 0 || preg_match('/^(31|43|46)\d{11,13}$/', $no)) {
$companyName = '韵达';
} elseif (strpos($no, 'BS') === 0 || strpos($no, 'HT') === 0 || preg_match('/^55\d{11,13}$/', $no)) {
$companyName = '百世快递';
} elseif (strpos($no, 'TT') === 0 || preg_match('/^66\d{10,12}$/', $no)) {
$companyName = '天天快递';
} elseif (preg_match('/^(EMS|EA|EB|EC|ED|EE|EF|10|11)\d{7,11}/', $no)) {
$companyName = '邮政特快专递';
} elseif (preg_match('/^(98|99|YZ)\d{9,13}$/', $no)) {
$companyName = '中国邮政';
} elseif (strpos($no, 'ZJS') === 0) {
$companyName = '宅急送';
} elseif (strpos($no, 'JT') === 0) {
$companyName = '极兔速递';
} elseif (strpos($no, 'ANE') === 0) {
$companyName = '安能物流';
foreach ($expressRows as $er) {
$eCode = strtolower(trim((string)($er['code'] ?? '')));
$eName = trim((string)($er['name'] ?? ''));
$regex = trim((string)($er['prefix_regex'] ?? ''));
if ($eCode !== '' && $eName !== '') {
$codeMap[$eCode] = $eName;
}
if ($companyName === '' && $regex !== '' && @preg_match($regex, $no) === 1) {
$companyName = $eName;
}
}
// 2. 若前缀未命中,尝试快递100智能单号识别接口(1.5秒超时保护)
// 若本地高确定性特征规则未唯一命中,尝试快递100智能单号识别接口(开启严格 TLS 校验与超时保护)
if ($companyName === '') {
try {
$ctx = stream_context_create([
'http' => ['timeout' => 1.5, 'ignore_errors' => true],
'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
'http' => ['timeout' => 2.0, 'ignore_errors' => true],
'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
]);
$resp = @file_get_contents('https://www.kuaidi100.com/autonumber/autoComNum?text=' . urlencode($no), false, $ctx);
if ($resp) {
@@ -107,24 +75,18 @@ class Order extends Base
}
}
}
} catch (\Exception $e) {
} catch (\Throwable $e) {
\think\Log::warning('[Order::detectExpress] ' . $e->getMessage());
}
}
// 3. 常见纯数字位数兜底识别
if ($companyName === '') {
if (preg_match('/^\d{15}$/', $no)) {
$companyName = '德邦快递';
} elseif (preg_match('/^\d{12}$/', $no)) {
$companyName = '顺丰速运';
} elseif (preg_match('/^\d{13}$/', $no)) {
$companyName = '圆通速递';
} elseif (preg_match('/^\d{14}$/', $no)) {
$companyName = '中通快递';
} else {
$companyName = '德邦快递';
}
$this->success('未能唯一识别物流公司,请手动选择', [
'express_no' => $no,
'company_name' => '',
'matched' => false,
]);
return;
}
$this->success('已识别物流公司', [
@@ -157,10 +119,11 @@ class Order extends Base
$reqServiceType = trim((string)$this->request->post('service_type', ''));
$isCustom = (int)$this->request->post('is_custom', 0);
$remark = trim((string)$this->request->post('remark'));
$goodsImages = $this->request->post('goods_images', '');
$rawGoodsImagesIn = $this->postMixed('goods_images', '');
$goodsImages = is_array($rawGoodsImagesIn) ? json_encode($rawGoodsImagesIn, JSON_UNESCAPED_UNICODE) : (string)$rawGoodsImagesIn;
// 支持多商品组合 (goods_list / items)
$goodsListRaw = $this->request->post('goods_list', $this->request->post('items', '', null), null);
$goodsListRaw = $this->postMixed('goods_list', $this->postMixed('items', ''));
$goodsList = [];
if (!empty($goodsListRaw)) {
if (is_string($goodsListRaw)) {
@@ -225,14 +188,29 @@ class Order extends Base
if (!$address) {
$contact = trim((string)$this->request->post('contact'));
$mobile = trim((string)$this->request->post('mobile'));
$province = trim((string)$this->request->post('province', '贵州省'));
$city = trim((string)$this->request->post('city', '贵阳市'));
$province = trim((string)$this->request->post('province', ''));
$city = trim((string)$this->request->post('city', ''));
$district = trim((string)$this->request->post('district', ''));
$detailAddr = trim((string)$this->request->post('address'));
$floor = max(1, (int)$this->request->post('floor', 1));
$hasElevator = (int)$this->request->post('has_elevator', 1);
$lng = trim((string)$this->request->post('lng', ''));
$lat = trim((string)$this->request->post('lat', ''));
if ($contact && $mobile && $detailAddr) {
if ($province === '' || $city === '') {
$this->error('请选择完整的服务地址省市区');
}
if ($lng === '' || $lat === '' || abs((float)$lng) < 0.0001 || abs((float)$lat) < 0.0001) {
$geo = TiandituService::geocoder(trim($province . $city . $district . $detailAddr));
if (!$geo && $city !== '') {
$geo = TiandituService::geocoder(trim($city . $district . $detailAddr));
}
if ($geo) {
$lng = (string)$geo['lng'];
$lat = (string)$geo['lat'];
}
}
$addressId = Db::name('address')->insertGetId([
'user_id' => $this->uid(),
'contact' => $contact,
@@ -241,6 +219,8 @@ class Order extends Base
'city' => $city,
'district' => $district,
'address' => $detailAddr,
'lng' => $lng,
'lat' => $lat,
'floor' => $floor,
'has_elevator' => $hasElevator,
'createtime' => time(),
@@ -253,13 +233,28 @@ class Order extends Base
if (!$address) {
$this->error('请选择或填写完整服务地址');
}
// 所选地址缺少经纬度时在事务开启前自动通过天地图补全并回填
if (empty($address['lng']) || empty($address['lat']) || abs((float)$address['lng']) < 0.0001 || abs((float)$address['lat']) < 0.0001) {
$geo = TiandituService::geocoder(trim(($address['province'] ?? '') . ($address['city'] ?? '') . ($address['district'] ?? '') . ($address['address'] ?? '')));
if ($geo) {
$address['lng'] = (string)$geo['lng'];
$address['lat'] = (string)$geo['lat'];
if (!empty($address['id'])) {
Db::name('address')->where('id', (int)$address['id'])->update([
'lng' => $address['lng'],
'lat' => $address['lat'],
'updatetime' => time(),
]);
}
}
}
if ($appointTime > 0 && $appointTime < time()) {
$this->error('预约时间不能早于当前时间');
}
// 多商品组合名称、总件数与图片汇总
$serviceName = $service ? $service['name'] : '同城综合上门服务';
$catId = $service ? (int)$service['cat_id'] : 1;
$serviceName = $service ? $service['name'] : '自定义上门服务';
$catId = $service ? (int)$service['cat_id'] : 0;
$serviceImage = $service ? $service['image'] : '';
if (!empty($goodsList) && is_array($goodsList)) {
$firstG = reset($goodsList);
@@ -373,6 +368,11 @@ class Order extends Base
'range' => '按面积计价',
];
// 事务外预加载当前生效的按订单维度抽佣规则与默认兜底配置
$customerType = $this->currentMerchantTeam() ? 'merchant' : 'personal';
$activeCommRules = CommissionService::getActiveRules();
$commDefaults = FinanceConfigService::getCommissionDefaults();
Db::startTrans();
try {
$lockedCouponId = 0;
@@ -413,6 +413,14 @@ class Order extends Base
$lockedCouponId = (int)$uc['id'];
}
$commMatch = CommissionService::matchOrderSnapshot([
'price_type' => $priceType,
'customer_type' => $customerType,
'cat_id' => (int)$catId,
'urgent' => $urgent ? 1 : 0,
'order_amount' => (float)$amount['pay_amount'] > 0 ? (float)$amount['pay_amount'] : (float)$amount['total_amount'],
], $activeCommRules, $commDefaults);
$id = (int)Db::name('order')->insertGetId([
'order_no' => $orderNo,
'user_id' => $uid,
@@ -452,9 +460,11 @@ class Order extends Base
'floor_amount' => $amount['floor_amount'],
'urgent_amount' => $amount['urgent_amount'],
'discount_amount' => $amount['discount_amount'],
'total_amount' => $amount['total_amount'],
'pay_amount' => $amount['pay_amount'],
'status' => $initStatus,
'total_amount' => $amount['total_amount'],
'pay_amount' => $amount['pay_amount'],
'commission_rate' => $commMatch['commission_rate'],
'commission_snapshot' => $commMatch['commission_snapshot'],
'status' => $initStatus,
'pay_status' => 0,
'coupon_id' => $lockedCouponId,
'verify_code' => $verifyCode,
@@ -581,6 +591,13 @@ class Order extends Base
}
}
// 事务外静默沉淀本次订单中用户真实上传的商品图片到「历史商品上传图片库」(自动跳过系统默认图)
try {
$this->archiveOrderUploadedGoodsImages($uid, (int)$catId, (string)$serviceName, $goodsList, $goodsImages);
} catch (\Exception $e) {
\think\Log::error('[Order::create archiveGoodsGallery] ' . $e->getMessage());
}
$this->success('下单成功', [
'order_id' => $id,
'order_no' => $orderNo,
@@ -589,175 +606,96 @@ class Order extends Base
}
/**
* 支付(联调模拟支付,pay_type=mock;上线换微信支付回调)
* 发起订单微信 JSAPI 支付(返回小程序 wx.requestPayment 参数包;0元抵扣单直接核销)
* @ApiMethod (POST)
*/
public function pay()
{
$orderId = (int)$this->request->post('order_id');
$payType = $this->request->post('pay_type', 'mock');
$order = $this->ownOrder($orderId, 'user');
$wxCode = trim((string)$this->request->post('wx_code', ''));
$order = $this->ownOrder($orderId, 'user');
if ((int)$order['pay_status'] === 1) {
$this->error('订单已支付,请勿重复支付');
}
if ((int)$order['status'] !== OrderStatus::PENDING_PAY) {
$this->error('订单状态不允许支付');
}
$now = time();
$nextStatus = OrderStatus::PENDING_ACCEPT;
Db::startTrans();
try {
$lockedOrder = Db::name('order')->where('id', $orderId)->lock(true)->find();
if (!$lockedOrder) {
throw new \InvalidArgumentException('订单不存在');
}
if ((int)$lockedOrder['pay_status'] === 1) {
throw new \InvalidArgumentException('订单已支付,请勿重复支付');
}
if ((int)$lockedOrder['status'] !== OrderStatus::PENDING_PAY) {
throw new \InvalidArgumentException('订单状态不允许支付');
}
// 兼容创单阶段已加锁核销的优惠券,防止重复报错或漏锁
if ((int)$lockedOrder['coupon_id'] > 0) {
$uc = Db::name('user_coupon')
->where('id', (int)$lockedOrder['coupon_id'])
->where('user_id', (int)$lockedOrder['user_id'])
->lock(true)
->find();
if (!$uc) {
throw new \InvalidArgumentException('订单关联的优惠券不存在');
}
if ($uc['status'] === 'used' && (int)$uc['order_id'] === $orderId) {
// 创单已锁定本单卡券
} elseif ($uc['status'] === 'unused') {
$affectedUc = Db::name('user_coupon')
->where('id', (int)$uc['id'])
->where('user_id', (int)$lockedOrder['user_id'])
->where('status', 'unused')
->update([
'status' => 'used',
'order_id' => $orderId,
'use_time' => $now,
]);
if (!$affectedUc) {
throw new \InvalidArgumentException('优惠券状态异常,请重新下单');
}
} else {
throw new \InvalidArgumentException('该优惠券已被其他订单使用或已过期');
}
}
Db::name('order')->where('id', $orderId)->update([
'pay_status' => 1,
'pay_type' => $payType,
'pay_time' => $now,
'transaction_id' => 'MOCK' . date('YmdHis', $now) . mt_rand(1000, 9999),
'updatetime' => $now,
]);
$nextStatus = $lockedOrder['price_type'] === 'quote' ? OrderStatus::QUOTING : OrderStatus::PENDING_ACCEPT;
$nextRemark = $nextStatus === OrderStatus::QUOTING
? '支付成功,订单已进入报价大厅,等待师傅报价'
: '支付成功,订单已进入接单大厅';
$this->transit($lockedOrder, $nextStatus, $nextRemark, [], 'user', $this->uid());
$this->addLog($orderId, $nextStatus, $nextStatus === OrderStatus::QUOTING ? '订单进入师傅报价大厅' : '订单进入师傅接单大厅', 'system', 0);
Db::commit();
$res = PaymentService::createOrderJsapiPay($order, $this->uid(), 'order', 0, $wxCode);
} catch (\think\exception\HttpResponseException $e) {
Db::rollback();
throw $e;
} catch (\InvalidArgumentException $e) {
Db::rollback();
$this->error($e->getMessage());
return;
} catch (\Exception $e) {
Db::rollback();
} catch (\Throwable $e) {
\think\Log::error('[Order::pay] ' . $e->getMessage());
$this->error('支付失败:' . $e->getMessage());
$this->error('发起微信支付失败:' . $e->getMessage());
return;
}
// 订单广播通知:进入接单/报价大厅后,通知周边在线认证师傅(排除下单人本人)
if (in_array($nextStatus, [OrderStatus::PENDING_ACCEPT, OrderStatus::QUOTING], true)) {
try {
$masters = Db::name('master')
->where('verify_status', 'pass')
->where('work_status', 'on')
->where('user_id', '<>', (int)$order['user_id'])
->limit(20)
->select();
foreach ($masters as $m) {
$this->notify('master', (int)$m['id'], '新工单就绪通知', '同城有新工单【' . $order['order_no'] . '】进入接单大厅,请尽快前往抢单!', 'order', $orderId);
}
} catch (\Exception $e) {
\think\Log::error('[Order::pay broadcast] ' . $e->getMessage());
}
}
$this->success('支付成功');
$msg = !empty($res['paid']) ? '支付成功' : '请完成微信支付';
$this->success($msg, $res);
}
/**
* 我的订单列表
* 小程序端完成 wx.requestPayment 后主动查单幂等核销(与异步回调双保险闭环)
* @ApiMethod (POST)
*/
public function confirmPay()
{
$outTradeNo = trim((string)$this->request->post('out_trade_no', ''));
$orderId = (int)$this->request->post('order_id', 0);
$payOrder = null;
if ($outTradeNo !== '') {
$payOrder = Db::name('pay_order')->where('out_trade_no', $outTradeNo)->find();
} elseif ($orderId > 0) {
$payOrder = Db::name('pay_order')->where('order_id', $orderId)->order('id desc')->find();
}
if (!$payOrder) {
$this->error('未找到对应的支付交易单');
}
// 强制校验订单归属权限,防止水平越权 IDOR
$this->ownOrder((int)$payOrder['order_id'], 'user');
try {
$res = PaymentService::confirmOrderPay((string)$payOrder['out_trade_no']);
} catch (\think\exception\HttpResponseException $e) {
throw $e;
} catch (\Throwable $e) {
\think\Log::error('[Order::confirmPay] ' . $e->getMessage());
$this->error('查询支付结果失败:' . $e->getMessage());
return;
}
if (empty($res['paid'])) {
$stateText = !empty($res['trade_state_text']) ? (string)$res['trade_state_text'] : '暂未确认到支付成功结果';
$this->error('支付未完成:' . $stateText, $res);
}
$this->success('支付成功', $res);
}
/**
* 用户在线支付施工增项补差价
* 用户在线微信支付施工增项补差价
* @ApiMethod (POST)
*/
public function payDiff()
{
$orderId = (int)$this->request->post('order_id');
$order = $this->ownOrder($orderId, 'user');
$wxCode = trim((string)$this->request->post('wx_code', ''));
$order = $this->ownOrder($orderId, 'user');
if ((int)$order['diff_status'] !== 1 || (float)$order['diff_amount'] <= 0) {
$this->error('当前订单无待支付的增项补差价');
}
$diffAmount = (float)$order['diff_amount'];
$newPayAmount = round((float)$order['pay_amount'] + $diffAmount, 2);
Db::startTrans();
try {
$lockedOrder = Db::name('order')->where('id', $orderId)->lock(true)->find();
if (!$lockedOrder || (int)$lockedOrder['diff_status'] !== 1 || (float)$lockedOrder['diff_amount'] <= 0) {
throw new \InvalidArgumentException('当前订单无待支付的增项补差价');
}
$diffAmount = (float)$lockedOrder['diff_amount'];
$newPayAmount = round((float)$lockedOrder['pay_amount'] + $diffAmount, 2);
Db::name('order')->where('id', $orderId)->update([
'diff_status' => 2,
'pay_amount' => $newPayAmount,
'updatetime' => time(),
]);
$this->addLog($orderId, (int)$lockedOrder['status'], '用户在线支付施工增项补差价 ¥' . $diffAmount, 'user', $this->uid());
Db::commit();
$res = PaymentService::createOrderJsapiPay($order, $this->uid(), 'diff', 0, $wxCode);
} catch (\think\exception\HttpResponseException $e) {
Db::rollback();
throw $e;
} catch (\InvalidArgumentException $e) {
Db::rollback();
$this->error($e->getMessage());
return;
} catch (\Exception $e) {
Db::rollback();
} catch (\Throwable $e) {
\think\Log::error('[Order::payDiff] ' . $e->getMessage());
$this->error('支付失败:' . $e->getMessage());
$this->error('发起补差价支付失败:' . $e->getMessage());
return;
}
if ((int)$order['master_id'] > 0) {
$m = Db::name('master')->where('id', $order['master_id'])->find();
if ($m) {
$this->notify('master', (int)$m['id'], '客户已支付增项补差价', '工单 ' . $order['order_no'] . ' 客户已支付增项补差价 ¥' . $diffAmount, 'order', $orderId);
}
}
$this->success('增项补差价支付成功!', ['pay_amount' => $newPayAmount]);
$this->success('请完成增项补差价微信支付', $res);
}
public function index()
@@ -1230,108 +1168,33 @@ class Order extends Base
}
/**
* 报价订单:用户选择师傅报价(选定后订单进入已接单)
* 报价订单:用户选择师傅报价并发起微信支付托管(付款确认后订单自动锁定师傅并进入已接单)
* @ApiMethod (POST)
*/
public function chooseQuote()
{
$orderId = (int)$this->request->post('order_id');
$quoteId = (int)$this->request->post('quote_id');
$order = $this->ownOrder($orderId, 'user');
$wxCode = trim((string)$this->request->post('wx_code', ''));
$order = $this->ownOrder($orderId, 'user');
if ($order['price_type'] !== 'quote') {
$this->error('该订单不是师傅报价订单');
}
if ((int)$order['status'] !== OrderStatus::QUOTING) {
$this->error('当前状态(' . OrderStatus::label((int)$order['status']) . ')不可选择报价');
}
if ((int)$order['master_id'] > 0) {
$this->error('已选定师傅,请勿重复选择');
}
$quote = Db::name('order_quote')->where('id', $quoteId)->where('order_id', $orderId)->find();
if (!$quote) {
$this->error('报价不存在');
}
if ($quote['status'] !== 'wait') {
$this->error('该报价已失效,请选择其他师傅');
}
if ((int)$quote['expire_time'] > 0 && (int)$quote['expire_time'] < time()) {
Db::name('order_quote')->where('id', $quoteId)->update(['status' => 'expired']);
$this->error('该报价已过期,请选择其他师傅');
}
$master = Db::name('master')->where('id', (int)$quote['master_id'])->find();
if (!$master) {
$this->error('师傅信息不存在');
}
$quoteAmount = round((float)$quote['amount'], 2);
$payAmount = max(0, round($quoteAmount - (float)$order['discount_amount'], 2));
$alreadyPaid = (int)$order['pay_status'] === 1 ? (float)$order['pay_amount'] : 0.0;
$needDiff = max(0, round($payAmount - $alreadyPaid, 2));
$payType = $this->request->post('pay_type', 'wechat');
$remark = '客户已选择 ' . $master['realname'] . ' 的报价 ¥' . $quoteAmount;
if ($needDiff > 0) {
$remark .= '(补付差额 ¥' . $needDiff . ')';
}
$remark .= ',等待师傅联系';
Db::startTrans();
try {
$lockedOrder = Db::name('order')->where('id', $orderId)->lock(true)->find();
if (!$lockedOrder || (int)$lockedOrder['status'] !== OrderStatus::QUOTING || (int)$lockedOrder['master_id'] !== 0) {
throw new \InvalidArgumentException('该工单已选定师傅或状态已变更,请刷新重试');
}
$quoteAmount = round((float)$quote['amount'], 2);
$payAmount = max(0, round($quoteAmount - (float)$lockedOrder['discount_amount'], 2));
$alreadyPaid = (int)$lockedOrder['pay_status'] === 1 ? (float)$lockedOrder['pay_amount'] : 0.0;
$needDiff = max(0, round($payAmount - $alreadyPaid, 2));
$updateData = [
'master_id' => (int)$quote['master_id'],
'accept_time' => time(),
'base_amount' => $quoteAmount,
'floor_amount' => 0,
'urgent_amount' => 0,
'total_amount' => $quoteAmount,
'pay_amount' => $payAmount,
'pay_status' => 1,
];
if ($needDiff > 0) {
$updateData['pay_type'] = $payType;
$updateData['pay_time'] = time();
}
$this->transit($lockedOrder, OrderStatus::ACCEPTED, $remark, $updateData, 'user', $this->uid());
Db::name('order_quote')->where('id', $quoteId)->update(['status' => 'accept']);
Db::name('order_quote')->where('order_id', $orderId)->where('id', '<>', $quoteId)
->where('status', 'wait')->update(['status' => 'reject']);
$this->notify('user', (int)$lockedOrder['user_id'], '已选定服务师傅', $remark, 'order', $orderId);
$this->notify('master', (int)$master['id'], '您的报价已被选中', '订单 ' . $lockedOrder['order_no'] . ' 客户已选择您的报价 ¥' . $quoteAmount . ',请尽快联系客户', 'order', $orderId);
Db::commit();
$res = PaymentService::createOrderJsapiPay($order, $this->uid(), 'quote', $quoteId, $wxCode);
} catch (\think\exception\HttpResponseException $e) {
Db::rollback();
throw $e;
} catch (\InvalidArgumentException $e) {
Db::rollback();
$this->error($e->getMessage());
return;
} catch (\Exception $e) {
Db::rollback();
} catch (\Throwable $e) {
\think\Log::error('[Order::chooseQuote] ' . $e->getMessage());
$this->error('选择报价失败:' . $e->getMessage());
$this->error('选择报价并发起支付失败:' . $e->getMessage());
return;
}
$this->success('已选定师傅并完成支付托管,请等待师傅联系', [
'pay_amount' => $payAmount,
'need_diff' => $needDiff,
'already_pay' => $alreadyPaid,
]);
$msg = !empty($res['paid'])
? '已选定师傅并完成支付托管,请等待师傅联系'
: '请完成报价托管微信支付';
$this->success($msg, $res);
}
/**
@@ -1377,7 +1240,7 @@ class Order extends Base
}
/**
* 取消订单(已支付则模拟退款)
* 取消订单(已支付则发起微信原路退款)
* @ApiMethod (POST)
*/
public function cancel()
@@ -1396,6 +1259,18 @@ class Order extends Base
$this->error('该订单已开具发票,如需取消退款请联系客服办理发票冲红');
}
// 若订单已支付,先在数据库事务外部调用微信支付 APIv3 逐笔发起原路退款(无有效流水严格拦截,严禁静默跳过)
$refundedAmount = 0.00;
if ((int)$order['pay_status'] === 1) {
try {
$refundedAmount = PaymentService::refundOrder($orderId, '用户取消:' . $reason);
} catch (\Throwable $re) {
\think\Log::error('[Order::cancel refund] order_id=' . $orderId . ' reason=' . $re->getMessage());
$this->error('申请微信原路退款失败:' . $re->getMessage());
return;
}
}
$prevMasterId = 0;
Db::startTrans();
try {
@@ -1407,7 +1282,7 @@ class Order extends Base
$extra = ['cancel_reason' => mb_substr($reason, 0, 255)];
if ((int)$lockedOrder['pay_status'] === 1) {
$extra['pay_status'] = 2;
$extra['refund_amount'] = $lockedOrder['pay_amount'];
$extra['refund_amount'] = $refundedAmount > 0 ? $refundedAmount : (float)$lockedOrder['pay_amount'];
}
$this->transit($lockedOrder, OrderStatus::CANCELLED, '用户取消:' . $reason, $extra, 'user', $this->uid());
@@ -1467,9 +1342,10 @@ class Order extends Base
$masterId = (int)$order['master_id'];
$payAmount = (float)$order['pay_amount'];
$rate = 10.00;
$commission = round($payAmount * $rate / 100, 2);
$settleAmount = round($payAmount - $commission, 2);
$settleCalc = CommissionService::calcByOrder($order);
$rate = $settleCalc['commission_rate'];
$commission = $settleCalc['commission'];
$settleAmount = $settleCalc['settle_amount'];
Db::startTrans();
try {
@@ -1479,8 +1355,10 @@ class Order extends Base
}
$masterId = (int)$lockedOrder['master_id'];
$payAmount = (float)$lockedOrder['pay_amount'];
$commission = round($payAmount * $rate / 100, 2);
$settleAmount = round($payAmount - $commission, 2);
$settleCalc = CommissionService::calcByOrder($lockedOrder);
$rate = $settleCalc['commission_rate'];
$commission = $settleCalc['commission'];
$settleAmount = $settleCalc['settle_amount'];
$this->transit($lockedOrder, OrderStatus::COMPLETED, '客户验收通过,订单完成', [
'verify_time' => time(),
@@ -1694,14 +1572,22 @@ class Order extends Base
$count = 0;
foreach ($rows as $order) {
$orderId = (int)$order['id'];
$masterId = (int)$order['master_id'];
$payAmount = (float)$order['pay_amount'];
$rate = 10.00;
$commission = round($payAmount * $rate / 100, 2);
$settleAmount = round($payAmount - $commission, 2);
Db::startTrans();
try {
$lockedOrder = Db::name('order')->where('id', $orderId)->lock(true)->find();
if (!$lockedOrder || (int)$lockedOrder['status'] !== OrderStatus::PENDING_VERIFY || (int)$lockedOrder['settle_status'] === 1) {
Db::rollback();
continue;
}
$masterId = (int)$lockedOrder['master_id'];
$payAmount = (float)$lockedOrder['pay_amount'];
$settleCalc = CommissionService::calcByOrder($lockedOrder);
$rate = $settleCalc['commission_rate'];
$commission = $settleCalc['commission'];
$settleAmount = $settleCalc['settle_amount'];
Db::name('order')->where('id', $orderId)->update([
'status' => OrderStatus::COMPLETED,
'verify_time' => time(),
@@ -1798,6 +1684,7 @@ class Order extends Base
{
$uid = $this->uid();
$catId = (int)$this->request->param('cat_id', 0);
$preferCatId = (int)$this->request->param('prefer_cat_id', 0);
$keyword = trim((string)$this->request->param('keyword', ''));
$cats = Db::name('service_cat')
@@ -1824,7 +1711,7 @@ class Order extends Base
$seenUrls = [];
foreach ($libRows as $r) {
$rawImg = trim((string)$r['image']);
if ($rawImg === '') {
if ($rawImg === '' || $this->isSystemDefaultImageUrl($rawImg)) {
continue;
}
$fullUrl = strpos($rawImg, 'http') === 0 ? $rawImg : cdnurl($rawImg, true);
@@ -1834,7 +1721,7 @@ class Order extends Base
'id' => (int)$r['id'],
'cat_id' => $cid,
'cat_name' => isset($catNameMap[$cid]) ? $catNameMap[$cid] : '通用商品',
'title' => (string)($r['title'] ?: '我的商品图'),
'title' => (string)($r['title'] ?: '历史上传商品'),
'image_url' => $fullUrl,
'source' => 'library',
'can_delete' => 1,
@@ -1883,8 +1770,8 @@ class Order extends Base
}
foreach ($candidates as $cand) {
$rawIm = $cand['img'];
// 排除 SVG 图标与系统图库静态参考图,仅保留用户真实上传图
if (substr(strtolower($rawIm), -4) === '.svg' || strpos($rawIm, '/gallery/') !== false || strpos($rawIm, '/goods/') !== false) {
// 排除 SVG 图标与系统图库静态参考图,仅保留用户真实上传过的历史商品图
if ($this->isSystemDefaultImageUrl($rawIm)) {
continue;
}
if ($keyword !== '' && mb_strpos($cand['title'], $keyword) === false) {
@@ -1902,19 +1789,120 @@ class Order extends Base
'cat_name' => isset($catNameMap[$cid]) ? $catNameMap[$cid] : '历史订单',
'title' => $cand['title'],
'image_url' => $fullUrl,
'source' => 'history',
'source' => 'order',
'can_delete' => 0,
'time_text' => $ho['createtime'] ? date('Y-m-d', (int)$ho['createtime']) : '',
];
}
}
if ($catId === 0 && $preferCatId > 0 && count($list) > 1) {
usort($list, function ($a, $b) use ($preferCatId) {
$aMatch = ((int)$a['cat_id'] === $preferCatId) ? 1 : 0;
$bMatch = ((int)$b['cat_id'] === $preferCatId) ? 1 : 0;
if ($aMatch !== $bMatch) {
return $bMatch <=> $aMatch;
}
return 0;
});
}
$this->success('', [
'cats' => $cats,
'list' => $list,
]);
}
/**
* 判断图片是否为平台系统默认参考图(避免将系统默认图混入用户个人的历史商品上传图库)
*/
protected function isSystemDefaultImageUrl($url)
{
$u = strtolower(trim((string)$url));
if ($u === '' || substr($u, -4) === '.svg') {
return true;
}
if (strpos($u, '/gallery/') !== false || strpos($u, '/goods/') !== false || strpos($u, '/uploads/service/') !== false || strpos($u, '/uploads/services/') !== false) {
return true;
}
return false;
}
/**
* 订单创建成功后将用户真实上传的商品图片自动沉淀到「历史商品上传图片库」
*/
protected function archiveOrderUploadedGoodsImages($uid, $defaultCatId, $defaultTitle, $goodsList, $rawGoodsImages)
{
$uid = (int)$uid;
if ($uid <= 0) {
return;
}
$entries = [];
if (!empty($goodsList) && is_array($goodsList)) {
foreach ($goodsList as $g) {
if (!is_array($g)) {
continue;
}
$gCatId = !empty($g['cat_id']) ? (int)$g['cat_id'] : (int)$defaultCatId;
$gTitle = !empty($g['custom_name']) ? trim((string)$g['custom_name']) : (!empty($g['item_name']) ? trim((string)$g['item_name']) : trim((string)$defaultTitle));
if (!empty($g['spec_name']) && $g['spec_name'] !== $gTitle) {
$gTitle .= '(' . trim((string)$g['spec_name']) . ')';
}
$imgs = isset($g['images']) && is_array($g['images']) ? $g['images'] : [];
foreach ($imgs as $im) {
if (is_string($im) && !$this->isSystemDefaultImageUrl($im)) {
$entries[] = ['cat_id' => $gCatId, 'title' => mb_substr($gTitle ?: '历史上传商品', 0, 80), 'url' => trim($im)];
}
}
}
} elseif (!empty($rawGoodsImages)) {
$arr = is_array($rawGoodsImages) ? $rawGoodsImages : (json_decode((string)$rawGoodsImages, true) ?: explode(',', (string)$rawGoodsImages));
foreach ($arr as $im) {
if (is_string($im) && !$this->isSystemDefaultImageUrl($im)) {
$entries[] = ['cat_id' => (int)$defaultCatId, 'title' => mb_substr(trim((string)$defaultTitle) ?: '历史上传商品', 0, 80), 'url' => trim($im)];
}
}
}
if (empty($entries)) {
return;
}
$now = time();
foreach ($entries as $ent) {
$rawU = $ent['url'];
if ($rawU === '' || strlen($rawU) > 255) {
continue;
}
$fullUrl = strpos($rawU, 'http') === 0 ? $rawU : cdnurl($rawU, true);
$exists = Db::name('user_goods_gallery')
->where('user_id', $uid)
->where('image', 'in', [$rawU, $fullUrl])
->value('id');
if ($exists) {
continue;
}
Db::name('user_goods_gallery')->insert([
'user_id' => $uid,
'cat_id' => max(0, (int)$ent['cat_id']),
'title' => $ent['title'],
'image' => $fullUrl,
'createtime' => $now,
]);
}
}
/**
* 安全读取兼容 JSON 数组与字符串的 POST 参数(规避 ThinkPHP 5 无 /a 修饰符时对数组抛类型异常)
*/
protected function postMixed($key, $default = null)
{
$all = $this->request->post(false);
if (is_array($all) && array_key_exists($key, $all)) {
return $all[$key];
}
return $default;
}
/**
* 上传保存商品图至个人专属商品图库
* @ApiMethod (POST)
@@ -1925,7 +1913,7 @@ class Order extends Base
$catId = max(0, (int)$this->request->post('cat_id', 0));
$title = mb_substr(trim((string)$this->request->post('title', '')), 0, 80);
$singleImg = trim((string)$this->request->post('image', ''));
$rawImages = $this->request->post('images', '', null);
$rawImages = $this->postMixed('images', '');
$imgList = [];
if ($singleImg !== '') {
@@ -1944,13 +1932,17 @@ class Order extends Base
}
}
if (empty($imgList)) {
$this->error('请上传有效的商品图片');
}
$validUrls = [];
foreach ($imgList as $u) {
if (!is_string($u)) {
continue;
}
$u = trim($u);
if ($u === '' || strlen($u) > 255 || substr(strtolower($u), -4) === '.svg') {
if ($u === '' || strlen($u) > 255 || $this->isSystemDefaultImageUrl($u)) {
continue;
}
if (strpos($u, 'http://') === 0 || strpos($u, 'https://') === 0 || strpos($u, '/') === 0) {
@@ -1959,7 +1951,7 @@ class Order extends Base
}
$validUrls = array_values(array_unique($validUrls));
if (empty($validUrls)) {
$this->error('请上传有效的商品图片');
$this->success('系统默认图片无需重复保存到历史图库', ['added' => 0, 'list' => []]);
}
if ($title === '' && $catId > 0) {
@@ -1971,6 +1963,7 @@ class Order extends Base
$now = time();
$saved = [];
$addedCount = 0;
foreach ($validUrls as $u) {
$fullUrl = strpos($u, 'http') === 0 ? $u : cdnurl($u, true);
$exists = Db::name('user_goods_gallery')
@@ -1995,6 +1988,7 @@ class Order extends Base
'image' => $fullUrl,
'createtime' => $now,
]);
$addedCount++;
$saved[] = [
'id' => $newId,
'cat_id' => $catId,
@@ -2005,7 +1999,7 @@ class Order extends Base
];
}
$this->success('已存入商品图库', ['list' => $saved]);
$this->success('已存入商品图库', ['added' => $addedCount, 'list' => $saved]);
}
/**
@@ -2016,7 +2010,7 @@ class Order extends Base
{
$uid = $this->uid();
$singleId = (int)$this->request->post('id', 0);
$rawIds = $this->request->post('ids', '', null);
$rawIds = $this->postMixed('ids', '');
$idArr = [];
if ($singleId > 0) {
@@ -2249,7 +2243,7 @@ class Order extends Base
$tplName = $itemName . ($specName !== '' && $specName !== $itemName ? (' · ' . $specName) : '');
}
$rawExtras = $this->request->post('extras', '', null);
$rawExtras = $this->postMixed('extras', '');
$extrasArr = [];
if (!empty($rawExtras)) {
$decEx = is_array($rawExtras) ? $rawExtras : json_decode(htmlspecialchars_decode((string)$rawExtras), true);
@@ -2268,7 +2262,7 @@ class Order extends Base
}
}
$rawImages = $this->request->post('images', '', null);
$rawImages = $this->postMixed('images', '');
$imagesArr = [];
if (!empty($rawImages)) {
$decIm = is_array($rawImages) ? $rawImages : json_decode(htmlspecialchars_decode((string)$rawImages), true);

查看文件

@@ -3,12 +3,9 @@
namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use think\Hook;
/**
* 手机短信接口
* 手机短信接口(短信验证码通道已下线)
*/
class Sms extends Api
{
@@ -16,89 +13,20 @@ class Sms extends Api
protected $noNeedRight = '*';
/**
* 发送验证码
*
* 发送验证码(已移除)
* @ApiMethod (POST)
* @ApiParams (name="mobile", type="string", required=true, description="手机号")
* @ApiParams (name="event", type="string", required=true, description="事件名称")
*/
public function send()
{
$mobile = $this->request->post("mobile");
$event = $this->request->post("event");
$event = $event ? $event : 'register';
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('手机号不正确'));
}
$last = Smslib::get($mobile, $event);
if ($last && time() - $last['createtime'] < 60) {
$this->error(__('发送频繁'));
}
$ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
if ($ipSendTotal >= 5) {
$this->error(__('发送频繁'));
}
if ($event) {
$userinfo = User::getByMobile($mobile);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changemobile']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
if (!Hook::get('sms_send')) {
$this->error(__('请在后台插件管理安装短信验证插件'));
}
$ret = Smslib::send($mobile, null, $event);
if ($ret) {
$this->success(__('发送成功'));
} else {
$this->error(__('发送失败,请检查短信配置是否正确'));
}
$this->error('短信验证码通道已移除,请使用手机号密码或微信一键登录');
}
/**
* 检测验证码
*
* 检测验证码(已移除)
* @ApiMethod (POST)
* @ApiParams (name="mobile", type="string", required=true, description="手机号")
* @ApiParams (name="event", type="string", required=true, description="事件名称")
* @ApiParams (name="captcha", type="string", required=true, description="验证码")
*/
public function check()
{
$mobile = $this->request->post("mobile");
$event = $this->request->post("event");
$event = $event ? $event : 'register';
$captcha = $this->request->post("captcha");
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('手机号不正确'));
}
if ($event) {
$userinfo = User::getByMobile($mobile);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changemobile']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
$ret = Smslib::check($mobile, $captcha, $event);
if ($ret) {
$this->success(__('成功'));
} else {
$this->error(__('验证码不正确'));
}
$this->error('短信验证码通道已移除,请使用手机号密码或微信一键登录');
}
}

查看文件

@@ -4,8 +4,6 @@ namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
@@ -59,82 +57,23 @@ class User extends Api
}
/**
* 手机验证码登录
* 手机验证码登录(已移除)
*
* @ApiMethod (POST)
* @ApiParams (name="mobile", type="string", required=true, description="手机号")
* @ApiParams (name="captcha", type="string", required=true, description="验证码")
*/
public function mobilelogin()
{
$mobile = $this->request->post('mobile');
$captcha = $this->request->post('captcha');
if (!$mobile || !$captcha) {
$this->error(__('Invalid parameters'));
}
if (!Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
if (!Sms::check($mobile, $captcha, 'mobilelogin', true)) {
$this->error(__('Captcha is incorrect'));
}
$user = \app\common\model\User::getByMobile($mobile);
if ($user) {
if ($user->status != 'normal') {
$this->error(__('Account is locked'));
}
//如果已经有账号则直接登录
$ret = $this->auth->direct($user->id);
} else {
$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
}
if ($ret) {
Sms::flush($mobile, 'mobilelogin');
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success(__('Logged in successful'), $data);
} else {
$this->error($this->auth->getError());
}
$this->error('短信验证码通道已移除,请使用手机号密码或微信一键登录');
}
/**
* 注册会员
* 注册会员(短信验证通道已移除)
*
* @ApiMethod (POST)
* @ApiParams (name="username", type="string", required=true, description="用户名")
* @ApiParams (name="password", type="string", required=true, description="密码")
* @ApiParams (name="email", type="string", required=true, description="邮箱")
* @ApiParams (name="mobile", type="string", required=true, description="手机号")
* @ApiParams (name="code", type="string", required=true, description="验证码")
*/
public function register()
{
$username = $this->request->post('username');
$password = $this->request->post('password');
$email = $this->request->post('email');
$mobile = $this->request->post('mobile');
$code = $this->request->post('code');
if (!$username || !$password) {
$this->error(__('Invalid parameters'));
}
if ($email && !Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));
}
if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
$ret = Sms::check($mobile, $code, 'register', true);
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
$ret = $this->auth->register($username, $password, $email, $mobile, []);
if ($ret) {
Sms::flush($mobile, 'register');
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success(__('Sign up successful'), $data);
} else {
$this->error($this->auth->getError());
}
$this->error('短信验证码通道已移除,请使用手机号密码或微信一键登录');
}
/**
@@ -229,38 +168,13 @@ class User extends Api
}
/**
* 修改手机号
* 修改手机号(短信验证通道已移除)
*
* @ApiMethod (POST)
* @ApiParams (name="mobile", type="string", required=true, description="手机号")
* @ApiParams (name="captcha", type="string", required=true, description="验证码")
*/
public function changemobile()
{
$user = $this->auth->getUser();
$mobile = $this->request->post('mobile');
$captcha = $this->request->post('captcha');
if (!$mobile || !$captcha) {
$this->error(__('Invalid parameters'));
}
if (!Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
$this->error(__('Mobile already exists'));
}
$result = Sms::check($mobile, $captcha, 'changemobile', true);
if (!$result) {
$this->error(__('Captcha is incorrect'));
}
$verification = $user->verification;
$verification->mobile = 1;
$user->verification = $verification;
$user->mobile = $mobile;
$user->save();
Sms::flush($mobile, 'changemobile');
$this->success();
$this->error('短信验证码通道已移除,暂不支持短信换绑手机号');
}
/**
@@ -318,18 +232,7 @@ class User extends Api
$this->error(__('Password must be 6 to 30 characters'));
}
if ($type == 'mobile') {
if (!Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
$user = \app\common\model\User::getByMobile($mobile);
if (!$user) {
$this->error(__('User not found'));
}
$ret = Sms::check($mobile, $captcha, 'resetpwd', true);
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
Sms::flush($mobile, 'resetpwd');
$this->error('短信验证码通道已移除,暂不支持手机短信找回密码');
} else {
if (!Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));

查看文件

@@ -124,22 +124,13 @@ class Validate extends Api
}
/**
* 检测手机验证码
* 检测手机验证码(已移除)
*
* @ApiMethod (POST)
* @ApiParams (name="mobile", type="string", required=true, description="手机号")
* @ApiParams (name="captcha", type="string", required=true, description="验证码")
* @ApiParams (name="event", type="string", required=true, description="事件")
*/
public function check_sms_correct()
{
$mobile = $this->request->post('mobile');
$captcha = $this->request->post('captcha');
$event = $this->request->post('event');
if (!\app\common\library\Sms::check($mobile, $captcha, $event)) {
$this->error(__('验证码不正确'));
}
$this->success();
$this->error('短信验证码通道已移除');
}
/**

查看文件

@@ -0,0 +1,140 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\PaymentService;
use app\common\library\WxPayV3Service;
use think\Db;
use think\Log;
use think\Response;
/**
* 微信支付 APIv3 异步通知回调控制器
* 覆盖:JSAPI 交易支付通知 / 原路退款通知 / 商家转账(1005)结果通知
*/
class Wxpay extends Api
{
protected $noNeedLogin = ['notify', 'refundNotify', 'transferNotify'];
protected $noNeedRight = '*';
/**
* 1. 微信支付交易结果异步通知 (/api/wxpay/notify)
*/
public function notify()
{
try {
$parsed = $this->parseAndVerifyCallback();
$eventType = strtoupper($parsed['event_type']);
$data = $parsed['data'];
if ($eventType === 'TRANSACTION.SUCCESS' && !empty($data['out_trade_no'])) {
PaymentService::confirmOrderPay((string)$data['out_trade_no'], $data);
}
return $this->wxResponse(true);
} catch (\Throwable $e) {
Log::error('[Wxpay::notify] ' . $e->getMessage());
return $this->wxResponse(false, $e->getMessage());
}
}
/**
* 2. 微信原路退款结果异步通知 (/api/wxpay/refundNotify)
*/
public function refundNotify()
{
try {
$parsed = $this->parseAndVerifyCallback();
$data = $parsed['data'];
$outRefundNo = trim((string)($data['out_refund_no'] ?? ''));
$outTradeNo = trim((string)($data['out_trade_no'] ?? ''));
$refStatus = strtoupper((string)($data['refund_status'] ?? ''));
if ($outRefundNo === '' && $outTradeNo === '') {
throw new \RuntimeException('退款回调缺少商户退款单号与商户支付单号');
}
$q = Db::name('pay_order');
if ($outRefundNo !== '') {
$q->where('refund_no', $outRefundNo);
} else {
$q->where('out_trade_no', $outTradeNo);
}
$po = $q->find();
if (!$po) {
Log::error("[Wxpay::refundNotify] 未找到本地支付流水单 out_refund_no={$outRefundNo}, out_trade_no={$outTradeNo}");
throw new \RuntimeException('未匹配到本地支付交易流水单');
}
try {
PaymentService::applyWxRefundResult($po, $data);
} catch (\Throwable $refundEx) {
// 若微信已下发明确退款异常/关闭终态,系统已完整落库记录原因并写入告警日志,向微信回传成功避免重复轰炸
if (in_array($refStatus, ['ABNORMAL', 'CLOSED'], true)) {
Log::error("[Wxpay::refundNotify] 退款终态异常已落库 out_trade_no={$po['out_trade_no']}, status={$refStatus}, reason=" . $refundEx->getMessage());
return $this->wxResponse(true);
}
throw $refundEx;
}
return $this->wxResponse(true);
} catch (\Throwable $e) {
Log::error('[Wxpay::refundNotify] ' . $e->getMessage());
return $this->wxResponse(false, $e->getMessage());
}
}
/**
* 3. 微信新版「商家转账」终态结果异步通知 (/api/wxpay/transferNotify)
*/
public function transferNotify()
{
try {
$parsed = $this->parseAndVerifyCallback();
$data = $parsed['data'];
$outBillNo = trim((string)($data['out_bill_no'] ?? ''));
if ($outBillNo === '') {
throw new \RuntimeException('商家转账回调缺少商户转账单号 out_bill_no');
}
$wd = Db::name('withdraw')->where('out_bill_no', $outBillNo)->find();
if (!$wd) {
Log::error("[Wxpay::transferNotify] 未找到本地提现单记录 out_bill_no={$outBillNo}");
throw new \RuntimeException('未找到匹配的本地提现单');
}
PaymentService::syncWithdrawTransfer((int)$wd['id'], $data);
return $this->wxResponse(true);
} catch (\Throwable $e) {
Log::error('[Wxpay::transferNotify] ' . $e->getMessage());
return $this->wxResponse(false, $e->getMessage());
}
}
/**
* 读取原始报文并使用微信支付公钥验签 + AES-256-GCM 解密
*/
protected function parseAndVerifyCallback()
{
$rawBody = file_get_contents('php://input');
if ($rawBody === false || $rawBody === '') {
$rawBody = (string)$this->request->getInput();
}
$headers = $this->request->header();
$wxSvc = new WxPayV3Service();
return $wxSvc->verifyAndDecryptNotify((string)$rawBody, is_array($headers) ? $headers : []);
}
/**
* 输出符合微信支付 APIv3 规范的 HTTP 响应
*/
protected function wxResponse($ok, $msg = '')
{
$code = $ok ? 200 : 500;
$body = [
'code' => $ok ? 'SUCCESS' : 'FAIL',
'message' => $ok ? '成功' : ($msg ?: '处理失败'),
];
return Response::create($body, 'json', $code);
}
}