更新:小程序登录认证接口

master
zwesy 2021-11-24 16:19:54 +08:00
parent 23e783b6ab
commit a361afb3f0
8 changed files with 67 additions and 180 deletions

View File

@ -673,4 +673,14 @@ if(!function_exists("formatBlankTime")){
($minute>0?$minute."分钟":'').
($second>0?$second."":'');
}
}
/**
* 生成用户默认昵称
*/
if (!function_exists('generateDefaultNickName')) {
function generateDefaultNickName()
{
return '用户'.generateRand('6', 'mix');
}
}

View File

@ -16,6 +16,7 @@ class User extends Base
{
protected $noNeedLogin = [
'login',
'test',
];
/**
@ -26,7 +27,12 @@ class User extends Base
*/
public function login(): Json
{
$params = $this->request->param();
$params = [
'code' => $this->request->param('code', ''),
'nick_name' => $this->request->param('nickName', ''),
'avatar_url' => $this->request->param('avatarUrl', ''),
'gender' => $this->request->param('gender', 0),
];
$validate = new UserValidate();
if (!$validate->scene('wx_applets')->check($params)) {
@ -43,155 +49,46 @@ class User extends Base
// 有效期2小时
$wxUser['expire_time'] = time() + 7200;
$wxUser['session_key'] = $wxUser['session_key'] ?? '';
$openID = $wxUser['openid'];
$openID = $wxUser['openid'] ?? '';
if (empty($openID)) {
return $this->json(4002, '登录失败');
}
$isActive = $params['is_active'] ?? 0;
$isActive = (is_numeric($isActive) && $isActive > 0) ? AccountRepository::BOOL_TRUE : AccountRepository::BOOL_FALSE;
$phoneActive = $params['phone_active'] ?? 0;
$phoneActive = (is_numeric($phoneActive) && $phoneActive > 0) ? AccountRepository::BOOL_TRUE : AccountRepository::BOOL_FALSE;
try {
$repo = AccountRepository::getInstance();
$account = $repo->findByOpenID($openID);
$inviteCode = $params['invite_code'] ?? '';
$inviteSource = $params['invite_source'] ?? AccountRepository::INVITE_SOURCE_DEF;
$channel = $params['channel'] ?? '';
$repo = AccountRepository::getInstance();
$account = $repo->findByOpenID($openID);
$nowDate = date('Y-m-d H:i:s');
if (!$account) {
// 自动注册
$inviterAid = 0;
$inviterParentAid = 0;
$inviter = null;
$customerService = 0;// 所属客服
if (!empty($inviteCode)) {
$inviter = $repo->findByInviteCode($inviteCode);
if ($inviter) {
$inviterAid = $inviter['id'];
$inviterParentAid = $inviter['inviter_account_id'];
$channel = (empty($channel) && $inviter['is_staff'] > 0) ? AccountRepository::CHANNEL_MEMBER : AccountRepository::CHANNEL_CUSTOMER;
if ($inviter['is_staff'] > 0) {
//若分享人是员工 自动绑定为客服
$customerService = $inviter['id'];
}
}
}
// 活码进入 绑定客服
if (isset($params['source_code']) && !empty($params['source_code'])) {
if ($sourceUser = Activity::findOne(['code' => $params['source_code']])) {
$customerService = $sourceUser['account_id'] ?? 0;
}
}
$inviteSource = in_array($inviteSource, array_keys(AccountRepository::inviteSourceList())) ? $inviteSource : AccountRepository::INVITE_SOURCE_DEF;
$channelList = $repo->channelList();
$channel = (empty($channel) || !in_array($channel, array_keys($channelList))) ? AccountRepository::CHANNEL_NORMAL : $channel;
$account = $repo->create([
'unionid' => $wxUser['unionid'] ?? '',
'openid' => $openID,
'last_login' => date('Y-m-d H:i:s'),
'login_ip' => $this->request->ip(),
'created_at' => date('Y-m-d H:i:s'),
'created_year' => date('Y'),
'created_month' => date('n'),
'created_day' => date('j'),
'nickname' => $params['nickname'] ?? '',
'headimgurl' => $params['headimgurl'] ?? '',
'country' => $params['country'] ?? '',
'province' => $params['province'] ?? '',
'city' => $params['city'] ?? '',
'county' => $params['county'] ?? '',
'gender' => $params['gender'] ?? 0,
'language' => $params['language'] ?? 'zh_CN',
'mobile' => $params['mobile'] ?? '',
'status' => AccountRepository::STATUS_NORMAL,
'invite_source' => $inviteSource,
'inviter_account_id' => $inviterAid,
'inviter_parent_id' => $inviterParentAid,
'channel' => $channel,
'is_staff' => AccountRepository::BOOL_FALSE,
'is_active' => $isActive,
'phone_active' => $phoneActive,
'customer_service' => $customerService,
'source_code' => $params['source_code'] ?? '',
'session_key' => $wxUser['session_key'] ?? '',
'user_code' => createUuid(), // 用户UUID
'open_id' => $openID,
'create_time' => $nowDate,
'login_time' => $nowDate,
'type' => Account::type_consumer, // 默认为普通消费者
'state' => Account::state_default,
'nick_name' => $params['nick_name'] ?: generateDefaultNickName(),
'avatar_url' => $params['avatar_url'] ?: Account::DEFAULT_AVATAR,
'gender' => $params['gender'],
]);
// 存在所属客服 添加绑定记录
if ($customerService > 0) {
CustomerReceive::firstBoundService($account['id'], $customerService);
}
$regAccountId = $account->id ?? 0;
$accountActive = $phoneActive > 0;
if ($inviter) {
$repo->addShareRegLog($regAccountId, $inviter['id'], AccountRepository::SHARE_GRADE_FIRST, $accountActive);
if ($inviterParentAid > 0) {
$repo->addShareRegLog($regAccountId, $inviterParentAid, AccountRepository::SHARE_GRADE_SECOND, $accountActive);
}
// 邀请人绑定的客服可获得积分, 有效用户才关联
if ($accountActive) {
$boundServiceAid = $repo->getBoundServiceAId($inviter['id']);
if ($boundServiceAid > 0) {
$repo->addShareRegLog($regAccountId, $boundServiceAid, AccountRepository::SHARE_GRADE_SERVICE, true);
}
}
}
AccountRecord::record($regAccountId, AccountRecord::TYPE_OTHER, AccountRecord::ACTION_REGISTER);
} else {
$updateData = [
'last_login' => date('Y-m-d H:i:s'),
'login_ip' => $this->request->ip(),
'session_key' => $wxUser['session_key'] ?? '',
'language' => $params['language'] ?? 'zh_CN',
'login_time' => $nowDate,
];
$phoneActiveOld = $account['phone_active'];
// 更新资料
$modifyStringList = ['headimgurl', 'nickname', 'mobile', 'country', 'province', 'city', 'county'];
$modifyStringList = ['nick_name', 'avatar_url'];
foreach ($modifyStringList as $modifyKey) {
if (isset($account[$modifyKey]) && empty($account[$modifyKey])) {
$updateData[$modifyKey] = $params[$modifyKey] ?? '';
if (isset($params[$modifyKey]) && !empty($params[$modifyKey])) {
$updateData[$modifyKey] = $params[$modifyKey];
}
}
if (empty($account['gender'])) {
$updateData['gender'] = $params['gender'] ?? 0;
}
if (isset($account['is_active']) && $account['is_active'] == AccountRepository::BOOL_FALSE) {
$updateData['is_active'] = $isActive;
}
if (isset($account['phone_active']) && $account['phone_active'] == AccountRepository::BOOL_FALSE) {
$updateData['phone_active'] = $phoneActive;
}
$repo->update($updateData, ['id' => $account['id']]);
$account = $repo->findById($account['id']);
// 授权手机号后才能算有效激活用户,并更新相关业务数据
if ($phoneActiveOld == AccountRepository::BOOL_FALSE && $account['phone_active'] == AccountRepository::BOOL_TRUE) {
if ($account['inviter_account_id'] > 0) {
$repo->addShareRegLog($account['id'], $account['inviter_account_id'], AccountRepository::SHARE_GRADE_FIRST, true);
// 邀请人绑定的客服可获得积分
$boundServiceAid = $repo->getBoundServiceAId($account['inviter_account_id']);
if ($boundServiceAid > 0) {
$repo->addShareRegLog($account['id'], $boundServiceAid, AccountRepository::SHARE_GRADE_SERVICE, true);
}
}
if ($account['inviter_parent_id'] > 0) {
$repo->addShareRegLog($account['id'], $account['inviter_parent_id'], AccountRepository::SHARE_GRADE_SECOND, true);
}
}
}
} catch (RepositoryException | Exception $e) {
@ -199,31 +96,23 @@ class User extends Base
}
$account = $account->toArray();
$account['avatar_url'] = File::convertCompleteFileUrl($account['avatar_url']);
$jwtData = [
'user_id' => $account['id'],
'open_id' => $openID,
'session_key' => $wxUser['session_key'],
'expire_time' => $wxUser['expire_time'],
'user_id' => $account['id'],
'user_code' => $account['user_code'],
'open_id' => $openID,
'session_key' => $wxUser['session_key'],
'expire_time' => $wxUser['expire_time'],
];
$account['headimgurl'] = File::convertCompleteFileUrl($account['headimgurl']);
$fields = [
'coding', 'real_name', 'nickname', 'headimgurl', 'gender', 'mobile',
'province', 'city', 'county', 'country', 'birthday',
'score', 'status', 'position', 'invite_code', 'channel',
'is_staff', 'is_active', 'phone_active'
];
$accountData = arrayKeysFilter($account, $fields);
$account['is_active'] = ($account['is_active'] == Account::COMMON_ON && $account['phone_active'] == Account::COMMON_ON);
$data = [
'account_id' => $account['id'],
'token' => Jwt::generate($jwtData),
'expire' => $wxUser['expire_time'],
'openid' => $openID,
$data = [
'avatar' => File::convertCompleteFileUrl($account['avatar_url']),
'nickName' => $account['nick_name'],
'token' => Jwt::generate($jwtData),
'userType' => $account['type'],
'userTypeDes' => Account::accountTypeDescList()[$account['type']] ?? '游客',
];
$data = array_merge($data, $accountData);
return $this->json(0, 'success', $data);
}

View File

@ -8,7 +8,8 @@ use think\exception\ValidateException;
class Account extends Base
{
public const type_consumer = 0;//个人消费者
public const type_visitor = -1;//游客
public const type_consumer = 0;//普通用户
public const type_business = 1;//商家
public const type_staff = 2;//员工
@ -17,6 +18,9 @@ class Account extends Base
public const state_fail = 2;// 2拒绝
public const state_success = 3;// 3审核通过
// 默认头像
public const DEFAULT_AVATAR = '/static/images/default-avatar.png';
public static function allState(){
return [
self::state_default=>"未提交",
@ -26,6 +30,16 @@ class Account extends Base
];
}
public static function accountTypeDescList(): array
{
return [
(string) self::type_visitor => '游客',
(string) self::type_consumer => '普通用户',
(string) self::type_business => '商家',
(string) self::type_staff => '员工',
];
}
public function tag()
{
return $this->hasOne(Tag::class,"id","tag_id");

View File

@ -69,7 +69,7 @@ class AccountRepository extends Repository
*/
public function findByOpenID(string $openID)
{
return $this->model->where('openid', $openID)->find();
return $this->model->where('open_id', $openID)->find();
}

View File

@ -23,7 +23,7 @@ class File
* @todo 若启用OOS存储需根据业务配置调整$fileDomain
*
*/
public static function convertCompleteFileUrl(?string $fileUrl, bool $ossAnalysis=true): string
public static function convertCompleteFileUrl(?string $fileUrl, bool $ossAnalysis=false): string
{
if (empty($fileUrl)) {
return '';

View File

@ -7,42 +7,16 @@ use think\Validate;
class User extends Validate
{
protected $rule = [
'username|用户名或手机号' => 'require',
'password|密码' => 'require|min:4|max:16',
'code|小程序code' => 'require',
'nickname|昵称' => 'max:100',
'headimgurl|头像' => 'max:300',
'country|国家' => 'max:100',
'province|省份' => 'max:100',
'city|城市' => 'max:100',
'county|区、县' => 'max:250',
'mobile|手机号' => 'mobile|max:20',
'invite_code|邀请码' => 'max:100',
'channel|来源渠道' => 'max:200',
'birthday|出生年月' => 'date',
'source_code|来源码' => 'max:250',
'nick_name|昵称' => 'max:100',
'avatar_url|头像' => 'max:250',
'gender|性别' => 'number',
'name|姓名' => 'require',
'user_id|用户ID' => 'require|number|gt:0',
'phone|联系方式' => 'require',
'address|详细地址' => 'require',
'province_str|省份' => 'require',
'city_str|城市' => 'require',
'county_str|区、县' => 'require',
];
protected $scene = [
'base' => ['username', 'password'],//普通模式
'wechat' => ['username'],//微信公众号登录
'qq' => ['username'],//qq登录
'address' => [
'user_id', 'name', 'phone', 'province', 'city', 'county', 'address',
'province_str', 'city_str', 'county_str'
],//地址管理
// 微信小程序登录
'wx_applets' => ['code', 'nickname', 'headimgurl', 'country', 'province', 'city', 'mobile', 'invite_code', 'channel', 'source_code'],
// 修改用户信息
'edit' => ['real_name', 'nickname', 'headimgurl', 'mobile', 'gender', 'province', 'city', 'county', 'birthday'],
'wx_applets' => ['code', 'nick_name', 'gender'],
];
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB