用wx.getUserProfile吊起授权登录的弹框
用wx.login获取code码调用接口获取openid和session_key进行登录
后端请求接口
public function Log(Request $request){ //获取code码 $code =$request->get('code'); //验证code码 if(empty($code)){ return response()->json([ 'code' => -1, 'data' => null, 'msg' => 'code不能为空' ]); } $appid = "wxafd868df85742f9a"; $sc = "654110ae269bed71a9155b7c4f6a8f61"; //微信授权登录第三方接口 $wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$sc&js_code=$code&grant_type=authorization_code"; //发送请求 $result = file_get_contents($wxLoginUrl); $result = json_decode($result,true); // print_r($result);die(); //验证接口返回的错误码 //40029 code无效 //45011 api minute-quota reach limit mustslower retry next minute api调用太频繁,请稍后再试 if (isset($result['errcode']) && $result['errcode'] != 0) { return response()->json([ 'code' => -1, 'data' => null, 'errcode'=>$result['errcode'], 'msg' => '解析失败', ]); } $data = UserMod::where('openid', $result['openid'])->first(); if ($data == null) { UserMod::create([ 'openid' => $result['openid'], 'session_key' => $result['session_key'] ]); } $token = Token::getToken($data); return response()->json([ 'code' => 0, 'token' => $token, 'openid'=>$result['openid'], 'msg' => '登录成功' ]); }
、、、、、、、前端调用接口
getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
// 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
console.log(res.userInfo)
wx.setStorageSync('userInfo', res.userInfo)
wx.setStorageSync('nickName', res.userInfo.nickName)
wx.setStorageSync('avatarUrl', res.userInfo.avatarUrl)
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
if(this.data.hasUserInfo=true){
wx.login({
success:(res)=> {
console.log(res.code)
if (res.code) {
//发起网络请求
wx.request({
url: 'http://www.rk.com/getLogins',
data: {
code: res.code
},
success: (res) => {
console.log(res.data)
//存储token
wx.setStorageSync('token', res.data.token)
wx.setStorageSync('openid', res.data.openid)
wx.navigateTo({
url: '/pages/homepage/homepage',
})
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
}
})
},