问题
I have been trying for the last few hours to print my refresh_token from the initial Google API call (even after de-authorizing and re-authorizing as others have suggested doing) but I still am not having any luck...the API works as expected but I want to set up refreshing functionality so my user does not lose access after token expires (resulting in errors).
Currently, the below code sets $_SESSION['refresh_token'] to null.
Any help would be greatly appreciated as I have been banging my head against the keyboard for quite some time...
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:
In getOauth() function add the following
$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
来源:https://stackoverflow.com/questions/33355635/google-api-refresh-token