uview-ui-pr
Version:
uView UI,是uni-app生态优秀的UI框架,全面的组件和便捷的工具会让您信手拈来,如鱼得水
124 lines (118 loc) • 3.88 kB
JavaScript
import tips from "./tips";
/**
* 授权验证
* @param {String} scope 权限名,去除 scope. 的值,如:用户信息 userInfo
* https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/authorize.html
* @param {String} name 权限名称
* @param {Boolean} openSetting 是否打开设置页
* @callback Promise {err, res, msg}
* err:0 为成功,1-6为失败
*/
/**
* getSetting 有调用次数上限!!!详情查看
* https://developers.weixin.qq.com/miniprogram/dev/framework/performance/api-frequency.html
*/
// 用户已授权的权限列表
const argeeList = {};
const authorize = function (scope, name = "该功能", useConfirm = true) {
return new Promise((resolve, reject) => {
if (!scope) {
resolve({ err: 1, res: "", msg: "scope未设置" });
return;
}
const key = `scope.${scope}`;
// 查询用户是否已经授权过,授权过后无需再调用getSetting接口
if (argeeList[key]) {
resolve({ err: 0, res: argeeList[key], msg: "success" });
return;
}
uni.getSetting({
success(res) {
if (!res.authSetting[key]) {
uni.authorize({
scope: key,
success(ret) {
// 用户已经同意小程序的${scope}授权,后续调用 ${scope} 接口不会弹窗询问
argeeList[key] = ret;
resolve({ err: 0, res: ret, msg: "success" });
},
fail(err) {
console.log(err);
if (useConfirm) {
// 用户拒绝授权(未授权),询问打开设置重新授权
tips.confirm({
title: "授权提醒",
content: `使用 ${name} 需要授权,您可以打开设置进行授权`,
showCancel: true,
confirmText: "打开设置",
}).then((result) => {
if (result) {
// 确认打开设置
uni.openSetting({
success(setRes) {
const authSetting =
setRes.authSetting;
console.log(authSetting);
// 授权状态是异步的,无法实时获取最新状态,先返回失败,后续有改善了,再开放
// resolve({ err: 5, res: '', msg: '已结束,请重试' })
if (authSetting[key]) {
// 用户在设置页授权成功
tips.toast("授权成功");
argeeList[key] = setRes;
resolve({
err: 0,
res: setRes,
msg: "设置页,已授权",
});
} else {
// 用户在设置页未授权
tips.toast("授权失败");
resolve({
err: 5,
res: "",
msg: "设置页,未授权",
});
}
},
fail(setErr) {
// 打开设置页失败,授权失败
tips.toast(
"打开设置页失败,请重试"
);
resolve({
err: 4,
res: setErr,
msg: "打开设置页失败,请重试",
});
},
});
} else {
// 取消打开设置,授权失败
resolve({
err: 3,
res: "",
msg: "取消进入设置页",
});
}
});
} else {
// 查询setting未授权
resolve({ err: 6, msg: "未授权" });
}
},
});
} else {
// 已授权${scope}
argeeList[key] = res.authSetting[key];
resolve({ err: 0, res, msg: "success" });
}
},
fail(err) {
// 查询失败,授权终止
useConfirm && tips.toast("查询授权信息失败,请重试");
resolve({ err: 2, res: err, msg: "查询授权信息失败,请重试" });
},
});
});
};
export default authorize;