TP5.1获取微信小程序用户手机号码

composer安装EasyWeChat

$ composer require overtrue/wechat:~4.0 -vvv

控制器

    /**
     * 获取微信小程序手机号码
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function getPhone()
    {
        //下面三个参数由小程序前端传
        $iv            = $this->request->param('iv');
        $encryptedData = $this->request->param('encryptedData');
        $code          = $this->request->param('code');

        $config = [
            'app_id'        => "XXXXXX",
            'secret'        => "XXXXXX",
            // 下面为可选项
            // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file'  => __DIR__ . '/wechat.log',
            ],
        ];
        $app    = Factory::miniProgram($config);
        //code换取session_key和openid
        $session = $app->auth->session($code);

        if (!empty($session['errcode'])) {
            //获取session_key和openid报错
            echo $session['errmsg'];die;
        }

        $decryptedData = $app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
        
        //用户手机号码
        echo $decryptedData['phoneNumber'];die;
    }

Pasa吴技术博客
请先登录后发表评论
  • latest comments
  • 总共0条评论