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

一、调用小程序验证组件,这两个组件都是可以文档地址

二、首先还是得先拿到code

(1)、必须在手机端去执行,开发者工具获取不到code。解决办法:将拿到的code在页面上渲染出来在复制一下就好了。

(2)、注意 :有时候拿到的code是失效的,所以我们要提前login或者在回调中先使用checkSession进行登录状态检查。

三、服务端执行解析 文档地址

java 复制代码
    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 "";
    }

四、执行结果

相关推荐
小溪彼岸2 天前
是时候给想做小程序的小伙伴泼盆冷水了
微信小程序
远山枫谷2 天前
一文理清页面/组件通信与 Store 全局状态管理
前端·微信小程序
木易士心3 天前
一文读懂:微信小程序云数据库直连原理与使用指南
微信小程序·serverless
明月_清风4 天前
小程序云函数:从入门到全栈的“降维打击”指南
前端·微信小程序·小程序·云开发
拉不动的猪4 天前
移动端调试工具VConsole初始化时的加载阻塞问题
前端·javascript·微信小程序
WangHappy6 天前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端7 天前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
icebreaker7 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker7 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
大米饭消灭者10 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro