App({
globalData: {
appid: '',
secret: '',
},
onLaunch: function () {
var that = this
var user = wx.getStorageSync('user') || {};
var userInfo = wx.getStorageSync('userInfo') || {};
if ((!user.openid || (user.expires_in || Date.now()) < (Date.now() + 600)) && (!userInfo.nickName)) {
wx.login({
success: function (res) {
if (res.code) {
var d = that.globalData;
var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + res.code + '&grant_type=authorization_code';
wx.request({
url: l,
data: {},
method: 'GET',
success: function (res) {
var obj = {};
obj.openid = res.data.openid;
wx.setStorageSync("openId", res.data.openid);
obj.expires_in = Date.now() + res.data.expires_in;
wx.setStorageSync('user', obj);
}
});
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
});
}
}
})
- 获取openId
wx.getStorageSync('openId')
- 注意点
在微信开发软件中,需要清理缓存之后,获取openId才能成功。
