1、登录:
下图的介绍是微信小程序登录的过程,开发过程中也是采用的这个逻辑。
- 通过调用wx.login() API,成功后会拿到用户的code信息
- 将code信息通过接口,传给自己的后台(不是微信的后台),在服务端发起对微信后台的请求,成功后拿到用户登录态信息,包括openid、session_key等。也就是通常所说的拿code换openid,这个openid是用户的唯一标识。
- 自己的后台,拿到openid、session_key等信息后,通过第三方加密,生成自己的session信息,返回给前端。
- 前端拿到第三方加密后的session后,通过wx.setStorage()保存在本地,以后的请求都需要携带这个经过第三方加密的session信息。
- 之后如果需要用户重新登录,先去检查本地的session信息,如果存在,再用wx.checkSession()检查是否在微信的服务器端过期。如果本地不存在或者已过期,则重新从步骤1开始走登录流程。
登录的代码如下:
wx.getStorage({
key: "code",
success: res => {
wx.checkSession({
success: res => {
console.log("Session未过期,登陆状态未失效");
},
fail: err => {
// 重新登录
console.log("Session过期,重新登录");
loginAction();
}
});
},
fail: res => {
console.log("无code信息,调用登录接口获取code");
loginAction();
}
});
2、授权:
这里以获取用户个人信息为例
之前获取用户信息直接用 wx.getUserInfo即可,但微信为了优化用户体验,后来被限制。使用button按钮的 open-type="getUserInfo" ,通过 bindgetuserinfo**事件获取用户信息,现在叒限制。**现在使用API: wx.getUserProFile获取用户信息。
获取用户信息。页面产生点击事件(例如 button 上 bindtap 的回调中)后才可调用,每次请求都会弹出授权窗口,用户同意后返回 userInfo。该接口用于替换 wx.getUserInfo,详情参考文档: developers.weixin.qq.com/community/d…
1.将授权登陆获取用户信息的接口调整了,新增了一个 wx.getUserProfile 。特说明一下授权登陆的注意事项:
2.原授权登陆流程不变,依旧是**
wx.login >>> code >>> 请求接口换取openid >>> openid >>> 自定义请求态 >>> uid
**只是获取用户信息的地方发生改变了,获取用户信息必须通过wx.getUserProfile获取,
3. wx.getUserProfile** 返回的加密数据中不包含 openId 和 unionId 字段。**通过wx.login接口获取的登录凭证可直接换取unionID
使用方面注意事项:
wx.getUserProfile这个API必须写在事件的最上面,只能事件触发
下面是官方示例直接复制即可实现简单的授权获取信息:
view
view
block
<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
<button wx:else="" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
block

text{{userInfo.nickName}}
Page({
data: {
userInfo: {},
hasUserInfo: false,
canIUseGetUserProfile: false,
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
},
getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
// 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
},
getUserInfo(e) {
// 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
},
})