发布时间:2018-03-27 09:24:23 作者:佚名 阅读:(104)
根据文档,只需要进行一个get请求到如下地址即可:
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
appid和secret在微信小程序后台可以看到,js_code为使用wx.login登录时获取到的code参数数据,grant_type这个不用改动。
js文件:
var openId = (wx.getStorageSync('openId'))
if (openId) {
wx.getUserInfo({
success: function (res) {
that.setData({
nickName: res.userInfo.nickName,
avatarUrl: res.userInfo.avatarUrl,
})
},
fail: function () {
// fail
console.log("获取失败!")
},
complete: function () {
// complete
console.log("获取用户信息完成!")
}
})
} else {
wx.login({
success: function (res) {
console.log(res.code)
if (res.code) {
wx.getUserInfo({
withCredentials: true,
success: function (res_user) {
wx.request({
//后台接口地址
url: 'https://....com/wx/login',
data: {
code: res.code,
encryptedData: res_user.encryptedData,
iv: res_user.iv
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
// this.globalData.userInfo = JSON.parse(res.data);
that.setData({
nickName: res.data.nickName,
avatarUrl: res.data.avatarUrl,
})
wx.setStorageSync('openId', res.data.openId);
}
})
}, fail: function () {
wx.showModal({
title: '警告通知',
content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
success: function (res) {
if (res.confirm) {
wx.openSetting({
success: (res) => {
if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
wx.login({
success: function (res_login) {
if (res_login.code) {
wx.getUserInfo({
withCredentials: true,
success: function (res_user) {
wx.request({
url: 'https://....com/wx/login',
data: {
code: res_login.code,
encryptedData: res_user.encryptedData,
iv: res_user.iv
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
that.setData({
nickName: res.data.nickName,
avatarUrl: res.data.avatarUrl,
})
wx.setStorageSync('openId', res.data.openId);
}
})
}
})
}
}
});
}
}, fail: function (res) {
}
})
}
}
})
}, complete: function (res) {
}
})
}
}
})
}
},
globalData: {
userInfo: null
}
欢迎分享转载→ 微信小程序获取用户openid
© 2015-2021 - 吾爱编程网 版权所有 苏ICP备18033726号-1关于我们 - 网站声明 - 联系我们