//用户授权登录,获取昵称头像
public function login(){
$img = input('img');
$nickname = input('nickname');
$gender = input('gender');
$pid = input('pid') ? input('pid') : 0;
$code = input('code');
$appid = config('app.appid'); //小程序appid
$secret = config('app.AppSecret'); //小程序秘钥
//拼接微信接口登录接口地址
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
$data = file_get_contents($url); //请求微信登录接口
$data = json_decode($data,true); //将微信返回值转换成数组
//如果返回值中有openid参数表示登录成功
if(isset($data['openid'])){
$user = Users::where('openid',$data['openid'])->find(); //在数据库中查询当前登录用户信息
$userinfo = json_decode(input('userinfo'),true); //接收小程序端用户数据
//判断该用户在数据库中是否存在
if($user)
{
//存在更新数据库用户数据
$user->img = $img;
$user->nickname = $nickname;
$user->save();
return json([
'status'=>'200',
'msg'=>'登录成功',
'data'=>$user
]);
}else{
//不存在根据自己数据库的数据结构添加用户数据
$user = new Users();
$user->nickname = $nickname;
$user->openid = $data['openid'];
$user->img = $img;
$user->ctime = time();
$user->gender = $gender;
$user->type = 0;
$user->pid = $pid;
$user->save();
$qrcode = $this->qrcode($user->id); //生成推广二维码
$user->qrcode = $qrcode;
$user->save();
return json([
'status'=>'200',
'msg'=>'登录成功',
'data'=>$user
]);
}
}else{
return json([
'status'=>'201',
'msg'=>'登录失败'
]);
}
}
小程序页面
<button bindtap="getUserProfile"> 授权登录 </button>
小程序前端
//获取用户头像昵称
getUserProfile:function(e){
wx.showLoading({
title: '正在登录',
})
let that = this
wx.getUserProfile({
desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
if(res.errMsg == 'getUserProfile:ok'){
wx.login({
success:r=>{
let img = res.userInfo.avatarUrl
let nickname = res.userInfo.nickName
let gender = res.userInfo.gender
wx.request({
url: api.wxlogin,
data:{
img:img,
nickname:nickname,
gender:gender,
code:r.code,
pid:that.data.pid
},
method:'post',
success:function(res){
wx.hideLoading()
if(res.data.status == '200'){
app.data.user_id = res.data.data.id
wx.redirectTo({
url: '/pages/index/index',
})
}else{
wx.showToast({
title: res.data.msg,
icon: 'none',
duration: 2000
})
}
}
})
}
})
}else{
wx.showToast({
title: '登录失败',//限制7个汉字
icon: 'none', //none 失败 loading 加载 success 成功
duration: 2000 //两秒钟自动关闭
})
}
}
})
},