如何在微信小程序中获取用户手机号码

发布于 2020-03-29 12:11:26

1、在小程序中使用button上启用获取手机号码事件

<button class="tellBinding" open-type='getPhoneNumber' bindgetphonenumber='onGetPhoneNumber' wx:if="{{!(userInfo.unique_phone && userInfo.unique_phone != 'undefined')}}">手机绑定</button>

2、JS文件中编写向后端发送解密手机号码的逻辑代码

onGetPhoneNumber: function (e) {
    let _this = this;
    if (!e.detail.encryptedData) {
      return;
    }
    
    App._post_form('user/bindmobile', {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
    }, (result) => {
      App.showSuccess(result.msg);
      _this.setData(result.data);
    });
}

3、后端编写解密手机号码的代码

public function bindmobile ()
{
    $user = $this->getUser(false);
    if(!$session = Cache::get($this->request->param('token'))){
        return $this->renderError('登录状态已失效,请重新登录');
    }
    $encry_data = $this->request->param('encryptedData','');
    $iv = $this->request->post('iv','');
    if(empty($encry_data) || empty($iv)){
        return $this->renderError('请求参数有误');
    }

    $wxConfig = Wxapp::getWxappCache();
    $WXBizDataCrypt = new wxBizDataCrypt($wxConfig['app_id'],$session['session_key']);
    if(0 != $res = $WXBizDataCrypt->decryptData($encry_data,$iv,$data)){
        return $this->renderError('数据解密错误'.$res);
    }else{
        $mobile_info = json_decode($data,true);
        //绑定手机
        if(User::where('unique_phone','=',$mobile_info['phoneNumber'])->where('is_delete','=',0)->count()){
            return $this->renderError('该手机号已绑定其他账号');
        }else{
            $user->unique_phone = $mobile_info['phoneNumber'];
            $user->save();
            return $this->renderSuccess(['userInfo'=>$user]);
        }

    }
}
代码来源:qingdian

Bug天天改,头发日日疏,码字不易,如果有帮助到你,就点击"下方感谢"支持一下把.

©声明:本站所有文章,如无特殊说明或标注,均为izhnagbo.cn原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。本文链接 https://www.izhangbo.cn/article/33.html
0 条评论

学习
记录

发布
问题