微信小程序通过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 "";
    }

四、执行结果

相关推荐
WangHappy1 天前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端1 天前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
icebreaker2 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker2 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
大米饭消灭者5 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro
FliPPeDround6 天前
Vitest Environment UniApp:让 uni-app E2E 测试变得前所未有的简单
微信小程序·e2e·前端工程化
FliPPeDround6 天前
微信小程序自动化的 AI 新时代:wechat-devtools-mcp 智能方案
微信小程序·ai编程·mcp
吴声子夜歌6 天前
小程序——布局示例
小程序
码云数智-大飞6 天前
如何创建自己的小程序,码云数智与有赞平台对比
微信小程序
luffy54596 天前
微信小程序页面使用类似filter函数的wxs语法
微信小程序·小程序