Search code examples
phpoauth-2.0google-apigoogle-oauthgoogle-api-php-client

How to store google api client object (access_token array) with offline access and reuse it


Following google-api-php-client => documentation I managed to get the $token = $client->fetchAccessTokenWithAuthCode($authorization_code); array:

$token array:6 [▼ ▼
  "access_token" => "***"
  "expires_in" => 3599
  "refresh_token" => "***"
  "scope" => "https://www.googleapis.com/auth/drive openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
  "token_type" => "Bearer"
  "id_token" => "***"
]

I used $client->setAccessType("offline"); so I got a "refresh_token" => "***"

Documentation mentions:

If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access.

I understand that in order to access Google API without the user interaction I would need to do:

$client = new Google_Client();
$client->setAccessToken($token);

Where $token is the array above. And then I can do api calls.

1) How should I store this $token array? Do I need to store only the refresh_token? And if so, how do I rebuild the $token array so that the setAccessToken() method will accept it?

2) Where should I store the array data? In the database or somewhere else?


Solution

  • You really only need to store the refresh token. Where you store it is up to you but it should be some place secure and you should denote the user who the refresh token is attached to. So that you can be sure that you dont show user a user b data because you mixed up their refresh tokens.

    I have been known to just store them in a folder.

    function getGoogleClient() {
        $client = getOauth2Client();
    
        // Refresh the token if it's expired.
        if ($client->isAccessTokenExpired()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
        }
    return $client;
    }