mp.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * 小程序相关权限
  3. * @param {String} scopeValue - 权限种类,isMessage为订阅消息设置,默认false
  4. *
  5. */
  6. const TIPS_MAP = {
  7. 'userInfo': '用户信息',
  8. 'userLocation': '地理位置', //需要在manifest中配置permission。
  9. 'address': '通信地址',
  10. 'userLocationBackground': '后台定位',
  11. 'record': '录音功能',
  12. 'writePhotosAlbum': '保存到相册',
  13. 'camera': '摄像头',
  14. 'invoice': '获取发票',
  15. 'invoiceTitle': '发票抬头',
  16. 'werun': '微信步数',
  17. 'message': '订阅消息'
  18. }
  19. export default class MpAuth {
  20. constructor(scopeValue) {
  21. this.scopeValue = scopeValue
  22. this.isMessage = scopeValue === 'message' ? true : false
  23. }
  24. // 检测当前请求权限是否可用。
  25. checkAuth() {
  26. const that = this;
  27. return new Promise((resolve, reject) => {
  28. uni.getSetting({
  29. withSubscriptions: that.isMessage, //是否获取用户订阅消息的订阅状态
  30. success: res => {
  31. if (!that.isMessage) { // 非订阅消息
  32. if (!res.authSetting[
  33. `scope.${this.scopeValue}`]) { //用户未请求过此权限,后者用户拒绝了此权限
  34. uni.authorize({ //如果没请求过,会弹窗询问。同意过,直接success。此前拒绝,直接fai
  35. scope: `scope.${this.scopeValue}`,
  36. success: res => { //用户同意
  37. console.log(
  38. `%c用户同意${TIPS_MAP[this.scopeValue]}权限1`,
  39. 'color:green;background:yellow');
  40. resolve(1)
  41. },
  42. fail: err => { //用户拒绝
  43. console.log(
  44. `%c用户拒绝${TIPS_MAP[this.scopeValue]}权限`,
  45. 'color:green;background:yellow');
  46. resolve(0)
  47. that.setAuth()
  48. }
  49. })
  50. } else { //用户同意授权此权限,直接调用接口
  51. console.log(`%c用户同意${TIPS_MAP[this.scopeValue]}权限2`,
  52. 'color:green;background:yellow');
  53. resolve(1)
  54. }
  55. } else { //订阅消息 TODO
  56. }
  57. },
  58. fail: err => {
  59. console.log(`%cuni.getSetting失败:`, 'color:green;background:yellow');
  60. console.log(err);
  61. }
  62. })
  63. })
  64. }
  65. // 引导用户开启权限
  66. setAuth() {
  67. uni.showModal({
  68. title: '设置权限',
  69. content: `当前功能需要${TIPS_MAP[this.scopeValue]}权限,是否开启?`,
  70. confirmText: '立即授权',
  71. success: res => {
  72. res.confirm && uni.openSetting()
  73. },
  74. fail: err => {
  75. console.log(`%cuni.showModal失败:`, 'color:green;background:yellow');
  76. }
  77. })
  78. }
  79. }