前言

以手机号权限询问为例子,总结小程序权限询问业务。

权限询问注意点

  1. 手机号获取api是需要通过点击按钮实现的;
  2. 用户拒绝一次以后,就不能再通过这个按钮唤醒了。 所以,我们一般需要封装一个自定义弹框,在必须要使用手机号权限的地方可以多次弹出。

流程

1. 权限判定

首先,通过自定义的权限标识判断当前权限获取状态

// 点击需要唤起手机号的地方
handleTask(e) {
  // 已有权限
  if(wx.getStorageSync('hadAuth')){
    ...
  }
  // 未有权限,唤起自己的弹框
  else{
    this.setData({
      isPhone: true
    })
  }
},

2. 自定义组件

封装一个手机弹框的自定义组件,给这个组件分别绑定同意事件和拒绝事件。

img

// 同意绑定
clickToBindPhone: function(e){
  // 手机验证接口
  this.closeBox()
  this.phoneAuth(e.detail.encryptedData,e.detail.iv)
},

img

(这个询问框才是真正的微信询问框,如果用户拒绝。下次我们还回生成新的询问事件触发按钮。)

3. 父子组件传值

由于关闭窗口的事件是要由父组件进行关闭的,所以这里的的closebox事件必须传递到外部,也就是

/** 子组件中 **/
// 关闭盒子
closeBox: function(){
  // 触发外部事件,并传递数据
  var detail = {
    ifPhone: false
  };
  this.triggerEvent('showBox', detail, { bubbles: false, composed: false });
},

/** 父组件中 **/
// 询问手机
<bindphone ifPhone_="" wx:if="" bind:showBox='showClick'></bindphone>

//组件接受操作
showClick: function (e) {
  this.setData({
    isPhone: e.detail.ifPhone
  })
}

4. 询问手机号

询问手机号,需要把打开询问的按钮类型设置为getPhoneNumber,这样,当我们点击同意时,回调函数自带的参数中,就会有请求到的相关信息encryptedData和iv

<button class="st-bp-btn-2" open-type="getPhoneNumber" bindgetphonenumber="clickToBindPhone">绑定</button>

// 同意绑定
clickToBindPhone: function(e){
  // 手机验证接口
  this.closeBox()
  this.phoneAuth(e.detail.encryptedData,e.detail.iv)
},

5. 把encryptedData和iv传回微信接口服务器,就能获得授权并拿到手机号了。

// 手机号业务登录
phoneAuth(encryptedData,iv){
  // 调手机登录接口
  http.httpPromise1.postPromise('/getphone?encryptedData='+encryptedData+'&iv=' + iv)
  .then(res => {
    ...
  })
}