tp5.1 获取 小程序手机号

小程序代码 index.wxml
 

<view class='padding flex flex-direction'>
  <button wx:if="{{!phone}}" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"> 获取手机号码</button> 
</view>

小程序代码 index.js

// index.js
// 获取应用实例
const app = getApp()

Page({
  //通过绑定手机号登录
  getPhoneNumber: function (e) {
    if (e.detail.errMsg == "getPhoneNumber:fail user deny") return;
    //用户允许授权
    //  console.log("iv", e.detail.iv);
    //  console.log('encryptedData',e.detail.encryptedData);
    wx.showLoading()
    var self=this
    //1. 调用登录接口获取临时登录code
    wx.login({
    success: res => {
    if(res.code){
      //console.log('code:',res.code)
     //2. 访问登录凭证校验接口获取session_key、openid
     wx.request({
     //url: "https://api.weixin.qq.com/sns/jscode2session",
     data: {
    //  'appid': "wxcc41e47562b08129",
    //  'secret': "50e4379d67a6860d18157c53dc6ac3c2",
      'appid': "wxd22cef532a3df79c",
      'secret': "4818079ea093da7da789c910b5705a16",
      'js_code': res.code,
      'grant_type': "authorization_code"
     },
     method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
     header: {
     'content-type': 'application/json'
     }, // 设置请求的 header
    //  success: function (data) {
      //console.log("data", data)
    //  if(data.statusCode==200){
      // console.log('encryptedData',e.detail.encryptedData)
      // console.log('iv',e.detail.iv)
    //  console.log('session_key',data.data.session_key)
    //  console.log('iv',e.detail.iv)
    //  console.log('encryptedData',e.detail.encryptedData)

      //3. 解密
      // wx.request({
         url: 'http://jl.com/api/v1/login',//z自己的网址
        data: {
        'encryptedData': e.detail.encryptedData,
        'iv': e.detail.iv,
        //'sessionKey': data.data.session_key,
           'code':res.code,
        },
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {
        'content-type': 'application/json'
        }, // 设置请求的 header
        success: function (data2) {        
          console.log(data2)

        wx.hideLoading()
       //console.log(data2.data.phoneNumber)
        if (data2.statusCode == 200 && data2.data.phoneNumber) {
        self.setData({ 
        phone: data2.data.phoneNumber
        })
        }
      },
      fail: function (err) {
      console.log(err);
      }
     })
    //  }
    //  },
    //  fail: function (err) {
    //  console.log(err);
    //  }
    //  }) 
    }
     
    }
    })
    },
  // data: {
  //   motto: 'Hello World',
  //   userInfo: {},
  //   hasUserInfo: false,
  //   canIUse: wx.canIUse('button.open-type.getUserInfo')
  // },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})

tp5.1 后端 

    //此方法适用于 小程序 传code encryptedData iv三个参数过来
    public function memberLogin(Request $request){
        $code = $request->post("code");
        if($code){//微信登录
            $encryptedData =$request->post("encryptedData");
            $iv = $request->post("iv");
            $result = $this->curl_get(sprintf(config('setting.login_url'), config('setting.appid'), config('setting.appsecret'), "$code"));//获取用户的openid  和sessionkey   openid为用户的唯一标识,建议存储于数据库中
            //微信
            $wxResult = json_decode($result,true);
            $isbeing = (new MemberModel())->isbeing($wxResult['openid']);//根据openid查看此用户是否已注册  如果你只是获取手机号请忽略这一步
            $getPhone = $this->getPhone($session_key,$encryptedData,$iv);//此方法我会再下面给出
            $phones = json_decode($getPhone,true);//这就是你想要的手机号了
            
         
        } 
     
    }

curl_get 方法

     /**
     * @param string $url get请求地址
     * @param int $httpCode 返回状态码
     * @return mixed
     */
    function curl_get($url, &$httpCode = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }

 

getPhone 方法 这里的 WXBizDataCrypt 需要自己去下载 网址如下 :https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#method-decode

    //获取微信手机号
    protected function getPhone($sessionKey,$encryptedData,$iv){
        $appid = config('setting.appid');
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData,$iv,$data);
        if ($errCode == 0) {
            return $data;
        } else {
            return false;
        }
    }

我把它们放在了 extend/lib 下  注意修改   namespace 和 class WXBizDataCrypt 下载下来 lib 的名字为小写,class 后的为大写,要把它们命名一致才可以

 

这样就可以了

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值