微信小程序获取用户手机号

官方文档地址如下

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

实现思路比较简单,以下是我的js代码

getPhoneNumber: function (e) {
    var that=this;
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '未授权,请手动填写',
        success: function (res) { }
      })
    } else {
      wx.request({
        url: app.globalData.url + '/routine/ydj/get_phone?uid=' + app.globalData.uid,
        method: 'POST',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
        },
        success: function (res) {
          if (res.data.code == 200) {
            that.setData({
              userphone : res.data.data.phoneNumber
            })
          }
        }
      })

    }
  }

接口代码

    public function get_phone($uid,$encryptedData,$iv)
    {
        $sessionKey=Db::table('ydj_wechat_user')->where('uid',$uid)->value('session_key');
        if (strlen($sessionKey) != 24) {
            return JsonService::fail('sessionKey错误!');
        }
        $aesKey=base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            return JsonService::fail('iv错误!');
        }
        $aesIV=base64_decode($iv);
        $aesCipher=base64_decode($encryptedData);
        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode( $result,true);
        Db::table('ydj_user')->where('uid',$uid)->update(array('phone'=>$dataObj['phoneNumber']));
        return JsonService::successful('请求成功',$dataObj);
    }

 

你可能感兴趣的:(小程序)