#起源
- 在做小程序时授权问题是少不了的,可有时候总有人会点击拒绝授权,那我们开发拿不到需要的数据是不是很苦恼呢?我在自己正在做的小程序里使用了一种方法,现在分享出来~~
- 我的这个demo是个人信息+地理位置的双重授权
#思路 - 要么授权通过,进入首页
- 要么拒绝授权,停留在有授权入口的页面
- 需要设置一个标志值:
authorizeInfo,根据此值得真假来决定是渲染首页还是渲染显示重新授权的页面。
#过程
在页面显示的时候,获取用户信息与地理位置(当然,这是我所需要的)
// userInfo wx.getUserInfo({ success:res={ this.setData({userInfo : true}) }, fail:res={ this.setData({ userInfo: false }) } }) // locationInfo wx.getLocation({ success: res = { this.setData({ locationInfo: true }) }, fail: res = { this.setData({ locationInfo: false }) } })authorizeInfo的设置就要依靠刚刚获取的这两个值了,设置定时器不断执行authorizeInfo,直到userInfo和locationInfo两个值都为true就把定时器清除(设置定时器是因为刚开始获取userInfo和locationInfo可能会失败),当两者都为真时表示所有授权均已通过,跳转至首页。否则,将会一直停留在授权页。
//all authorize let timer = setInterval(() = { this.authorizeInfo(); if (this.data.userInfo && this.data.locationInfo){ clearInterval(timer) } }, 100) //authorizeInfo authorizeInfo: function(){ if (this.data.userInfo && this.data.locationInfo) { this.setData({ authorizeInfo: true }) //reLaunch wx.reLaunch({ url: '/pages/index/index' }) } else { this.setData({ authorizeInfo: false }) } }而重新授权这个操作需要调用wx.openSetting这个接口,通过返回值判断,用户再次调用授权操作后是否全部授权,是的话跳转至首页,否则停留在授权页。
//toAuthorize toAuthorize:function(){ //重新调起授权 wx.openSetting({ success: (res) = { if (res.authSetting["scope.userInfo"] && res.authSetting["scope.userLocation"]) { this.setData({ authorizeInfo: true }) //reLaunch wx.reLaunch({ url: '/pages/index/index' }) }else{ this.setData({ authorizeInfo: false }) } }, fail: (res) = { console.log("授权失败") } })使用方法
- 我的这个demo是个人信息加地理位置的双重授权
- pages下的authorize文件夹是可以拿来直接用的 复制粘贴到你的pages下就可以了
- 源码请移步GitHub 戳我去看源码
wepy常用封装
由于我平时主要使用wepy开发项目 所以这些常用封装及项目架子都是使用的wepy
覆盖了一些常用操作与封装、登录流程、保存图片至相册及相关授权流程
所有常用封装及流程实现请点我前往GitHub查看https://github.com/webxing/wepy_skeleton
项目目录结构
.├── README.md└── wepy_skeleton ├── package.json // 配置启动脚本 (debug/dev/build) ├── project.config.json ├── src │ ├── app.wpy // networkTimeout plugins this.use('promisify') 拦截request请求 │ ├── common │ │ ├── animate.wxss // 动画支持 │ │ ├── api.js // 所有api │ │ ├── collectFormId.js // 收集formId │ │ ├── common.js // 封装一些公用方法 │ │ ├── decorator.js // 封装trycatch装饰器 实现对函数的错误监控 │ │ ├── http.js // 封装小程序request请求 │ │ ├── bindEvent.js // 当n个触发条件均满足时 触发函数 │ │ └── storage.js // 封装storage为promise │ ├── components │ │ └── Modal.wpy // 错误弹窗 │ └── pages │ └── index.wpy // 登录流程 引入装饰器trycatch 配置错误处理handleError │ └── sign.wpy // 保存图片至相册及相关授权处理 │ └── auth.wpy // 授权页 └── wepy.config.js // 配置rootURL 配置Less autoprefix 配置drop_console drop_debugger#个人链接
- github:https://github.com/webxing
- 简书:https://www.jianshu.com/u/489662a091fd
本人两年纯小程序开发经验 新建了一个交流群 欢迎加入

以下是我独立开发的小程序 第一次Pro 欢迎使用 欢迎吐槽














