
调用接口获取登录凭证(code)进而换取用户登录态信息,包括用户的唯一标识(openid) 及本次登录的会话密钥(session_key)。用户数据的加解密通讯需要依赖会话密钥完成。
// 登录
wx.login({
success: res => {
console.log(res)
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
拿到上一步获取的code,结合小程序 appid 和 secret 请求接口:
`https://api.weixin.qq.com/sns/jscode2session?appid=${_this.globalData.AppID}&secret=${_this.globalData.AppSecret}&&js_code=${res.code}&grant_type=authorization_code`换取openid,与 openid 一同被返回的,还包括 session_key,其中 session_key 是对用户数据进行加密签名的密钥。为了自身应用安全,session_key 不应该在网络上传输。

// app.js
App({
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
},
//app.js
getUserInfo:function(cb){
var that = this
if(that.globalData.userInfo){
typeof cb == "function" && cb(that.globalData.userInfo)
}else{
//调用登录接口
wx.showModal({
title: '温馨提示',
content: '正在请求获取您的个人信息,以后续方便使用本程序!',
success(res) {
if (res.confirm) {
wx.getUserProfile({
desc: "获取你的昵称、头像、地区及性别",
success: res => {
that.globalData.userInfo = res.userInfo
typeof cb == "function" && cb(that.globalData.userInfo)
},
fail: res => {
//拒绝授权
that.showErrorModal('您拒绝了请求');
return;
}
})
} else if (res.cancel) {
//拒绝授权 showErrorModal是自定义的提示
that.showErrorModal('您拒绝了请求');
return;
}
}
})
}
},
globalData: {
userInfo: null
}
})onLoad() {
var that = this
app.getUserInfo(function (userInfo) {
console.log(userInfo)
//更新数据
that.setData({
userInfo: userInfo
})
})
}<block wx:if="{{canIUseOpenData}}">
<view class="userinfo-avatar" bindtap="bindViewTap">
<open-data type="userAvatarUrl"></open-data>
</view>
<open-data type="userNickName"></open-data>
</block><block wx:elif="{{!hasUserInfo}}">
<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
<button wx:elif="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
</block>getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
console.log(res)
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
},