1.wxml
<!-- 如果只是展示用户头像昵称,可以使用 <open-data /> 组件 -->
<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>
<!-- 需要使用 button 来授权登录 -->
<button type="primary" open-type="getUserInfo" bindtap="click">授权登录</button>
?
2. .js
click(){
wx.getUserProfile({
desc: 'desc',
success:(res) => {
// console.log(res),
wx.login({
// timeout: 10000,
success(res){
let code = res.code
if(code){
wx.request({
url: 'http://www.wenk.com/index.php/admin/WxLogin', //仅为示例,并非真实的接口地址
method:'post',
data: {
code:code,
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data.data.openid)
wx.setStorage({
key:'openid',
data:res.data.data.openid
})
wx.reLaunch({
url: '/pages/shou/shou',
})
}
})
}
}
})
}
})
},
3.后端API接口
public function WxLogin()
{
$code = input('code');
$appid = '微信公众平台获取';
$secret = '微信公众平台获取';
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
$output = json_decode(file_get_contents($url),true);
$WxLogin = [
'openid' => $output['openid'],
'session_key' => $output['session_key']
];
//判断用户是否是第一次登录
$user = (new \app\admin\model\Login())->where('openid',$output['openid'])->find();
//判断
if ($user){
return json(['code' => 200,'msg' => 'success','data' => $user]);
}
//没有登陆过则添加入库保存
if ((new \app\admin\model\Login())->insert($WxLogin)){
return json(['code' => 200,'msg' => 'success','data' => $WxLogin]);
}else{
return json(['code' => 500,'msg' => 'error','data' => $WxLogin]);
}
}
|