微信小程式-獲得使用者openid、暱稱等資訊的方式
阿新 • • 發佈:2019-01-07
var self = this;
wx.login({ //登入
success: function (res) {
if (res.code) {
getApp().globalData.code = res.code;
var code2 = "";
code2 = res.code;
if (code2 != "") {
wx.getUserInfo({ //獲得個人資訊
// withCredentials: true,
success: function (res) {
getApp().globalData.nickName = res.userInfo.nickName;//儲存nickName
getApp().globalData.city = res.userInfo.city;//儲存city
self.setData({
nickName: res.userInfo.nickName
});
},
fail: function (res) { },
complete: function (res) { },
});
var d =getApp().globalData;
var url1 = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + code2 + '&grant_type=authorization_code';
wx.request({ //獲得openid
url: url1,
data: {},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 設定請求的 header
success: function (res) {
console.log(res);
getApp().globalData.openid = res.data.openid;//儲存openid
}
});
}
else {
console.log("code1為空!" + res.code);
}
}
else {
console.log('獲取使用者登入態失敗!' + res.errMsg);
}
},
fail: function (res) { },
complete: function (res) { },
wx.login({ //登入
success: function (res) {
if (res.code) {
getApp().globalData.code = res.code;
var code2 = "";
code2 = res.code;
if (code2 != "") {
wx.getUserInfo({ //獲得個人資訊
// withCredentials: true,
success: function (res) {
getApp().globalData.nickName = res.userInfo.nickName;//儲存nickName
getApp().globalData.city = res.userInfo.city;//儲存city
self.setData({
nickName: res.userInfo.nickName
});
},
fail: function (res) { },
complete: function (res) { },
});
var d =getApp().globalData;
var url1 = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + code2 + '&grant_type=authorization_code';
wx.request({ //獲得openid
url: url1,
data: {},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 設定請求的 header
success: function (res) {
console.log(res);
getApp().globalData.openid = res.data.openid;//儲存openid
}
});
}
else {
console.log("code1為空!" + res.code);
}
}
else {
console.log('獲取使用者登入態失敗!' + res.errMsg);
}
},
fail: function (res) { },
complete: function (res) { },
});
讚賞請掃下面的微信支付碼: