微信小程序通过code换取手机号

一、调用小程序验证组件,这两个组件都是可以文档地址
在这里插入图片描述
二、首先还是得先拿到code
(1)、必须在手机端去执行,开发者工具获取不到code。解决办法:将拿到的code在页面上渲染出来在复制一下就好了。
(2)、注意:有时候拿到的code是失效的,所以我们要提前login或者在回调中先使用checkSession进行登录状态检查。
在这里插入图片描述
三、服务端执行解析 文档地址


    public function getPhone(Request $request)
    {
        $code = $request->input('code');
        $uri = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$this->getAccessToken();
        //客户端获取并传过来
        $options = [
            'body' => json_encode(['code' => $code]),
            'headers' => ['Content-Type' => 'application/json']
        ];
        $response = (new \GuzzleHttp\Client)->post($uri, $options);
        $body = $response->getBody();
        $result = json_decode((string)$body, true);
        if ($result['errcode'] == 0) {
            return response()->json(["code" => 200, 'data' => $result['phone_info']]);
        }
        return response()->json(["code" => 201, 'data' => $result]);
    }

    public function getAccessToken()
    {
        $uri = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET';
        $response = (new \GuzzleHttp\Client)->get($uri);
        $body = $response->getBody();
        $result = json_decode((string)$body, true);
        if (!empty($result['access_token'])) {
            return $result['access_token'];
        }
        return "";
    }

四、执行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值