小程式第一次授權獲取不到openid,需要重新編譯一下之后才能獲取。
代碼如下:
這是授權過了走的代碼:
wx.getSetting({
success: function (res) {
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: function (res) {
that.setData({
avatarUrl: res.userInfo.avatarUrl,
userInfo: res.userInfo
}),
// 用戶已經授權過,不需要顯示授權頁面,所以不需要改變 isHide 的值
// 根據自己的需求有其他操作再補充
// 我這里實作的是在用戶授權成功后,呼叫微信的 wx.login 介面,從而獲取code
wx.login({
success: res => {
// 獲取到用戶的 code 之后:res.code
//console.log("用戶的code:" + res.code);
that.setData({
code: res.code
}),
//請求獲取openid
wx.request({
url: app.globalData.url + '/appInterface/getOpenid.do?code=' + res.code,
//url: app.globalData.url + '/appInterface/getOpenid.do',
method: 'GET',
// data:{
// code: res.code
// },
header: {
'Content-Type': 'application/json'
},
success: function (ares) {
//將openid設定為所有頁面都能訪問
app.globalData.openid = ares.data.obj
//默認請求注冊會員
// wx.request({
// url: app.globalData.url + '/appInterface/addUser.do',
// data: {
// userOpenid: ares.data.obj,
// userNick: that.data.userInfo.nickName,
// userHadimag: that.data.userInfo.avatarUrl
// },
// method: 'POST',
// header: {
// 'Content-Type': 'application/x-www-form-urlencoded'
// },
// success: function (bres) {
// }
// })
}
})
//授權成功跳轉到首頁
wx.reLaunch({
url: '/pages/login/login'
})
}
});
}
});
} else {
// 用戶沒有授權
// 改變 isHide 的值,顯示授權頁面
that.setData({
isHide: true
});
}
}
});
這是第一次授權時走的代碼:
bindGetUserInfo: function (e) {
if (e.detail.userInfo) {
//用戶按了允許授權按鈕
var that = this;
// 獲取到用戶的資訊了,列印到控制臺上看下
console.log("用戶的資訊如下:");
console.log(e.detail.userInfo);
//授權成功后,通過改變 isHide 的值,讓實作頁面顯示出來,把授權頁面隱藏起來
that.setData({
isHide: false
});
wx.getUserInfo({
success: function (res) {
that.setData({
avatarUrl: res.userInfo.avatarUrl,
userInfo: res.userInfo
}),
// 用戶已經授權過,不需要顯示授權頁面,所以不需要改變 isHide 的值
// 根據自己的需求有其他操作再補充
// 我這里實作的是在用戶授權成功后,呼叫微信的 wx.login 介面,從而獲取code
wx.login({
success: res => {
// 獲取到用戶的 code 之后:res.code
console.log("用戶的code:" + res.code);
wx.request({
url: app.globalData.url + '/appInterface/getOpenid.do?code=' + res.code,
//url: app.globalData.url + '/appInterface/getOpenid.do',
method: 'GET',
// data:{
// code: res.code
// },
header: {
'Content-Type': 'application/json'
},
success: function (ares) {
//將openid設定為所有頁面都能訪問
app.globalData.openid = ares.data.obj
//默認請求注冊會員
// wx.request({
// url: app.globalData.url + '/appInterface/addUser.do',
// data: {
// userOpenid: ares.data.obj,
// userNick: that.data.userInfo.nickName,
// userHadimag: that.data.userInfo.avatarUrl
// },
// method: 'POST',
// header: {
// 'Content-Type': 'application/x-www-form-urlencoded'
// },
// success: function (bres) {
// }
// })
}
})
wx.reLaunch({
url: '/pages/login/login'
})
}
});
}
});
} else {
//用戶按了拒絕按鈕
wx.showModal({
title: '警告',
content: '您點擊了拒絕授權,將無法進入小程式,請授權之后再進入!!!',
showCancel: false,
confirmText: '回傳授權',
success: function (res) {
// 用戶沒有授權成功,不需要改變 isHide 的值
if (res.confirm) {
console.log('用戶點擊了“回傳授權”');
}
}
});
}
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/123754.html
標籤:其他技術專區
上一篇:如何的更好的領悟學習知識'
下一篇:jacob操作ppt報錯
