首页 > 解决方案 > 没有获得令牌谷歌 Oauth

问题描述

我正在尝试使用 google API 登录,但由于某种原因,两者$_GET["code"]都是$this->request->getVar('code')空的,因此我无法获取我的令牌。我已经尝试过$_GET["code"]$this->request->getVar('code')但没有任何效果:

错误图像 第二个图像

我正在关注这个视频教程:点击这里

public function signup_with_gmail() {
   
    require_once APPPATH.'Libraries\vendor\autoload.php';
    $google_client = new \Google_Client();
    //$google_client->setApplicationName("pharma");
    $google_client->setClientId('clientID');
    $google_client->setClientSecret('SECRET');
    $google_client->setRedirectUri('http://localhost/pharma/User/sign_in');
    $google_client->addScope('email');
    $google_client->addScope('profile');
    
    print_r($this->request->getVar('code') === NULL);
    print_r($_GET['code']);
    if ($this->request->getVar('code') != NULL) {
        $token = $google_client->fetchAccessTokenWithAuthCode($this->request->getVar('code'));
        if(!$token['error']){
            $google_client->setAccessToken($token['access_token']);
            $session->set('access_token', $token['access_token']);
            //now get profile data create another object
            $google_service = new \Google_Service_Oauth2($google_client);
            $data = $google_service->userinfo->get();
            print_r($data);
        }
    }
    print_r($data);
}

标签: google-oauthcodeigniter-4

解决方案


$this->request->getVar('code')只有当您点击使用创建的 URL 时,才会生成其中的代码$google_client->createAuthUrl();

所以,你可以这样做......

在控制器中写入 $data['loginButton'] = $google_client->createAuthUrl();

将此传递给“使用 Google 登录”按钮$data['loginButton']的锚标记中的视图。

现在,当您单击“使用 Google 登录”按钮时,它将重定向回相同的localhost.com/loginURL,但这次您将在 URL 中拥有代码。因此,您可以使用它来获取它$this->request->getVar('code')并遵循该过程的其余部分。

  • 请确保ClientIdClientSecret等所有详细信息均正确无误
  • 并更新到最新"google/apiclient": "^2.10"

推荐阅读