Anubarak Anubarak - 1 month ago 21
PHP Question

PHP Google Analytics server to server OAuth get Refresh Token

I'm trying to get a

refresh token
from Google's authentication server for use with the Google Analytics API in a server side authentication with a
Service Account Credential
using the official Google PHP client library.

I'm able to create a
access token
and use that but currently I create a new token every time a user enters the page. I would like to decrease our traffic and get a refresh token to pass it to my JavaScript function.

gapi.analytics.auth.authorize({
serverAuth: {
access_token: accessToken <-refresh token is that even possible?
}
});


My current PHP code is:

$client = new \Google_Client();
$client->setApplicationName("Craft CMS Plugin");
$client->setAuthConfig($credentialPath);
$client->setAccessType('offline');
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);

$client->refreshTokenWithAssertion();

$this->analyticsAccount = new \Google_Service_Analytics($client);
$token = $client->getAccessToken();
$accessToken = $token['access_token'];


But there is no refresh_token. I can
var_dump
everything but I only find the access token. I already tried this Refresh Token for Google Api Php Client but it didn't work.

Can you please help me? How can I get one.
Thank you very much

Answer
  1. Service accounts work differently than Oauth2. They don't have refresh Tokens.
  2. JavaScript doesn't have the power to use Refresh Tokens.
  3. Why are you worried about traffic the service account should only be requesting authentication when it needs it once an hour. As far as traffic is concerned I would think this is minor.

Answer what you want to do is not possible if the service account is working leave it.