小程序获取微信用户的openid
//index.js
//获取应用实例
const app = getApp() Page({
globalData: {
appid: '11121221a89e0',//appid需自己提供
secret: '',//secret需自己提供,此处的
}, data: {
motto: '技术带来改变',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
//事件处理函数
bindViewTap: function() {
wx.switchTab({
url: '../task/task'
})
}, onLoad: function () {
var that = this
var user = wx.getStorageSync('user') || {};
var userInfo = wx.getStorageSync('userInfo') || {};
if ((!user.openid || (user.expires_in || Date.now()) < (Date.now() + )) && (!userInfo.nickName)) {
wx.login({
success: function (res) {
if (res.code) {
wx.getUserInfo({
success: function (res) {
var objz = {};
objz.avatarUrl = res.userInfo.avatarUrl;
objz.nickName = res.userInfo.nickName;
console.log(objz);
wx.setStorageSync('userInfo', objz);//存储userInfo
}
});
var d = that.globalData;//这里存储了appid、secret、token串
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', // 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
}
});
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
});
}
}, getUserInfo: function(e) {
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
},
LoadUserSub: function (res) {
var openid=res;
console.log(openid);
} })
app.js中的代码