如何获取微信小程序用户openid
1个回答
展开全部
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) {
//发起网络请求获取openid
// console.log(res.code)
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session?appId=你的appid&secret=你的secret&js_code='+res.code+'&grant_type=authorization_code',
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('openid', obj);//存储openid
}
});
//获取用户资料
wx.getUserInfo({
success: function (res) {
// console.log("111")
var users={};
users.avatarUrl=res.userInfo.avatarUrl;
users.nickName=res.userInfo.nickName;
console.log(users);
wx.setStorageSync('userInfo', users);//存储用户信息
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})
}
}
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) {
//发起网络请求获取openid
// console.log(res.code)
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session?appId=你的appid&secret=你的secret&js_code='+res.code+'&grant_type=authorization_code',
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('openid', obj);//存储openid
}
});
//获取用户资料
wx.getUserInfo({
success: function (res) {
// console.log("111")
var users={};
users.avatarUrl=res.userInfo.avatarUrl;
users.nickName=res.userInfo.nickName;
console.log(users);
wx.setStorageSync('userInfo', users);//存储用户信息
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询