我正在使用codeigniter MVC框架登录到我的网站使用谷歌客户端库。一切都很好,除了$client->getAccessToken()
时,谷歌重定向与代码,我做了以下代码。$client->getAccessToken()
返回空值。这是我的代码控制器函数一。在这个函数中,我设置我的凭据创建authUrl。
public function login()
{
// Include two files from google-php-client library in controller
include_once APPPATH . 'third_party/google-api-php-client/vendor/autoload.php';
// Store values in variables from project created in Google Developer Console
$client_id = 'XXXXXX';
$client_secret = 'XXXXX';
$redirect_uri = 'path/to/mysite/login/loginGoogle';
$simple_api_key = 'XXXXXXX';
// Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("mysite");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$authUrl = $client->createAuthUrl();
$data['authUrl'] = $authUrl;
$this->load->view('login',$data);
}
之后,当谷歌认证和重定向到我的重定向URI,这是另一个控制器功能,这是下面给出的。和问题是在这个功能。
public function loginGoogle()
{
// Include two files from google-php-client library in controller
include_once APPPATH . 'third_party/google-api-php-client/vendor /autoload.php';
$client_id = 'XXXXXX';
$client_secret = 'XXXXX';
$redirect_uri = 'path/to/mysite/login/loginGoogle';
$simple_api_key = 'XXXXXXX';
// Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("mysite");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$objOAuthService = new Google_Service_Oauth2($client);
// Add Access Token to Session
if(!isset($_SESSION['access_token'])){
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$token = $client->getAccessToken();
$_SESSION['access_token'] = $token;
print_r($this -> session -> userdata());exit;
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
// Set Access Token to make Request
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
// Get User Data from Google and store them in $data
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
$data['userData'] = $userData;
$_SESSION['access_token'] = $client->getAccessToken();
}}
这里,在第二个函数getAccessToken中,什么也不返回,且Google抛出expection。
2条答案
按热度按时间esbemjvw1#
看起来你从来没有得到过刷新令牌。有两种不同的令牌,访问令牌大约每隔几个小时过期一次,但刷新令牌只在重定向请求用户权限时发送一次。它需要存储在安全的地方,以便将来用于刷新访问令牌。下面是我的codeigniter代码访问Google API(这将替换loginGoogle函数中的if语句:
ix0qys7i2#
如果您正在PLESK上运行,则可能需要将
/var/lib/php/session
上的权限更改为1777
。