Skip to content

How to use "Service account" authorization (rather than user based access refresh tokens)

tamcy edited this page Aug 13, 2015 · 4 revisions

If you have a script or an app which always accesses the same spreadsheet to store data (perhaps from a website form) it is generally easier to use "Service account" authorization which doesn't require the user-authorization-redirect flow, nor the use of refresh tokens. Here is how to achieve it:

  1. Create the “Service Account” via Google Developer Console

  2. Download the P12 key file

  3. Note down the Client ID and Client Email which will be needed in the following steps

  4. Grant sharing permissions on any necessary Google Drive files/folders with the Client email address obtained above

  5. Gain an access token using the following PHP function:

    /**
     * Retrieves a Google API access token by using a P12 key file,
     * client ID and email address
     *
     * These three things may be obtained from 
     * https://console.developers.google.com/
     * by creating a new "Service account"
     */
    function getGoogleTokenFromKeyFile($clientId, $clientEmail, $pathToP12File) {
        $client = new Google_Client();
        $client->setClientId($clientId);
    
        $cred = new Google_Auth_AssertionCredentials(
            $clientEmail,
            array('https://spreadsheets.google.com/feeds'),
            file_get_contents($pathToP12File)
        );
    
        $client->setAssertionCredentials($cred);
    
        if ($client->getAuth()->isAccessTokenExpired()) {
            $client->getAuth()->refreshTokenWithAssertion($cred);
        }
    
        $service_token = json_decode($client->getAccessToken());
        return $service_token->access_token;
    }
  6. Pass that token when creating your new DefaultServiceRequest(getGoogleTokenFromKeyFile(..., ..., ...))