Google OAuth2.0 php客户端使用刷新令牌交换访问令牌

时间:2014-01-21 11:15:07

标签: php google-api google-oauth access-token google-api-php-client

我正在尝试使用刷新令牌在访问令牌过期后交换访问令牌。但是,这样做的时候我一直面临着像“invalid_grant”这样的问题。

我想在尝试为新的access_token交换refresh_token时存在一些问题。我的代码如下所示:

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';

session_start();

$client = new Google_Client();
$client->setApplicationName("My app");
$client->setApprovalPrompt (auto); //prompt consent screen only for first time

//*********** Replace with Your API Credentials **************
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://example.com/oauth2callback');
$client->setDeveloperKey('xxx');
//************************************************************

$client->setScopes(array('https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email'));
$client->refreshToken(file_get_contents('refreshtoken.conf')); //retrieve refresh_token from file
$client->setAccessToken("refresh_token"); // I guess something is wrong here. I am trying to pass the refresh token to get a new access token but not sure if this is correct
$client->authenticate(); //after that authenticate user
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client); // Call the OAuth2 class for get email address

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['access_token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['access_token'])) {
  $client->setAccessToken($_SESSION['access_token']);
}

if ($client->getAccessToken()) {
  $user = $oauth2->userinfo->get();
  $me = $plus->people->get('me');
  $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2

  $optParams = array('maxResults' => 100);
  $activities = $plus->activities->listActivities('me', 'public', $optParams);

  $jsonarray = json_decode($client->getAccessToken());
  $arrGoogleAuth['access_token']=$jsonarray->access_token;
  $arrGoogleAuth['refresh_token']=$jsonarray->refresh_token;
    //filewrite

  $myFile = "refreshtoken.conf";
  $fh = fopen($myFile, 'w') or die("can't open file"); //write the json into refresh.conf
  fwrite($fh, $client->getAccessToken());
  fclose($fh);

  $_SESSION['access_token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
}
?>

2 个答案:

答案 0 :(得分:1)

如果不是PHP客户端库的专家,查看它的代码,我相信您的代码的以下子集/轻微更改应该足够(假设您以前成功请求了脱机访问,获得了刷新令牌)并保持$client->getAccessToken())的输出(应该是JSON对象):

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';

session_start();

$client = new Google_Client();
$client->setApplicationName("My app");
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://example.com/oauth2callback');
$client->setDeveloperKey('xxx');

$client->setScopes(array('https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email'));

$client->setAccessToken(file_get_contents('refreshtoken.conf'));
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client); 

基本上$client->getAccessToken()的输出包括访问令牌,刷新令牌(如果被授予),生存时间信息等。假设你坚持使用JSON blob,然后设置它,你可以继续使用Google_PlusService (和其他Google API) - 他们会自动检查访问令牌是否已过期,并根据需要使用刷新令牌获取新的访问令牌。

答案 1 :(得分:1)

if ($client->getAccessToken()) {

  if($client->isAccessTokenExpired()) {

     $client->authenticate();
     $NewAccessToken = json_decode($client->getAccessToken());
     $client->refreshToken($NewAccessToken->refresh_token);

    } else {

      $user = $oauth2->userinfo->get();
      $me = $plus->people->get('me');
      $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2

      $optParams = array('maxResults' => 100);
      $activities = $plus->activities->listActivities('me', 'public', $optParams);

      $_SESSION['access_token'] = $client->getAccessToken();
    }
} else {
  $authUrl = $client->createAuthUrl();
}