微信小程序授权登录
微信小程序更改了getUserInfo的接口,无法自动去弹出授权,所以在获取授权信息的时候需要根据button去进行获取;
在首页文件中,编写一个获取授权的页面,在刚进入页面时,判断用户是否授权。如果没有授权则显示出授权的页面,否则直接显示页面;
// 判断是否需要显示授权按钮<view wx:if="{{isHide}}"> <view wx:if="{{canIUse}}" > <view class='header'> <image src='/images/wx_login.png'></image> </view> <view class='content'> <view>申请获取以下权限</view> <text>获得你的公开信息(昵称,头像等)</text> </view> <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo"> 授权登录 </button> </view> <view wx:else>请升级微信版本</view></view><view wx:else> 这里是正文内容 </view>css:
//授权框的样式;.header { margin: 90rpx 0 90rpx 50rpx; border-bottom: 1px solid #ccc; text-align: center; width: 650rpx; height: 300rpx; line-height: 450rpx;}.header image { width: 200rpx; height: 200rpx;}.content { margin-left: 50rpx; margin-bottom: 90rpx;}.content text { display: block; color: #9d9d9d; margin-top: 40rpx;}.bottom { border-radius: 80rpx; margin: 70rpx 50rpx; font-size: 35rpx;}js代码
page({isHide: false,userInfo: {}}) onLoad: function () { var that = this; // 查看是否授权 wx.getSetting({ success: function (res) { if (res.authSetting['scope.userInfo']) { wx.getUserInfo({ success: function (res) { // 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值 // 获取昵称和头像,**这里看需求因为这里需要将昵称和头像传送给后台所以需要;** var name = res.userInfo.nickName; var photo = res.userInfo.avatarUrl; //调取登录按钮 that.userLogin(name,photo); } }); } else { // 用户没有授权 // 改变 isHide 的值,显示授权页面 that.setData({ isHide: true }); } } }); }, // 用户登录方法userLogin:function(name,photo){ var That = this; wx.login({ success: res => { wx.request({ url: api.login, data:{code:res.code,name:name,photo:photo}, success: res => { // 获取oppenid 和sessicon_key 用户ID var wechat = { openid:res.data.openid, session_key: res.data.session_key, uid:res.data.uid } //返回openid session_key 本地缓存,方便其他页面使用 wx.setStorage({ key: 'wechat', data: wechat }) } }); } });},// 用户授权方法 bindGetUserInfo: function (e) { if (e.detail.userInfo) { //用户按了允许授权按钮 var that = this; var name = e.detail.userInfo.nickName;//获取姓名 var photo = e.detail.userInfo.avatarUrl;//获取头像 //授权成功后执行登录方法; this.userLogin(name,photo); //授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来 that.setData({ isHide: false, userInfo:e.detail, }); } else { //用户按了拒绝按钮 wx.showModal({ title: '警告', content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!', showCancel: false, confirmText: '返回授权', success: function (res) { // 用户没有授权成功,不需要改变 isHide 的值 if (res.confirm) { console.log('用户点击了“返回授权”'); } } }); } },













