Google API刷新令牌

时间:2015-10-26 21:06:45

标签: php oauth-2.0 google-api google-analytics-api google-api-php-client

我最近几个小时一直在尝试从最初的Google API调用中打印我的refresh_token(即使在取消授权和重新授权后,正如其他人建议的那样)但我仍然没有运气...... API按预期工作,但我想设置刷新功能,以便我的用户在令牌过期后不会失去访问权限(导致错误)。

目前,以下代码将$ _SESSION [' refresh_token']设置为null。

任何帮助都会非常感激,因为我一直在用键盘撞击键盘已经有一段时间......

private function googleAnalyticsClient(){
    App::import('Vendor', 'google-api-php-client', array('file' => 'autoload.php'));
    $client = new Google_Client();
    $client->setAuthConfigFile(__DIR__ . '/client_secrets.json'); 
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');
    $client->addScope('https://www.googleapis.com/auth/analytics.readonly');

    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        $client->setAccessToken($_SESSION['access_token']);
        $analytics = new Google_Service_Analytics($client);
        return $analytics;
    } else {
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
}

public function getOauth()
{
    App::import('Vendor', 'google-api-php-client', array('file' => 'autoload.php'));

    // Create the client object and set the authorization configuration
    // from the client_secrets.json you downloaded from the Developers Console.
    $client = new Google_Client();
    $client->setAuthConfigFile(__DIR__ . '/client_secrets.json');
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks');
    $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

    // Handle authorization flow from the server.
    if (! isset($_GET['code'])) {
      $auth_url = $client->createAuthUrl();
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
      $client->authenticate($_GET['code']);
      $_SESSION['access_token'] = $client->getAccessToken();
      $_SESSION['refresh_token'] = $client->getRefreshToken();
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/dashboard/tpstats';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
}

1 个答案:

答案 0 :(得分:1)

在getOauth()函数中添加以下内容

$client = new Google_Client();
$client->setAuthConfigFile(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);    
$client->setAccessType('offline'); //To fetch refresh token(Refresh token issued only first time)
$client->setApprovalPrompt('force'); //Adding this will force for refresh token