1. 获取openID(在app.js):
/**
* 全局变量
*/
globalData: {
userInfo: null,
appid: 'wx08**********2796', //appid
secret: '64cd85a****************2c75dfd5', //secret
amapKey: '6ef95**********************92021bdf14', //高德地图key
},
/**获取OpenID */
getOpenId: function () {
var that = this
wx.login({
success: function (res) {
if (res.code) {
wx.getUserInfo({
success: function (res) {
console.log(res.userInfo);
wx.setStorageSync('userInfo', res.userInfo); //存储userInfo
}
});
//这里存储了appid、secret、token串
var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + that.globalData.appid + '&secret=' + that.globalData.secret + '&js_code=' + res.code + '&grant_type=authorization_code';
wx.request({
url: url,
data: {},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 设置请求的 header
success: function (res) {
var obj = {};
obj.openid = res.data.openid;
obj.expires_in = Date.now() + res.data.expires_in;
console.log(obj);
wx.setStorageSync('user', obj); //存储openid
that.globalData.openid = res.data.openid;
}
});
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
});
}
2. 获取userInfo:
/**获取用户信息 */
getUserInfo: function () {
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
console.log("userInfo", res.userInfo)
this.globalData.userInfo = res.userInfo;
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
}
另外,小程序官方对获取用户信息的说明:为优化用户体验,使用
wx.getUserInfo
接口直接弹出授权框的开发方式将逐步不再支持。从2018年4月30日开始,小程序与小游戏的体验版、开发版调用wx.getUserInfo
接口,将无法弹出授权询问框,默认调用失败。正式版暂不受影响。开发者可使用以下方式获取或展示用户信息:1、使用 button 组件,并将 open-type 指定为 getUserInfo 类型,获取用户基本信息。
详情参考文档:https://developers.weixin.qq.com/miniprogram/dev/component/button.html
2、使用 open-data 展示用户基本信息。
详情参考文档:https://developers.weixin.qq.com/miniprogram/dev/component/open-data.html
网友评论