微信小程序登录接口getUserProfile官方调整后新老版本兼容处理

700 阅读1分钟

2021年4月中旬,微信官方发布公告,对小程序登录接口做出调整 回收wx.getUserInfo接口可获取用户授权的个人信息能力,新增getUserProfile接口 公告详情:developers.weixin.qq.com/community/d…

login.wxml

<button class='login_button' wx:if="{{canIUseGetUserProfile}}" bindtap="wxLogin_new">授权登录</button>
<button class='login_button' wx:else open-type="getUserInfo" bindgetuserinfo="wxLogin_old">授权登录</button>

login.js

Page({
	data: {
		canIUseGetUserProfile:false,
		hasClick:false
	},
	onLoad: function(options) {
		console.log(wx.canIUse('getUserProfile'))
		//判断当前用户的基础库版本是否可调用新接口getUserProfile
		if (wx.canIUse('getUserProfile')) {
			this.setData({
				canIUseGetUserProfile:true
			})
		}
	},
	wxLogin_new(e) {
		if(this.data.hasClick){
			return
		}
		this.data.hasClick = true
		console.log("getUserProfile授权")
		wx.getUserProfile({
			desc: '用于展示头像昵称', 
			success: (res) => {
				this.data.hasClick = false
				console.log("wx.getUserProfile拿到的信息", res);
				wx.showLoading({
					title:"授权中"
				})
				let params = {
					encrypted_data: res.encryptedData,
					iv: res.iv,
					nickName:res.userInfo.nickName,
					avatarUrl:res.userInfo.avatarUrl,
					gender:res.userInfo.gender
				}
				wx.login({
					success:(res)=>{
						// console.log(res)
						let code = res.code
						//请求后台登录接口
						//..............
					}
				})
			},
			fail:(err)=>{
				this.data.hasClick = false
				console.log(err)
			}
		})
	},
	wxLogin_old(e) {
		console.log("getUserInfo授权")
		wx.showLoading({
			title:"授权中"
		})
		wx.login({
			success: (res) => {
				console.log(res)
				let code = res.code
				wx.getUserInfo({
					withCredentials: true,
					success: (res) => {
						console.log("getUserInfo返回信息====", res)
						//请求后台登录接口
						//..............
					},
					fail: (err) => {
						console.log("获取微信头像昵称失败", err)
					}
				})
			}
		})
	}
})