微信小程序获取手机号

该代码段展示了如何在PHP中使用微信API获取访问令牌(access_token),然后通过此令牌获取用户授权的小程序内手机号。主要涉及curl发起HTTP请求和处理JSON响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	public function getPhoneNumber(Request $request)
    {
        $token = $this->getAccessToken();
        $phone = $this->getPhone($request->param('code'),$token['access_token']);
        if ($phone['errcode'] == -1){
            return error('获取手机号失败');
        }

        return success($phone);
    }

    public function getAccessToken(){
        $wechat = config('easywechat.easywechat');
        $appid = $wechat['app_id']; //小程序appid
        $secret = $wechat['secret']; //小程序开发秘钥
        $get_token_url = 'https://api.weixin.qq.com/cgi-bin/token?appid=' . $appid . '&secret=' . $secret . '&grant_type=client_credential';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $get_token_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);

        return json_decode($res, true);
    }

    public function getPhone($code , $token){
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;
        $request_data = array(
            'code' => $code
        );
        $return = json_decode($this->https_request($url, $request_data, 'json'), true);
        return $return;
    }

    public function https_request($url, $data, $type)
    {
        if ($type == 'json') {
            $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
            $data = json_encode($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值