app.json:
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
}
app.js:
App({
//全局参数
globalData: {
userInfo: null
},
onLaunch: function () {
// 获取用户信息
wx.getSetting({
success: res => {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
console.log('已经授权')
}
}
})
},
})
html:
<button open-type="getUserInfo" bindgetuserinfo="getUserInfo">用户信息授权</button>
<button bindtap='onAuthLocation' >授权并获取位置</button>
<button bindtap='gotoSetting' >打开授权信息面板</button>
index.js:
const app = getApp()
Page({
data: {
userInfo: {},
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
onLoad: function () {
//userInfo有数据
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
})
}
else if (this.data.canIUse){
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
})
}
}
else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
})
}
})
}
},
//信息授权点击了允许
getUserInfo: function(e) {
console.log(e)
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
})
},
//位置授权
onAuthLocation() {
wx.authorize({
scope: 'scope.userLocation',
success: (res) => {
console.log('成功:', res)
this.onGetLocation();//获取位置
},
fail: (res) => {
console.log('失败:', res)
},
})
},
//获取位置
onGetLocation() {
wx.getLocation({
success: (res) => {
console.log('成功:', res)
},
fail: (res) => {
console.log('失败:', res)
},
})
},
//授权面板
gotoSetting() {
wx.openSetting({
success: (res) => {
console.log(res)
}
})
},
})