微信小程序获取手机号码 PHP/前端代码

小程序端代码

// 首先需要通过wx.login()方法获取code,然后从后端换取session_key,不要获取按钮时获取可能会导致登录态失效 
// index.js
  onLoad: function(i) {
    let that = this; 
    wx.login({
      success:login=>{
        getApp().request({
          s:'User.getSesson',
          code:login.code
        }).then(res=>{ 
          that.setData({
            session_key: res.data.data.session_key,
          });
        }); 
      }
    })
  }, 

	// 授权获取手机号	
  getPhoneNumber: function(phone) {
    getApp().request({
      's': 'User.getPhone', 
      session_key: that.data.session_key,
      encryptedData: phone.detail.encryptedData,
      iv: phone.detail.iv,
    }).then(res => {
      if (res && res.data && res.data.data) {
        // 解密手机号 res.data.data.phoneNumber
      } else {
        wx.showModal({
          title: '提示',
          content: '网络异常,请重新获取手机号',
        })
      }
    }); 
  },
//app.js 
  request: function(param, methods = 'post') {
    return new Promise(success => {
      wx.request({
        method: methods ? methods : 'post',
        url: 'https://yld.angyakeji.com/www/public/index.php',
        data: param,
        complete: function(res) {
          success(res);
        }
      })
    });
  },

PHP

// 获取session
    public function getSesson()
    {
        header("Content-Type:text/html;charset=utf8");
        header("Access-Control-Allow-Origin: *"); //解决跨域
        header('Access-Control-Allow-Methods:POST'); // 响应类型  
        header('Access-Control-Allow-Headers:*'); // 响应头设置 
        error_reporting(E_ALL);
        $code = $_REQUEST['code'];
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx231bd3f08954da9e&secret=edf8c4929f2ad86db08e0cd3c588a14c&js_code=' . $code . '&grant_type=authorization_code';
        $html = file_get_contents($url);   
        $html = json_decode($html);
        return  $html;
    }

// 解密手机号
    public function getPhone()
    { 
        $aesKey = base64_decode($_REQUEST['session_key']);

        $aesIV = base64_decode($_REQUEST['iv']);

        $aesCipher = base64_decode($_REQUEST['encryptedData']);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        return  json_decode($result, true);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值