On this page
第三方登录api
controller层:application\api\controller\v1\User.php
php
// 第三方登录
public function otherLogin(){
// 验证登录信息
(new UserValidate())->goCheck('otherlogin');
$token = (new UserModel())->otherlogin();
return self::showResCode('登录成功',['token'=>$token]);
}
route层:route\route.php
php
// 不需要验证token
Route::group('api/:version/',function(){
...
// 第三方登录
Route::post('user/otherlogin','api/:version.User/otherLogin');
...
});
validate层:application\common\validate\UserValidate.php
php
// 验证规则
protected $rule = [
...
'provider'=>'require',
'openid'=>'require',
'nickName'=>'require',
'avatarUrl'=>'require',
'expires_in'=>'require',
...
];
// 验证场景
protected $scene = [
...
'otherlogin'=>['provider','openid','nickName','avatarUrl','expires_in'],
...
];
model层:application\common\model\User.php
php
// 绑定第三方登录
public function userbind(){
return $this->hasMany('UserBind');
}
// 判断用户是否存在(在前面课程的基础上扩充)
public function isExist($arr=[]){
if(!is_array($arr)) return false;
if (array_key_exists('phone',$arr)) { // 手机号码
return $this->where('phone',$arr['phone'])->find();
}
// 用户id
if (array_key_exists('id',$arr)) { // 用户名
return $this->where('id',$arr['id'])->find();
}
if (array_key_exists('email',$arr)) { // 邮箱
return $this->where('email',$arr['email'])->find();
}
if (array_key_exists('username',$arr)) { // 用户名
return $this->where('username',$arr['username'])->find();
}
// 第三方参数
if (array_key_exists('provider',$arr)) {
$where = [
'type'=>$arr['provider'],
'openid'=>$arr['openid']
];
return $this->userbind()->where($where)->find();
}
return false;
}
// 用户是否被禁用(在前面课程基础上扩展)
public function checkStatus($arr,$isReget = false){
$status = 1;
if ($isReget) {
// 账号密码登录 和 第三方登录
$userid = array_key_exists('user_id',$arr)?$arr['user_id']:$arr['id'];
// 判断第三方登录是否绑定了手机号码
if ($userid < 1) return $arr;
// 查询user表
$user = $this->find($userid)->toArray();
// 拿到status
$status = $user['status'];
}else{
$status = $arr['status'];
}
if($status==0) throw new BaseException(['code'=>200,'msg'=>'该用户已被禁用','errorCode'=>20001]);
return $arr;
}
// 第三方登录
public function otherlogin(){
// 获取所有参数
$param = request()->param();
// 解密过程(待添加)
// 验证用户是否存在
$user = $this->isExist(['provider'=>$param['provider'],'openid'=>$param['openid']]);
// 用户不存在,创建用户
$arr = [];
if (!$user) {
$user = $this->userbind()->create([
'type'=>$param['provider'],
'openid'=>$param['openid'],
'nickname'=>$param['nickName'],
'avatarurl'=>$param['avatarUrl'],
]);
$arr = $user->toArray();
$arr['expires_in'] = $param['expires_in'];
return $this->CreateSaveToken($arr);
}
// 用户是否被禁用
$arr = $this->checkStatus($user->toArray());
// 登录成功,返回token
$arr['expires_in'] = $param['expires_in'];
return $this->CreateSaveToken($arr);
}