Update Token for Google Api Php Client

I use the Google API client to access Google Analytics. I want to access data offline, so I need an update token. How to get refresh_token?

+8
access-token google-analytics-api
source share
2 answers

try using the following code:

<?php require_once 'apiClient.php'; const REDIRECT_URL = 'INSERT YOUR REDIRECT URL HERE'; const CLIENT_ID = 'INSERT YOUR CLIENT ID HERE'; const CLIENT_SECRET = 'INSERT YOUR CLIENT SECRET'; const ANALYTICS_SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'; // Build a new client object to work with authorization. $client = new apiClient(); $client->setClientId(CLIENT_ID); $client->setClientSecret(CLIENT_SECRET); $client->setRedirectUri(REDIRECT_URL); $client->setScopes(array(ANALYTICS_SCOPE)); $client->setAccessType('offline'); $auth = $client->authenticate(); if ($client->getAccessToken()) { $token = $client->getAccessToken(); $authObj = json_decode($token); $refreshToken = $authObj->refresh_token; } ?> 
+7
source share

For PHP SDK client Google v2:

 php composer.phar require google/apiclient:^2.0 

You can try the PHP code to update accessToken as follows:

 <?php require_once __DIR__ . '/vendor/autoload.php'; define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json'); define('SCOPES', implode(' ', array( Google_Service_Analytics::ANALYTICS_READONLY) )); $client = new Google_Client(); $client->setApplicationName('YOUR APPLICATION NAME'); $client->setScopes(SCOPES); $client->setAuthConfig(CLIENT_SECRET_PATH); $client->setAccessType('offline'); // Input AccessToken from such as session or database $accessToken = json_decode('YOUR CURRENT ACEESS TOKEN'); $client->setAccessToken($accessToken); // Refresh the token if it expired. if ($client->isAccessTokenExpired()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); // Get RefreshToken as json which can be reused $refreshToken = json_encode($client->getAccessToken()); } 

Offline issue

In addition, if you want to preserve the existing behavior in your server applications, you need to set approval_prompt to force , otherwise you can get NULL returned from getRefreshToken (), which does not contain a Google document saying:

 $client->setApprovalPrompt('force'); 

Link Upcoming OAuth 2.0 Endpoint Changes

+1
source share

All Articles