小程序可以通過微信官方提供的登錄能力方便地獲取微信提供的用戶身份標(biāo)識,快速建立小程序內(nèi)的用戶體系。

調(diào)用接口獲取登錄憑證(code)。通過憑證進(jìn)而換取用戶登錄態(tài)信息,包括用戶的唯一標(biāo)識(openid)及本次登錄的會話密鑰(session_key)等。用戶數(shù)據(jù)的加解密通訊需要依賴會話密鑰完成。
通過wx.login獲取登錄憑證code ,然后調(diào)用后臺接口wx.request發(fā)送參數(shù)code調(diào)用接口換取openid和session_key,wx.checkSession檢測當(dāng)前用戶登錄態(tài)是否有效
onLaunch: function (options) {
// 檢測版本的更新(添加)
var that = this;
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
// 請求完新版本信息的回調(diào)
})
updateManager.onUpdateReady(function () {
wx.showModal({
title: '更新提示',
content: '新版本已經(jīng)準(zhǔn)備好,是否重啟應(yīng)用?',
success: function (res) {
if (res.confirm) {
// 新的版本已經(jīng)下載好,調(diào)用 applyUpdate 應(yīng)用新版本并重啟
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function () {
// 新的版本下載失敗
})
// 查看是否授權(quán)
// that.getSetting()
that.getOpenid()
},
// 獲取openid
getOpenid:function(){
var that = this
wx.login({
success: function (loginCode) {
// console.log(loginCode.code)
// 獲取openid
wx.request({
url: ‘xxxxxxxxxxxx’,
data: {
js_code: loginCode.code
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',
success: function (res) {
if (res.data.code == 1) {
that.globalData.openId = res.data.data.openid;
console.log(that.globalData.openId)
if (that.employIdCallback) {
that.globalData.openId = res.data.data.openid;
that.employIdCallback(that.globalData.openId);
}
}
},
// 獲取openid失敗
fail: function (res) {
}
})
}
})
},
globalData: {
openId: '',
token:'',
},
小程序授權(quán)
方法1:getSetting獲取用戶的當(dāng)前設(shè)置。返回值中只會出現(xiàn)小程序已經(jīng)向用戶請求過的權(quán)限。
獲取用戶nickName,avatarUrl,gender,city,province,country,language等各種信息
// 查看是否授權(quán)
getSetting:function(){
var that = this
wx.getSetting({
success(res) {
if (res.authSetting['scope.userInfo']) {
// 已經(jīng)授權(quán),可以直接調(diào)用 getUserInfo 獲取頭像昵稱
wx.getUserInfo({
success(res) {
console.log(res)
var avatarUrl = res.userInfo.avatarUrl;
var nickName = res.userInfo.nickName;
that.globalData.avatarUrl = avatarUrl;
that.globalData.nickName = nickName;
}
})
}else{
// 未授權(quán)
}
}
})
},
方法2:如果只是需要獲取頭像和昵稱的話使用微信開放能力
<open-data type="userAvatarUrl"></open-data> <open-data type="userGender" lang="zh_CN"></open-data> //城市和省份獲取的都是字母拼寫,例如:Bozhou Anhui <open-data type="userCity"></open-data> <open-data type="userProvince" lang="zh_CN"></open-data>