
微信小程序的常用授权
来源:
浏览:116
时间:2023-08-09
1、微信授权头像昵称等
先上代码,新版本getUserProfile:
wxml
js:
data: {
userInfo: {},
hasUserInfo: false,
canIUseGetUserProfile: false,
},
onLoad() {
//用来判断是否兼容新旧版本
let that = this;
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
}else if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo;
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
},
getUserProfile(e) {
let code = "";
let that = this;
//先获取code和后台进行交换,因为会异步所以用了setTimeout
wx.login({
success(res) {
code = res.code;
}
});
setTimeout(() => {
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res1) => {
//拿到用户头像昵称等信息
that.setData({
userInfo: res1.userInfo,
hasUserInfo: true,
})
//调接口存到数据库,并弹出获取手机号的弹框
wx.request({
url: 'https:njlingshi.com/api/weChatAuth?code='+code,
method: "POST",
success(res2) {
that.setData({
showPhoneModal: true,//展示获取手机号的弹框
codeKey: res2.data.data.codeKey,//存储key和用户加密信息后面用到
userInfoEncrypt: {
"encryptedData": res1.encryptedData,
"iv": res1.iv
}
})
}
})
}
})
})
},
复制代码
旧版本getUserInfo:
wxml
js:
//data部分和上面一样
getUserInfo(e) {
//在这里就可以拿到用户加密信息encryptedData和iv等
// 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
wx.login({
success(res) {
if (res.code) {
wx.request({
url: 'https:njlingshi.com/api/weChatAuth?code='+code,
method: "POST",
success(res) {
that.setData({
showPhoneModal: true,//展示获取手机号的弹框
"codeKey": res.data.data.codeKey,
"userInfoEncrypt": {
//存储key和用户加密信息后面用到
"encryptedData": e.detail.encryptedData,
"iv": e.detail.iv
}
})
}
})
}
}
});
},
复制代码
区别:
1、getUserProfile页面产生点击事件后才可调用,每次请求都会弹出授权窗口,需要在wx.getUserProfile({})方法执行后拿到用户信息
getUserInfo在按钮点击的时候就可以拿到信息,目前不推荐使用了。
2、记住这时候接口如果提示解密失败、微信解密验签失败是后端的锅不要背,硬气点!
3、tips:小程序在最后审核上线的时候会卡登录,如果你进页面必须要授权登录才行可能会不通过,这个要先沟通好,首页等接口不需要token也可以访问。
2、授权获取手机号码
wxml:
js:getPhoneNumber(e) {
let that = this;
if (!e.detail.iv) {//判断是否允许授权,拿到加密信息,展示授权弹框
this.setData({
showPhoneModal: false
})
return;
}
wx.request({
url: 'https:njlingshi.com/api/miniProgramLogin',
method: "POST",
data: {//传入接口需要用到的各种参数
"codeKey": that.data.codeKey,
"userInfoEncrypt": that.data.userInfoEncrypt,
"userPhoneEncrypt": {
encryptedData: e.detail.encryptedData,
iv: e.detail.iv
}
},
success(res) {
if(res.statusCode == 200) {
app.globalData.token = res.data.data.token;//存入token和用户信息在全局变量中
app.globalData.userInfo = res.data.data;
that.setData({showPhoneModal: false})
wx.setStorage({
key: "token",
data: res.data.data.token
})
wx.setStorage({
key: "userinfo",
data: res.data.data
})
wx.showLoading({title: '加载中'});
setTimeout(()=>{wx.hideLoading();},1500)
//可以在这里调用界面需要token的接口
}else {
wx.showToast({
icon:'error',
title: res.data.message,
})
}
}
})
},
复制代码
3、授权获取地址位置
app.json中加入
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置效果展示"
}},
app.js
onShow() {
//获取用户当前位置
wx.getLocation({
type: 'gcj02',
success (res) {//记录经纬度方便后面其他界面用到
that.globalData.userLat = res.latitude;
that.globalData.userLong = res.longitude;
}
})
},
globalData: {
userLat: '',//用户所在经纬度
userLong: '',
}
复制代码
算出用户当前位置与目的位置的距离
app.js中写公共方法
// 计算距离函数
Rad(d) { //根据经纬度判断距离
return d * Math.PI / 180.0;
},
getDistance(lat1, lng1, lat2, lng2) {
// lat1用户的纬度 // lng1用户的经度 // lat2商家的纬度 // lng2商家的经度
var radLat1 = this.Rad(lat1);
var radLat2 = this.Rad(lat2);
var a = radLat1 - radLat2;
var b = this.Rad(lng1) - this.Rad(lng2);
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * 6378.137;
s = Math.round(s * 10000) / 10000;
s = s.toFixed(1) + 'km' //保留两位小数
return s
},
js中使用示例:
app.getDistance(app.globalData.userLat,app.globalData.userLong,"31.929074190568766","118.8757504898559");
复制代码
4、封装请求接口
个人认为这样操作,在一定程度上做到了请求拦截,相当于vue的axios的请求拦截
app.js
wxRequest(method, url, data, callback, errFun) {
let baseUrl = 'https://njlingshi.com';//这里千万不要写很多前缀不然后面接口不一样很麻烦
wx.request({
url: baseUrl+url,
method: method,
data: data,
header: {
'content-type': method == 'GET' || method == 'POST'?'application/json':'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': this.globalData.token
},
dataType: 'json',
success: function (res) {
if(res.statusCode == 200) {
callback(res.data);
}else if(
res.statusCode == 401){//这里根据情况改401状态码,我这里代码登录失效
wx.showToast({
icon: "none",
title: '请登录!',
})
wx.removeStorageSync('token');
}else {//剩余情况就是接口报错需要提醒了
wx.showToast({
icon: "none",
title: res.data.errMsg ? res.data.errMsg : res.data.message,
})
}
},
fail: function (err) {
console.log(err)
errFun(err);
}
})
},
js调用:
let that = this;
app.wxRequest('GET', '/api/getHotList',{}, (res) => {
this.setData({
hotList: res.data && res.data.length > 0 ? res.data : []
})
}, (err) => {
console.log(err)
})
复制代码
5、一些简单的小坑避免指南
function indexOf(arr, value) {
if (arr.indexOf(value) < 0) {
return false;
} else {
return true;
}
}
module.exports.indexOf = indexOf;
复制代码
先写这么多,后期再更新,觉得有用的朋友点个赞呀~


