feat: 新增账号安全模块及资质校验功能

- 新增账号安全页面及支付密码验证组件
- 新增用户类型选择流程及商家资质管理
- 新增订单资质校验逻辑,师傅需满足订单证书要求
- 新增企业资质认证相关数据库表及接口
- 优化用户列表展示,区分个人与商家用户类型
这个提交包含在:
2026-11-21 15:37:01 +08:00
父节点 8a35d93a15
当前提交 b71980dd6b
共有 58 个文件被更改,包括 1515 次插入 和 169 次删除

查看文件

@@ -80,7 +80,7 @@ class Home extends Backend
// 4. 实时待办预警与风控中心(6大核心运营待办)
$pendingMaster = Master::where('verify_status', 'pending')->count();
$pendingMerchant = Merchant::where('verify_status', 'pending')->count();
$pendingMerchant = Db::name('user_enterprise_cert')->where('verify_status', 'pending')->count();
$waitingAppeal = Appeal::where('status', 'wait')->count();
$waitingWithdraw = Withdraw::where('status', 'wait')->count();
$waitingInvoice = Db::name('invoice')->where('status', 'wait')->count();

查看文件

@@ -144,7 +144,7 @@ class MasterCert extends Backend
? "技能证书审核通过({$certName})"
: "技能证书审核未通过({$certName})";
$msgContent = $status === 'pass'
? "您上传的「{$certName}」已通过平台审核,可正常承接对应资质要求的工单。"
? "您上传的「{$certName}」已通过平台审核,有效期内可向相关订单用户展示。"
: ("您上传的「{$certName}」未通过审核,原因:" . ($auditMsg !== '' ? $auditMsg : '照片不清晰或证件不符合要求,请重新上传。'));
Db::name('message')->insert([

查看文件

@@ -30,12 +30,68 @@ class Merchant extends Backend
$this->view->assign("verifyStatusList", $this->model->getVerifyStatusList());
}
/** 独立展示用户提交的企业资质;审核接口沿用原权限。 */
public function certificates()
{
return $this->view->fetch();
}
public function index()
{
$this->request->filter(['strip_tags', 'trim']);
if (false === $this->request->isAjax()) {
return $this->view->fetch();
}
if ($this->request->isPost() && $this->request->post('view') === 'audit_cert') {
if (!$this->auth->check('merchant/edit')) $this->error('无权审核企业资质');
$this->token();
$id = (int)$this->request->post('id');
$decision = (string)$this->request->post('decision', '');
$reason = trim((string)$this->request->post('audit_msg', ''));
if (!in_array($decision, ['pass', 'reject'], true)) $this->error('审核状态无效');
if ($decision === 'reject' && $reason === '') $this->error('请输入驳回原因');
if (mb_strlen($reason) > 500) $this->error('驳回原因过长');
$updated = Db::name('user_enterprise_cert')->where('id', $id)->where('verify_status', 'pending')->update([
'verify_status' => $decision, 'audit_msg' => $decision === 'reject' ? $reason : '', 'updatetime' => time(),
]);
if (!$updated) $this->error('申请不存在或已处理,请刷新');
$this->success('审核完成');
}
if ($this->request->get('view') === 'certs') {
$offset = max(0, (int)$this->request->get('offset', 0));
$limit = min(100, max(1, (int)$this->request->get('limit', 20)));
$search = trim((string)$this->request->get('search', ''));
$makeQuery = function () use ($search) {
$query = Db::name('user_enterprise_cert')->alias('c')->join('user u', 'u.id = c.user_id', 'LEFT');
if ($search !== '') $query->where(function ($q) use ($search) {
$q->where('c.company_name', 'like', '%' . $search . '%')->whereOr('c.license_no', 'like', '%' . $search . '%')->whereOr('u.mobile', 'like', '%' . $search . '%');
});
return $query;
};
$total = $makeQuery()->count();
$rows = $makeQuery()->field('c.*,u.nickname,u.mobile,u.user_type')->order('c.id', 'desc')->limit($offset, $limit)->select();
foreach ($rows as &$row) $row['license_url'] = cdnurl($row['license_image'], true);
unset($row);
return json(['total' => $total, 'rows' => $rows]);
}
if ($this->request->get('view') === 'accounts') {
$offset = max(0, (int)$this->request->get('offset', 0));
$limit = min(100, max(1, (int)$this->request->get('limit', 20)));
$search = trim((string)$this->request->get('search', ''));
$makeQuery = function () use ($search) {
$query = Db::name('user')->where('user_type', 'merchant')->where('identity_selected', 1);
if ($search !== '') $query->where(function ($q) use ($search) {
$q->where('nickname', 'like', '%' . $search . '%')
->whereOr('mobile', 'like', '%' . $search . '%')
->whereOr('company_name', 'like', '%' . $search . '%');
});
return $query;
};
$total = $makeQuery()->count();
$rows = $makeQuery()->field('id,nickname,mobile,company_name,company_legal_person,company_legal_mobile,company_tech_mobile,createtime')
->order('id', 'desc')->limit($offset, $limit)->select();
return json(['total' => $total, 'rows' => $rows]);
}
if ($this->request->request('keyField')) {
return $this->selectpage();
}

查看文件

@@ -445,6 +445,9 @@ class Order extends Backend
if (!$targetMaster || $targetMaster['verify_status'] !== 'pass') {
$this->error('所选师傅不存在或未通过实名认证');
}
if (!\app\common\library\OrderQualification::forMaster($row['qual_req'] ?? '', $masterId)) {
$this->error('所选师傅未持有符合订单要求的有效认证证书:' . $row['qual_req']);
}
$oldMasterId = (int)$row['master_id'];
if ($oldMasterId === $masterId && (int)$row['status'] >= 3) {
$this->error('当前工单已由该师傅承接,无需重复指派');

查看文件

@@ -39,11 +39,13 @@ class User extends Backend
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->with('group')
->where($where)
->order($sort, $order)
->paginate($limit);
$filters = json_decode((string)$this->request->get('filter', '{}'), true);
$selectedType = is_array($filters) ? ($filters['user_type'] ?? null) : null;
$query = $this->model->with('group')->where($where);
if (in_array($selectedType, ['personal', 'merchant'], true)) {
$query->where('user.identity_selected', 1);
}
$list = $query->order($sort, $order)->paginate($limit);
$rows = $list->items();
$uids = array_column($rows, 'id');
@@ -103,6 +105,13 @@ class User extends Backend
$v->hidden(['password', 'salt']);
$roles = [];
if (!(int)$v['identity_selected']) {
$roles[] = ['type' => 'unselected', 'label' => '待选择用户类型'];
} elseif ($v['user_type'] === 'merchant') {
$roles[] = ['type' => 'merchant_user', 'label' => '商家用户'];
} else {
$roles[] = ['type' => 'owner', 'label' => '个人用户'];
}
if (isset($masterMap[$uid]) && $masterMap[$uid]['verify_status'] === 'pass') {
$roles[] = ['type' => 'master', 'label' => '认证师傅 (' . $masterMap[$uid]['realname'] . ')'];
}
@@ -111,10 +120,6 @@ class User extends Backend
} elseif (isset($memberMap[$uid]) && !empty($memberMap[$uid])) {
$roles[] = ['type' => 'member', 'label' => '企业子账号 (' . $memberMap[$uid] . ')'];
}
if (empty($roles)) {
$roles[] = ['type' => 'owner', 'label' => '个人业主'];
}
$v['role_badges'] = $roles;
$v['order_count'] = $orderStatMap[$uid]['cnt'] ?? 0;
$v['total_spent'] = $orderStatMap[$uid]['spent'] ?? '0.00';
@@ -139,6 +144,7 @@ class User extends Backend
$uid = (int)$row['id'];
$masterProfile = Db::name('master')->where('user_id', $uid)->find();
$enterpriseCert = Db::name('user_enterprise_cert')->where('user_id', $uid)->find();
$merchantProfile = Db::name('merchant')->where('user_id', $uid)->find();
if (!$merchantProfile) {
$memberBind = Db::name('merchant_member')->alias('mm')
@@ -201,6 +207,7 @@ class User extends Backend
'row' => $row,
'masterProfile' => $masterProfile,
'merchantProfile' => $merchantProfile,
'enterpriseCert' => $enterpriseCert,
'addressList' => $addressList,
'recentOrders' => $recentOrders,
'coupons' => $coupons,

查看文件

@@ -61,4 +61,7 @@
config: {$config|json_encode}
};
require.config.site.version += "-admin-list-20261119";
if (require.config.controllername === 'merchant' || require.config.controllername === 'user.user') {
require.config.site.version += "-identity-security-20261121";
}
</script>

查看文件

@@ -448,13 +448,13 @@
</a>
<!-- 商家待审 -->
<a href="{:url('merchant/index', ['verify_status' => 'pending'])}" class="action-card addtabsit" title="企业商家">
<a href="{:url('merchant/certificates')}" class="action-card addtabsit" title="企业资质认证">
<div class="action-info">
<div class="action-icon" style="background: #f0fdf4; color: #16a34a;">
<i class="fa fa-building-o"></i>
</div>
<div class="action-text">
<div class="name">商家待审核</div>
<div class="name">企业资质待审核</div>
<div class="sub">企业资质核验</div>
</div>
</div>

查看文件

@@ -0,0 +1,8 @@
<div class="panel panel-default panel-intro">
<div class="panel-heading"><strong>企业资质认证</strong><p class="text-muted">个人用户和商家用户均可提交企业资质认证;认证不会改变用户类型。</p></div>
<div class="panel-body">
<form id="cert-audit-token">{:token()}</form>
<div id="certs-toolbar" class="toolbar"><a href="javascript:;" class="btn btn-primary" id="certs-refresh" title="刷新"><i class="fa fa-refresh"></i></a></div>
<table id="certs-table" class="table table-striped table-bordered table-hover table-nowrap" data-operate-audit="{:$auth->check('merchant/edit')}" width="100%"></table>
</div>
</div>

查看文件

@@ -1,8 +1,8 @@
<div class="panel panel-default panel-intro">
<div class="panel-heading">
{:build_heading(null,FALSE)}
<span>企业业务档案及旧资质记录</span>
<ul class="nav nav-tabs" data-field="verify_status">
<li class="{:$Think.get.verify_status === null ? 'active' : ''}"><a href="#t-all" data-value="" data-toggle="tab">全部商家</a></li>
<li class="{:$Think.get.verify_status === null ? 'active' : ''}"><a href="#t-all" data-value="" data-toggle="tab">全部档案</a></li>
<li class="{:$Think.get.verify_status === 'pending' ? 'active' : ''}"><a href="#t-pending" data-value="pending" data-toggle="tab"><i class="fa fa-clock-o text-warning"></i> 企业资质待审</a></li>
<li class="{:$Think.get.verify_status === 'pass' ? 'active' : ''}"><a href="#t-pass" data-value="pass" data-toggle="tab"><i class="fa fa-check-circle text-success"></i> 认证通过</a></li>
<li class="{:$Think.get.verify_status === 'reject' ? 'active' : ''}"><a href="#t-reject" data-value="reject" data-toggle="tab"><i class="fa fa-times-circle text-danger"></i> 已驳回</a></li>
@@ -30,3 +30,4 @@
</div>
</div>
</div>

查看文件

@@ -35,12 +35,16 @@
<div class="ud-name">
<span>{$row.nickname|default=$row.username|htmlentities}</span>
<span class="label {if $row.status=='normal'}label-success{else/}label-default{/if}">{if $row.status=='normal'}正常{else/}已停用{/if}</span>
<span class="label {if $row.user_type=='merchant' && $row.identity_selected}label-primary{else/}label-default{/if}">{if !$row.identity_selected}待选择用户类型{elseif $row.user_type=='merchant'/}商家用户{else/}个人用户{/if}</span>
{if !empty($masterProfile) && $masterProfile.verify_status=='pass'}
<span class="label label-warning"><i class="fa fa-wrench"></i> 认证师傅:{$masterProfile.realname|htmlentities}</span>
{/if}
{if !empty($merchantProfile) && $merchantProfile.verify_status=='pass'}
<span class="label label-primary"><i class="fa fa-building-o"></i> 关联企业:{$merchantProfile.name|htmlentities}</span>
{/if}
{if !empty($enterpriseCert)}
<span class="label label-info">企业资质:{if $enterpriseCert.verify_status=='pass'}已认证{elseif $enterpriseCert.verify_status=='pending'/}审核中{else/}未通过{/if}</span>
{/if}
</div>
<div class="ud-sub">
账号: {$row.username|htmlentities} &nbsp;|&nbsp;
@@ -66,6 +70,32 @@
</div>
</div>
{if !empty($enterpriseCert)}
<div class="ud-card">
<div class="ud-card-hd"><i class="fa fa-certificate"></i> 企业资质认证</div>
<div class="ud-card-bd">
<table class="table table-bordered table-condensed" style="margin-bottom:0;"><tbody>
<tr><th>企业名称</th><td>{$enterpriseCert.company_name|htmlentities}</td><th>营业执照号码</th><td>{$enterpriseCert.license_no|htmlentities}</td></tr>
<tr><th>法人姓名</th><td>{$enterpriseCert.legal_person|default='未填写'|htmlentities}</td><th>审核结果</th><td>{if $enterpriseCert.verify_status=='pass'}已通过{elseif $enterpriseCert.verify_status=='pending'/}待审核{else/}已驳回:{$enterpriseCert.audit_msg|htmlentities}{/if}</td></tr>
</tbody></table>
</div>
</div>
{/if}
{if $row.identity_selected && $row.user_type=='merchant'}
<div class="ud-card">
<div class="ud-card-hd"><i class="fa fa-building-o"></i> 商家用户资料</div>
<div class="ud-card-bd">
<table class="table table-bordered table-condensed" style="margin-bottom:0;">
<tbody>
<tr><th>公司名称</th><td>{$row.company_name|default='未填写'|htmlentities}</td><th>法人姓名</th><td>{$row.company_legal_person|default='未填写'|htmlentities}</td></tr>
<tr><th>法人手机号</th><td>{$row.company_legal_mobile|default='未填写'|htmlentities}</td><th>技术手机号</th><td>{$row.company_tech_mobile|default='未填写'|htmlentities}</td></tr>
</tbody>
</table>
</div>
</div>
{/if}
<div class="row">
<!-- 常用上门服务地址簿 -->
<div class="col-xs-12 col-sm-6">

查看文件

@@ -1,5 +1,11 @@
<div class="panel panel-default panel-intro">
{:build_heading()}
<div class="panel-heading"><strong>用户列表</strong><p class="text-muted">查看个人用户、商家用户及其独立的师傅身份。</p>
<ul class="nav nav-tabs" data-field="user_type">
<li class="active"><a href="#users-all" data-value="" data-toggle="tab">全部用户</a></li>
<li><a href="#users-personal" data-value="personal" data-toggle="tab">个人用户</a></li>
<li><a href="#users-merchant" data-value="merchant" data-toggle="tab">商家用户</a></li>
</ul>
</div>
<div class="panel-body">
<div id="myTabContent" class="tab-content">

查看文件

@@ -43,6 +43,9 @@ class Auth extends Base
if (!$user) {
// 若数据库中无此手机号:直连数据库插入注册新会员
if (!preg_match('/^\S{6,30}$/', $password)) {
$this->error('登录密码须为6至30位非空字符');
}
$ret = $this->auth->register($mobile, $password, '', $mobile, []);
if (!$ret) {
$this->error($this->auth->getError() ?: '注册登录失败');
@@ -54,9 +57,10 @@ class Auth extends Base
if (empty($user['password'])) {
$this->error('该账号尚未设置登录密码,请使用微信一键登录后设置密码');
}
$encryptPassword = $this->auth->getEncryptPassword($password, $user['salt']);
if ($user['password'] !== $encryptPassword) {
$this->error('手机号或密码不正确');
try {
\app\common\library\AccountSecurity::verify((int)$user['id'], 'login', $password);
} catch (\Throwable $e) {
$this->error($e->getMessage() === '密码不正确' ? '手机号或密码不正确' : $e->getMessage());
}
$this->auth->direct($user['id']);
}
@@ -83,7 +87,7 @@ class Auth extends Base
protected function profileData()
{
$uid = $this->uid();
$user = Db::name('user')->field('id,nickname,mobile,email,avatar,money,score,user_type,contact_address,createtime')->where('id', $uid)->find();
$user = Db::name('user')->field('id,nickname,mobile,email,avatar,money,score,user_type,identity_selected,company_name,company_legal_person,company_legal_mobile,company_tech_mobile,contact_address,createtime')->where('id', $uid)->find();
$master = Db::name('master')->where('user_id', $uid)->find();
$couponCount = Db::name('user_coupon')->where('user_id', $uid)->where('status', 'unused')->count();
@@ -152,13 +156,7 @@ class Auth extends Base
'pending_verify' => $getCnt(7),
];
if ($merchantRole === 'member' && $merchant && $merchant['verify_status'] === 'pass') {
$userType = 'merchant';
} elseif (!empty($user['user_type']) && in_array($user['user_type'], ['personal', 'merchant'], true)) {
$userType = $user['user_type'];
} else {
$userType = ($merchant && $merchant['verify_status'] === 'pass') ? 'merchant' : 'personal';
}
$userType = in_array($user['user_type'], ['personal', 'merchant'], true) ? $user['user_type'] : 'personal';
return [
'id' => (int)$user['id'],
@@ -167,10 +165,11 @@ class Auth extends Base
'email' => !empty($user['email']) ? (string)$user['email'] : ($merchant && !empty($merchant['email']) ? (string)$merchant['email'] : ''),
'contact_address' => !empty($user['contact_address']) ? (string)$user['contact_address'] : ($merchant ? (string)($merchant['province'] . $merchant['city'] . $merchant['district'] . $merchant['address']) : ''),
'user_type' => $userType,
'company_name' => $merchant ? (string)$merchant['name'] : '',
'legal_person' => $merchant && isset($merchant['legal_person']) ? (string)$merchant['legal_person'] : '',
'legal_mobile' => $merchant && isset($merchant['legal_mobile']) ? (string)$merchant['legal_mobile'] : '',
'tech_mobile' => $merchant && isset($merchant['tech_mobile']) ? (string)$merchant['tech_mobile'] : '',
'identity_selected' => (bool)$user['identity_selected'],
'company_name' => $user['company_name'] !== '' ? $user['company_name'] : ($merchant ? (string)$merchant['name'] : ''),
'legal_person' => $user['company_legal_person'] !== '' ? $user['company_legal_person'] : ($merchant ? (string)($merchant['legal_person'] ?? '') : ''),
'legal_mobile' => $user['company_legal_mobile'] !== '' ? $user['company_legal_mobile'] : ($merchant ? (string)($merchant['legal_mobile'] ?? '') : ''),
'tech_mobile' => $user['company_tech_mobile'] !== '' ? $user['company_tech_mobile'] : ($merchant ? (string)($merchant['tech_mobile'] ?? '') : ''),
'avatar' => !empty($user['avatar']) ? (strpos((string)$user['avatar'], 'http') === 0 ? $user['avatar'] : cdnurl($user['avatar'], true)) : '',
'balance' => (float)$user['money'],
'coupon_count' => (int)$couponCount,
@@ -190,10 +189,14 @@ class Auth extends Base
public function saveAccount()
{
$uid = $this->uid();
$currentUserType = Db::name('user')->where('id', $uid)->value('user_type');
$userType = trim((string)$this->request->post('user_type', $currentUserType ?: 'personal'));
if (!in_array($userType, ['personal', 'merchant'], true)) {
$userType = 'personal';
$currentUser = Db::name('user')->where('id', $uid)->find();
$userType = (string)$currentUser['user_type'];
$requestedType = $this->request->post('user_type', null);
if ($requestedType !== null && $requestedType !== $userType) {
$this->error('用户类型确定后不可自行修改');
}
if (empty($currentUser['identity_selected'])) {
$this->error('请先选择用户类型');
}
$nickname = trim((string)$this->request->post('nickname', ''));
$mobile = trim((string)$this->request->post('mobile', ''));
@@ -221,19 +224,18 @@ class Auth extends Base
}
$merchantRel = $this->merchantOf($uid);
if ($userType === 'merchant') {
if (!$merchantRel || ($merchantRel['merchant']['verify_status'] ?? '') !== 'pass') {
$this->error('请先提交企业入驻申请并通过审核后再启用商家账号');
}
}
$userUpdate = [
'nickname' => $nickname,
'user_type' => $userType,
'contact_address' => $contactAddress,
'email' => $email,
'updatetime' => time(),
];
if ($userType === 'merchant') {
foreach (['company_name' => $companyName, 'company_legal_person' => $legalPerson, 'company_legal_mobile' => $legalMobile, 'company_tech_mobile' => $techMobile] as $field => $value) {
$requestField = ['company_name' => 'company_name', 'company_legal_person' => 'legal_person', 'company_legal_mobile' => 'legal_mobile', 'company_tech_mobile' => 'tech_mobile'][$field];
if ($this->request->has($requestField, 'post')) $userUpdate[$field] = $value;
}
}
if ($mobile !== '' && preg_match('/^1\d{10}$/', $mobile)) {
$conflict = Db::name('user')->where('mobile', $mobile)->where('id', '<>', $uid)->find();
if ($conflict) {
@@ -268,6 +270,22 @@ class Auth extends Base
$this->success('保存成功', ['userinfo' => $this->profileData()]);
}
/** 首次登录选择用户类型,原子更新防止重复选择。 */
public function selectIdentity()
{
$type = trim((string)$this->request->post('user_type', ''));
if (!in_array($type, ['personal', 'merchant'], true)) {
$this->error('请选择个人用户或商家用户');
}
$updated = Db::name('user')->where('id', $this->uid())->where('identity_selected', 0)->update([
'user_type' => $type, 'identity_selected' => 1, 'updatetime' => time(),
]);
if (!$updated) {
$this->error('用户类型确定后不可自行修改');
}
$this->success('选择成功', ['userinfo' => $this->profileData()]);
}
/**
* 微信授权登录(小程序 uni.login 拿到的 code)
* @ApiMethod (POST)

查看文件

@@ -35,6 +35,16 @@ class Base extends Api
return (int)$this->auth->id;
}
/** Verify the account payment password before any balance debit. */
protected function requirePaymentPassword()
{
try {
\app\common\library\AccountSecurity::verify($this->uid(), 'payment', (string)$this->request->post('payment_password', ''));
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
/** 验证新头像属于当前账号,且是符合限制的图片附件。 */
protected function validateAvatar($url)
{

查看文件

@@ -6,6 +6,7 @@ use app\common\library\CommissionService;
use app\common\library\FinanceConfigService;
use app\common\library\FinishImageUrls;
use app\common\library\OrderStatus;
use app\common\library\OrderQualification;
use app\common\library\PaymentService;
use app\common\library\TiandituService;
use app\common\library\TencentVerifyService;
@@ -750,7 +751,10 @@ class Master extends Base
}
$now = time();
$qualificationCerts = OrderQualification::certificates((int)$master['id']);
$qualificationToday = date('Y-m-d');
foreach ($list as &$row) {
$row['qualification_allowed'] = OrderQualification::allows($row['qual_req'], $qualificationCerts, $qualificationToday);
unset($row['verify_code'], $row['_has_coord'], $row['_dist_km'], $row['_same_city']);
$row['appoint_text'] = $row['appoint_time'] ? date('Y-m-d H:i', (int)$row['appoint_time']) : '接单后与业主预约';
$row['pay_amount'] = (float)$row['pay_amount'];
@@ -897,6 +901,9 @@ class Master extends Base
if ((int)$order['status'] !== OrderStatus::PENDING_ACCEPT || (int)$order['master_id'] !== 0) {
$this->error('手慢了,该订单已被接走');
}
if (!OrderQualification::forMaster($order['qual_req'] ?? '', (int)$master['id'])) {
$this->error('该订单要求持有已审核通过且有效的「' . $order['qual_req'] . '」,请先上传认证证书');
}
$affected = Db::name('order')
->where('id', $orderId)
@@ -1320,6 +1327,9 @@ class Master extends Base
if ((int)$order['master_id'] > 0) {
$this->error('该订单已选定师傅');
}
if (!OrderQualification::forMaster($order['qual_req'] ?? '', (int)$master['id'])) {
$this->error('该订单要求持有已审核通过且有效的「' . $order['qual_req'] . '」,请先上传认证证书');
}
if ($amount <= 0) {
$this->error('请填写报价金额');
}
@@ -1354,6 +1364,7 @@ class Master extends Base
public function withdraw()
{
$master = $this->requireMaster();
$this->requirePaymentPassword();
$amount = round((float)$this->request->post('amount'), 2);
$wxCode = trim((string)$this->request->post('wx_code', ''));
$channel = trim((string)$this->request->post('channel', 'wechat'));
@@ -2331,6 +2342,7 @@ class Master extends Base
$estCommission = $estCalc['commission'];
$estMasterFee = $estCalc['settle_amount'];
$qualificationAllowed = OrderQualification::forMaster($order['qual_req'] ?? '', $masterId);
$data = [
'id' => (int)$order['id'],
'order_no' => $order['order_no'],
@@ -2368,6 +2380,7 @@ class Master extends Base
'express_company' => (string)($order['express_company'] ?? ''),
'goods_arrived' => (int)($order['goods_arrived'] ?? 1),
'qual_req' => (string)($order['qual_req'] ?? ''),
'qualification_allowed' => $qualificationAllowed,
'master_req' => (string)($order['master_req'] ?? ''),
'contact' => $contactDisplay,
'mobile' => $mobile,
@@ -2392,8 +2405,8 @@ class Master extends Base
'description' => $myQuote['description'],
'status' => $myQuote['status'],
] : null,
'can_grab' => ($order['price_type'] !== 'quote' && (int)$order['status'] === OrderStatus::PENDING_ACCEPT && (int)$order['master_id'] === 0 && (int)$order['user_id'] !== $this->uid()),
'can_quote' => ($order['price_type'] === 'quote' && in_array((int)$order['status'], [OrderStatus::PENDING_ACCEPT, OrderStatus::QUOTING], true) && (int)$order['master_id'] === 0 && !$myQuote && (int)$order['user_id'] !== $this->uid()),
'can_grab' => ($qualificationAllowed && $order['price_type'] !== 'quote' && (int)$order['status'] === OrderStatus::PENDING_ACCEPT && (int)$order['master_id'] === 0 && (int)$order['user_id'] !== $this->uid()),
'can_quote' => ($qualificationAllowed && $order['price_type'] === 'quote' && in_array((int)$order['status'], [OrderStatus::PENDING_ACCEPT, OrderStatus::QUOTING], true) && (int)$order['master_id'] === 0 && !$myQuote && (int)$order['user_id'] !== $this->uid()),
];
// 本人已接工单:附带完整履约节点、增项补差、完工取证、结算入账与操作轨迹
@@ -2943,7 +2956,7 @@ class Master extends Base
}
$this->success('', [
'notice' => '请上传本人真实的技能证书信息。技能证书审核通过后,才能接商家指定资质要求的订单。',
'notice' => '请上传本人真实的技能证书信息。审核通过且在有效期内的证书名称会展示给相关订单用户。',
'is_master_applied' => $master ? 1 : 0,
'verify_status' => $master ? (string)$master['verify_status'] : '',
'items' => $items,

查看文件

@@ -591,53 +591,12 @@ class Merchant extends Base
}
}
/**
* 要求已通过审核的商家
* 若当前用户为 merchant 类型但无 merchant 档案,则自动创建一条空档案兜底
* 同一 user_id 只能创建一条(user_id 唯一约束已由后台 add() 保证)
*/
/** 要求商家档案已通过审核;账号类型不代表企业资质。 */
protected function requireMerchant()
{
$m = $this->merchantInfo();
if (!$m) {
$curUser = Db::name('user')->where('id', $this->uid())->find();
if ($curUser && !empty($curUser['user_type']) && $curUser['user_type'] === 'merchant') {
// 再次确认:user_id 必须唯一,防止并发创建重复记录
$existCheck = Db::name('merchant')->where('user_id', $this->uid())->find();
if ($existCheck) {
if ($existCheck['verify_status'] !== 'pass') {
Db::name('merchant')->where('id', (int)$existCheck['id'])->update([
'verify_status' => 'pass',
'updatetime' => time(),
]);
$existCheck['verify_status'] = 'pass';
}
return $existCheck;
}
$now = time();
$newId = Db::name('merchant')->insertGetId([
'user_id' => $this->uid(),
'name' => !empty($curUser['nickname']) ? (string)$curUser['nickname'] : '商家用户',
'license_no' => null,
'contact' => (string)$curUser['nickname'],
'mobile' => (string)$curUser['mobile'],
'address' => isset($curUser['contact_address']) ? (string)$curUser['contact_address'] : '',
'email' => isset($curUser['email']) ? (string)$curUser['email'] : '',
'verify_status' => 'pass',
'createtime' => $now,
'updatetime' => $now,
]);
return Db::name('merchant')->where('id', $newId)->find();
}
$this->error('请先在「账号信息」切换为商家类型', null, 2001);
}
if ($m['verify_status'] !== 'pass') {
Db::name('merchant')->where('id', (int)$m['id'])->update([
'verify_status' => 'pass',
'updatetime' => time(),
]);
$m['verify_status'] = 'pass';
if (!$m || $m['verify_status'] !== 'pass') {
$this->error('请先完成商家资质审核', null, 2001);
}
return $m;
}

查看文件

@@ -7,6 +7,7 @@ use app\common\library\FinanceConfigService;
use app\common\library\OrderStatus;
use app\common\library\OrderServiceSnapshot;
use app\common\library\OrderPaymentResultService;
use app\common\library\MasterOrderCredentials;
use app\common\library\PaymentService;
use app\common\library\TiandituService;
use think\Db;
@@ -640,6 +641,7 @@ class Order extends Base
try {
if ($payType === 'balance') {
$this->requirePaymentPassword();
$res = PaymentService::payOrderByBalance($order, $this->uid(), 'order');
} else {
$res = PaymentService::createOrderJsapiPay($order, $this->uid(), 'order', 0, $wxCode);
@@ -725,6 +727,7 @@ class Order extends Base
try {
if ($payType === 'balance') {
$this->requirePaymentPassword();
$res = PaymentService::payOrderByBalance($order, $this->uid(), 'diff');
} else {
$res = PaymentService::createOrderJsapiPay($order, $this->uid(), 'diff', 0, $wxCode);
@@ -1035,6 +1038,23 @@ class Order extends Base
}
}
// 一次性读取订单关联师傅的公开技能与有效证书,避免报价列表逐人查询。
$credentialMasterIds = array_column($quotes, 'master_id');
if ($master) $credentialMasterIds[] = $master['id'];
$credentialMasterIds = array_values(array_unique(array_filter(array_map('intval', $credentialMasterIds))));
if ($credentialMasterIds) {
$skillRows = Db::name('master_skill')->field('master_id,skill_name,status')
->where('master_id', 'in', $credentialMasterIds)->where('status', 'normal')->select();
$certRows = Db::name('master_cert')->field('master_id,cert_name,status,is_long_term,expire_date')
->where('master_id', 'in', $credentialMasterIds)->where('status', 'pass')->select();
$credentials = MasterOrderCredentials::project($credentialMasterIds, $skillRows, $certRows, date('Y-m-d'));
if ($master) $master = array_merge($master, $credentials[$master['id']]);
foreach ($quotes as &$quote) {
if (isset($credentials[$quote['master_id']])) $quote = array_merge($quote, $credentials[$quote['master_id']]);
}
unset($quote);
}
$creatorUser = Db::name('user')->where('id', (int)$order['user_id'])->find();
$rawCreatorMobile = (string)(($creatorUser && !empty($creatorUser['mobile'])) ? $creatorUser['mobile'] : $order['mobile']);
$maskedCreatorMobile = strlen($rawCreatorMobile) >= 7 ? substr_replace($rawCreatorMobile, '****', 3, 4) : $rawCreatorMobile;
@@ -1224,8 +1244,14 @@ class Order extends Base
$payType = trim((string)$this->request->post('pay_type', 'wechat'));
$order = $this->ownOrder($orderId, 'user');
$quoteMasterId = (int)Db::name('order_quote')->where('id', $quoteId)->where('order_id', $orderId)->value('master_id');
if ($quoteMasterId > 0 && !\app\common\library\OrderQualification::forMaster($order['qual_req'] ?? '', $quoteMasterId)) {
$this->error('该师傅目前没有符合订单要求的有效认证证书,请选择其他师傅');
}
try {
if ($payType === 'balance') {
$this->requirePaymentPassword();
$res = PaymentService::payOrderByBalance($order, $this->uid(), 'quote', $quoteId);
} else {
$res = PaymentService::createOrderJsapiPay($order, $this->uid(), 'quote', $quoteId, $wxCode);

查看文件

@@ -0,0 +1,133 @@
<?php
namespace app\api\controller;
use app\common\library\AccountSecurity;
use app\common\library\WxLogin;
use app\common\library\TencentVerifyService;
use app\common\library\EnterpriseLicenseImage;
use think\Db;
class Security extends Base
{
private function verifyBoundPhone($code, $mobile)
{
if (trim((string)$code) === '') $this->error('请先验证绑定的微信手机号');
$phone = WxLogin::getPhoneNumber((string)$code);
$verified = isset($phone['purePhoneNumber']) ? (string)$phone['purePhoneNumber'] : (string)($phone['phoneNumber'] ?? '');
if (isset($phone['error']) || $verified === '' || !hash_equals((string)$mobile, $verified)) {
$this->error('手机号验证失败,请使用绑定手机号重新验证');
}
}
public function status()
{
$user = Db::name('user')->field('password,mobile')->where('id', $this->uid())->find();
$security = Db::name('user_security')->where('user_id', $this->uid())->find();
$cert = Db::name('user_enterprise_cert')->where('user_id', $this->uid())->find();
$this->success('', [
'has_login_password' => !empty($user['password']),
'has_payment_password' => $security && $security['payment_password_hash'] !== '',
'enterprise_cert' => $cert ?: null,
]);
}
public function changeLoginPassword()
{
$uid = $this->uid();
$new = (string)$this->request->post('new_password', '');
$old = (string)$this->request->post('old_password', '');
if (!preg_match('/^\S{6,30}$/', $new)) $this->error('登录密码须为6至30位非空字符');
$user = Db::name('user')->field('password,mobile')->where('id', $uid)->find();
if (!empty($user['password'])) {
try { AccountSecurity::verify($uid, 'login', $old); } catch (\Throwable $e) { $this->error($e->getMessage()); }
$ignoreOld = false;
} else {
$this->verifyBoundPhone($this->request->post('phone_code', ''), $user['mobile']);
$ignoreOld = true;
}
if (!$this->auth->changepwd($new, $old, $ignoreOld)) $this->error($this->auth->getError() ?: '设置失败');
\app\common\library\Token::clear($uid);
$this->success('登录密码已更新,请重新登录');
}
public function setPaymentPassword()
{
$uid = $this->uid();
$new = (string)$this->request->post('new_password', '');
if (!preg_match('/^\d{6}$/', $new)) $this->error('支付密码须为6位数字');
try { AccountSecurity::verify($uid, 'login', (string)$this->request->post('login_password', '')); }
catch (\Throwable $e) { $this->error($e->getMessage()); }
$updated = Db::name('user_security')->where('user_id', $uid)->where('payment_password_hash', '')->update(['payment_password_hash' => password_hash($new, PASSWORD_DEFAULT)]);
if (!$updated) $this->error('支付密码已设置,请使用修改功能');
$this->success('支付密码设置成功');
}
public function changePaymentPassword()
{
$uid = $this->uid();
$new = (string)$this->request->post('new_password', '');
if (!preg_match('/^\d{6}$/', $new)) $this->error('支付密码须为6位数字');
$oldHash = (string)Db::name('user_security')->where('user_id', $uid)->value('payment_password_hash');
try { AccountSecurity::verify($uid, 'payment', (string)$this->request->post('old_password', '')); }
catch (\Throwable $e) { $this->error($e->getMessage()); }
$updated = Db::name('user_security')->where('user_id', $uid)->where('payment_password_hash', $oldHash)->update(['payment_password_hash' => password_hash($new, PASSWORD_DEFAULT)]);
if (!$updated) $this->error('支付密码已变更,请重新操作');
$this->success('支付密码修改成功');
}
public function submitEnterpriseCert()
{
$uid = $this->uid();
$name = trim((string)$this->request->post('company_name', ''));
$license = strtoupper(trim((string)$this->request->post('license_no', '')));
$image = trim((string)$this->request->post('license_image', ''));
$person = trim((string)$this->request->post('legal_person', ''));
if ($name === '' || mb_strlen($name) > 255) $this->error('请填写企业名称');
if (!preg_match('/^[A-Z0-9]{15,18}$/', $license)) $this->error('请填写正确的营业执照号码');
if (mb_strlen($person) > 100) $this->error('法人姓名过长');
$attachment = Db::name('attachment')->where('user_id', $uid)->where('url', $image)->where('category', 'cert')->find();
if (!$attachment || (int)$attachment['filesize'] > 10 * 1024 * 1024 || !in_array(strtolower((string)$attachment['mimetype']), ['image/jpeg', 'image/png', 'image/webp'], true)) {
$this->error('请上传本人营业执照图片');
}
$existing = Db::name('user_enterprise_cert')->where('user_id', $uid)->find();
$data = ['company_name' => $name, 'license_no' => $license, 'license_image' => $image,
'legal_person' => $person, 'verify_status' => 'pending', 'audit_msg' => '', 'updatetime' => time()];
if ($existing) {
if ($existing['verify_status'] !== 'reject') $this->error('已有企业资质申请,审核中或已通过');
$updated = Db::name('user_enterprise_cert')->where('id', (int)$existing['id'])->where('verify_status', 'reject')->update($data);
if (!$updated) $this->error('申请状态已变更,请刷新后重试');
} else {
$data['user_id'] = $uid;
$data['createtime'] = time();
try { Db::name('user_enterprise_cert')->insert($data); }
catch (\Throwable $e) { $this->error('提交失败,请刷新后重试'); }
}
$this->success('企业资质已提交,请等待审核');
}
public function recognizeEnterpriseLicense()
{
$image = trim((string)$this->request->post('license_image', ''));
$attachment = Db::name('attachment')->where('user_id', $this->uid())->where('url', $image)->where('category', 'cert')->find();
if (!$attachment || (int)$attachment['filesize'] > 10 * 1024 * 1024 || !in_array(strtolower((string)$attachment['mimetype']), ['image/jpeg', 'image/png', 'image/webp'], true)) {
$this->error('请上传本人营业执照图片');
}
try {
$imageBytes = EnterpriseLicenseImage::read($attachment);
} catch (\Throwable $e) {
$this->error('图片读取失败,请重新上传或手动填写');
}
try {
$reply = TencentVerifyService::request('ocr', '2018-11-19', 'BizLicenseOCR', ['ImageBase64' => base64_encode($imageBytes)]);
$data = $reply['Response'] ?? [];
if (!empty($data['Error']) || empty($data['Name']) || empty($data['RegNum'])) {
$this->error('未能识别营业执照,请重新上传或手动填写');
}
$this->success('识别成功,请核对信息', ['company_name' => (string)$data['Name'], 'license_no' => (string)$data['RegNum'], 'legal_person' => (string)($data['Person'] ?? '')]);
} catch (\think\exception\HttpResponseException $e) {
throw $e;
} catch (\Throwable $e) {
$this->error('营业执照识别暂不可用,请手动填写');
}
}
}

查看文件

@@ -212,52 +212,10 @@ class User extends Api
$this->error(__('Operation failed'), $url);
}
/**
* 重置密码
*
* @ApiMethod (POST)
* @ApiParams (name="mobile", type="string", required=true, description="手机号")
* @ApiParams (name="newpassword", type="string", required=true, description="新密码")
* @ApiParams (name="captcha", type="string", required=true, description="验证码")
*/
/** 密码找回暂不开放,保留旧路由返回明确提示。 */
public function resetpwd()
{
$type = $this->request->post("type", "mobile");
$mobile = $this->request->post("mobile");
$email = $this->request->post("email");
$newpassword = $this->request->post("newpassword");
$captcha = $this->request->post("captcha");
if (!$newpassword || !$captcha) {
$this->error(__('Invalid parameters'));
}
//验证Token
if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
$this->error(__('Password must be 6 to 30 characters'));
}
if ($type == 'mobile') {
$this->error('短信验证码通道已移除,暂不支持手机短信找回密码');
} else {
if (!Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));
}
$user = \app\common\model\User::getByEmail($email);
if (!$user) {
$this->error(__('User not found'));
}
$ret = Ems::check($email, $captcha, 'resetpwd', true);
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
Ems::flush($email, 'resetpwd');
}
//模拟一次登录
$this->auth->direct($user->id);
$ret = $this->auth->changepwd($newpassword, '', true);
if ($ret) {
$this->success(__('Reset password successful'));
} else {
$this->error($this->auth->getError());
}
$this->error('暂不支持找回密码');
}
/**

查看文件

@@ -0,0 +1,56 @@
<?php
namespace app\common\library;
use think\Db;
/** Shared account credential verification and per-account throttling. */
class AccountSecurity
{
public static function ensure($uid)
{
$prefix = config('database.prefix');
if (!preg_match('/^[A-Za-z0-9_]+$/', $prefix)) {
throw new \RuntimeException('数据库配置错误');
}
Db::execute("INSERT IGNORE INTO `{$prefix}user_security` (`user_id`) VALUES (?)", [(int)$uid]);
}
public static function verify($uid, $kind, $password)
{
if (!in_array($kind, ['login', 'payment'], true)) {
throw new \InvalidArgumentException('验证类型错误');
}
$attemptsField = $kind === 'payment' ? 'payment_failed_attempts' : 'failed_attempts';
$lockedField = $kind === 'payment' ? 'payment_locked_until' : 'locked_until';
self::ensure($uid);
Db::startTrans();
try {
$row = Db::name('user_security')->where('user_id', (int)$uid)->lock(true)->find();
if ((int)$row[$lockedField] > time()) {
throw new \RuntimeException('密码错误次数过多,请15分钟后重试');
}
if ($kind === 'login') {
$user = Db::name('user')->field('password,salt')->where('id', (int)$uid)->find();
$correct = $user && $user['password'] !== '' && hash_equals((string)$user['password'], md5(md5($password) . $user['salt']));
} elseif ($kind === 'payment') {
if ($row['payment_password_hash'] === '') {
throw new \RuntimeException('请先在账号安全中设置支付密码');
}
$correct = password_verify($password, $row['payment_password_hash']);
}
$failures = $correct ? 0 : (int)$row[$attemptsField] + 1;
Db::name('user_security')->where('user_id', (int)$uid)->update([
$attemptsField => $failures >= 5 ? 0 : $failures,
$lockedField => $failures >= 5 ? time() + 900 : 0,
]);
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
if (!$correct) {
throw new \RuntimeException($failures >= 5 ? '密码错误次数过多,请15分钟后重试' : '密码不正确');
}
return true;
}
}

查看文件

@@ -221,14 +221,10 @@ class Auth
return false;
}
if ($user->loginfailure >= 10 && time() - $user->loginfailuretime < 86400) {
$this->setError('Please try again after 1 day');
return false;
}
if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
$user->save(['loginfailure' => $user->loginfailure + 1, 'loginfailuretime' => time()]);
$this->setError('Password is incorrect');
try {
AccountSecurity::verify((int)$user->id, 'login', $password);
} catch (\RuntimeException $e) {
$this->setError($e->getMessage() === '密码不正确' ? 'Password is incorrect' : $e->getMessage());
return false;
}

查看文件

@@ -0,0 +1,44 @@
<?php
namespace app\common\library;
use think\Loader;
/** Reads an already-authorized attachment without accepting a caller-supplied remote URL. */
class EnterpriseLicenseImage
{
public static function read(array $attachment)
{
$url = (string)($attachment['url'] ?? '');
$size = (int)($attachment['filesize'] ?? 0);
if ($url === '' || $url[0] !== '/' || $size <= 0 || $size > 10 * 1024 * 1024) {
throw new \RuntimeException('营业执照图片无效');
}
if (($attachment['storage'] ?? '') === 'cos') {
$config = get_addon_config('cos');
if (!$config || empty($config['bucket']) || empty($config['region']) || empty($config['secretId']) || empty($config['secretKey'])) {
throw new \RuntimeException('云存储未配置');
}
Loader::addNamespace('Qcloud\\Cos', ROOT_PATH . 'addons/cos/library/Qcloud/Cos/');
$client = new \Qcloud\Cos\Client([
'region' => $config['region'], 'schema' => 'https',
'credentials' => ['secretId' => $config['secretId'], 'secretKey' => $config['secretKey']],
]);
$result = $client->getObject(['Bucket' => $config['bucket'], 'Key' => ltrim($url, '/'), 'Range' => 'bytes=0-10485760']);
$bytes = (string)$result['Body'];
} elseif (($attachment['storage'] ?? '') === 'local') {
$root = realpath(ROOT_PATH . 'public');
$file = realpath(ROOT_PATH . 'public' . $url);
if (!$root || !$file || strpos($file, $root . DIRECTORY_SEPARATOR) !== 0 || !is_file($file) || !is_readable($file)) {
throw new \RuntimeException('营业执照图片不存在');
}
if (filesize($file) > 10 * 1024 * 1024) throw new \RuntimeException('营业执照图片过大');
$bytes = file_get_contents($file);
} else {
throw new \RuntimeException('不支持的图片存储类型');
}
if (!is_string($bytes) || $bytes === '' || strlen($bytes) > 10 * 1024 * 1024) {
throw new \RuntimeException('营业执照图片读取失败');
}
return $bytes;
}
}

查看文件

@@ -0,0 +1,29 @@
<?php
namespace app\common\library;
class MasterOrderCredentials
{
public static function project(array $masterIds, array $skills, array $certificates, $today)
{
$result = [];
foreach ($masterIds as $id) {
if ((int)$id > 0) $result[(int)$id] = ['skills' => [], 'certificates' => []];
}
foreach ($skills as $row) {
$id = (int)$row['master_id'];
$name = trim((string)$row['skill_name']);
if (isset($result[$id]) && $row['status'] === 'normal' && $name !== '' && !in_array($name, $result[$id]['skills'], true)) {
$result[$id]['skills'][] = $name;
}
}
foreach ($certificates as $row) {
$id = (int)$row['master_id'];
$name = trim((string)$row['cert_name']);
$valid = (int)$row['is_long_term'] === 1 || (!empty($row['expire_date']) && $row['expire_date'] >= $today);
if (isset($result[$id]) && $row['status'] === 'pass' && $valid && $name !== '' && !in_array($name, $result[$id]['certificates'], true)) {
$result[$id]['certificates'][] = $name;
}
}
return $result;
}
}

查看文件

@@ -0,0 +1,31 @@
<?php
namespace app\common\library;
use think\Db;
class OrderQualification
{
public static function certificates($masterId)
{
return Db::name('master_cert')->field('cert_name,cert_code,is_custom,status,is_long_term,expire_date')
->where('master_id', (int)$masterId)->where('status', 'pass')->select();
}
public static function allows($requirement, array $certificates, $today)
{
$requirement = trim((string)$requirement);
if ($requirement === '') return true;
foreach ($certificates as $cert) {
if ((string)$cert['status'] !== 'pass' || (int)$cert['is_custom'] !== 0 || (string)$cert['cert_code'] === 'other') continue;
if (trim((string)$cert['cert_name']) !== $requirement) continue;
if ((int)$cert['is_long_term'] === 1 || (!empty($cert['expire_date']) && $cert['expire_date'] >= $today)) return true;
}
return false;
}
public static function forMaster($requirement, $masterId)
{
if (trim((string)$requirement) === '') return true;
return self::allows($requirement, self::certificates($masterId), date('Y-m-d'));
}
}