之前微信授权登录时是直接可以通过getUserInfo接口 弹出授权弹窗。由于微信官方修改了 getUserInfo 接口,所以现在无法实现一进入微信小程序就弹出授权窗口,只能通过 button 去触发
效果图:
.js代码
const app = getApp()
Page({
data: {
userInfo: {},
isHide: false,
//判断小程序的API,回调,参数,组件等是否在当前版本可用。
canIUse: wx.canIUse('button.open-type.getUserInfo'),
},
refresh: function(){
wx.navigateTo({
url: './index',
})
},
onLoad: function () {
var that = this;
// 查看是否授权
wx.getSetting({
success: function (res) {
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: function (res) {
that.setData({
userInfo: res.userInfo,
isHide: false
})
}
})
} else {
// 用户没有授权
// 改变 isHide 的值,显示授权页面
that.setData({
isHide: true
})
}
}
})
},
bindGetUserInfo: function (e) {
if (e.detail.userInfo) {
//用户按了允许授权按钮
var that = this;
// 获取到用户的信息了,打印到控制台上看下
console.log("用户的信息如下:")
console.log(e.detail.userInfo)
app.globalData.userInfo = e.detail.userInfo
//授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来
that.setData({
userInfo: e.detail.userInfo,
isHide: false
})
} else {
//用户按了拒绝按钮
wx.showModal({
title: '警告',
content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入',
showCancel: false,
confirmText: '返回授权',
success: function (res) {
// 用户没有授权成功,不需要改变 isHide 的值
if (res.confirm) {
console.log('用户点击了“返回授权”')
}
}
})
}
},
})
.wxml代码
<view wx:if="{{isHide}}">
<view wx:if="{{canIUse}}">
<button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo">
授权登录
</button>
</view>
<view wx:else>请升级微信版本</view>
</view>
<view wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<button bindtap="refresh">刷新</button>
</view>
.wxss代码
.bottom {
border-radius: 80rpx;
margin: 70rpx 50rpx;
font-size: 35rpx;
}
.userinfo-avatar {
width: 128rpx;
height: 128rpx;
margin: 20rpx;
border-radius: 50%;
}