当前位置:   article > 正文

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

微信小程序通过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 "";
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/955051
推荐阅读
相关标签
  

闽ICP备14008679号