小程序+php获取用户手机号

思路: 设置一个按钮添加open-type="getPhoneNumber"和bindgetphonenumber="myGetPhone",绑定一个方法,接收一个参数e,通过点击按钮获取用户的code凭证,传递给php,php调用自己的方法getWxPhoneNumber(),并把接收到的code保存为json格式,同时调用自己的方法getWxToken()获取access_token,然后发送post请求获取用户手机号,返回给小程序。

前端小程序代码:


<button 
    class="authbtn" 
    open-type="getPhoneNumber" 
    type="primary" 
    bindgetphonenumber="myGetPhone"
    >获取手机号
</button>
<view style="height: 80px;width: 750rpx;line-height: 80px;">
    code获取手机号:{{phone}}
</view>

小程序内js代码:


myGetPhone(e) {
    //console.log(e.deatil.code)
    wx.request({
      url: `https://xxxxxxx.xxx/wxgetphonenumber.php?phone_code=${e.detail.code}`,
      success: (res) => {
        console.log(res)
        this.setData({
          phone: res.data.phone.phoneNumber
        })
      }
    })
  },

php代码使用的curl扩展库来发送post请求,获取手机号:


// 获取access_token 
// return string
function getWxToken($appid, $secret)
{
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;

    $token = json_decode(file_get_contents($url, true), true);

    $token = $token['access_token'];

    return $token;
}


// 获取手机号 和access_token
// return array
function getWxPhoneNumber($code, $appid, $secret)
{
    $token = getWxToken($appid, $secret);
    $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;

    $data = json_encode(["code" => $code]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);        // 发送post请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 传入post参数

    $res = curl_exec($ch);
    curl_close($ch);

    $arr = [
        'access_token' => $token,
        'phone' => json_decode($res,true)['phone_info']
    ];
    return $arr;
}

php接收前端数据,调用上面的方法获取手机号代码:

/**
 * 
 * 接收前端传参 
 * 
 */

$appid = "xxxxxxxxxxxxxx";
$secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';

$code['openid_code'] = $_REQUEST['openid_code'];
$code['phone_code'] = $_REQUEST['phone_code'];

// 请求手机号和access_token
if (!empty($code['phone_code'])) {
    $rs = getWxPhoneNumber($code['phone_code'], $appid, $secret);

    echo json_encode($rs);
    exit;
}

返回数据截图:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值