设置小程序启动页为登录页
1.wxml代码(布局的,最终要的是按钮)
<view class='header'>
<image src='/image/1.png'></image> //图片自己引入
</view>
<view class='content'>
<view>申请获取以下权限</view>
<text>获得你的公开信息(昵称,头像等)</text>
</view>
<button class='bottom' type='primary' open-type="getUserInfo" bind:getuserinfo="bindGetUserInfo">
授权登录
</button>
2.butten按钮的设置
3.绑定触发事件后在js文件中写相对应的方法(以下是login.js中的全部代码)
Page({
data: {
//判断小程序的API,回调,参数,组件等是否在当前版本可用。
canIUse: wx.canIUse('button.open-type.getUserInfo'),
isHide: false
},
onLoad: function () {
//页面初次加载判断用户是否授权过 去缓存中读取是否有
wx.getStorage({
key: 'openid',
success(res) {
//判断是否有openid 如果不为空则跳转到首页
if (res.data != "") {
//跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
wx.switchTab({
url: '/pages/index/index'
})
}
}
})
},
bindGetUserInfo(e) {
console.log(e)
//如果不允许 则没有userInfo这个值
//获取用户的昵称 判断用户点击的是允许还是拒绝
if (e.detail.userInfo) {
//如果用户允许,则能得到userInfo
console.log(e.detail.userInfo)
//获取用户的昵称
let nickname = e.detail.userInfo.nickName
// console.log(nickname)
//获取用户的昵称 去获取code
wx.login({
success(res) {
if (res.code) {
//得到了code值 携带参数发送请求
console.log(res.code)
//发起网络请求
wx.request({
url: 'http://www.xxxxxx.com/index.php/users/index/index',
data: {
code: res.code,
nickname: nickname,
},
dataType: "json",
method: "GET",
success(res) {
console.log(res.data.data.openid)
console.log(res.data.code)
//判断是否授权成功
if (res.data.code == 200) {
//将用户的openid缓存起来
wx.setStorage({
key: "openid",
data: res.data.data.openid
})
//页面跳转
wx.switchTab({
//跳转地址
url: '/pages/index/index',
})
} else {
}
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
}
})
4.php中的逻辑处理 如何获取用户信息
public function index()
{
//获取到code值
$code=input('code');
//已知appid 与 secret 从自己的微信公众平台注册获取
$appid="xxxxxxx";
$secret="xxxxxxxxx";
$url="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
//通过curl函数获取用户的oppid和sessionkey 将其进行添加入库
$res=curl_request($url,false,[],true);
//对 JSON 格式的字符串进行解码,转换为 PHP 变量 此次将 JSON 格式的字符串转化为数组
$res=\Qiniu\json_decode($res,true);
//判断用户是否已经授权过
$user=\app\wxxcx\model\Users::where('openid',$res['openid'])->find();
//如果用户已将存在则直接返回数据
if ($user){
return json(['code'=>200,'msg'=>'success','data'=>$user]);
}
//拼接数组入库保存
$info=[
'openid'=>$res['openid'],
'sessionkey'=>$res['session_key']
];
//添加入库
$data=\app\wxxcx\model\Users::create($info)->toArray();
//将数据返回
if ($data){
return json(['code'=>200,'msg'=>'success','data'=>$data]);
}else{
return json(['code'=>500,'msg'=>'error','data'=>""]);
}
}
5.wxss
/**index.wxss**/
.userinfo {
display: flex;
flex-direction: column;
align-items: center;
}
.userinfo-avatar {
width: 128rpx;
height: 128rpx;
margin: 20rpx;
border-radius: 50%;
}
.userinfo-nickname {
color: #aaa;
}
.usermotto {
margin-top: 200px;
}
注释:上面这种做法的好处的,设置登录页为默认启动页,而tabbar并未设置该页,所以说不用考虑tabbar在未登录状态下的是否显示问题,后端处理成功后考虑到后面会验证用户是否登录,所以要将用户的openid存入缓存中,等待随时取值
以上是以启动页来获取用户个人信息,微信小程序还提供了可以在app.js中通过获取当前浏览者的code进而获取openid和session_key