Search code examples
phpgoogle-apicrongoogle-oauthgoogle-api-php-client

Using PHP Cron and Google API access


I need to use CRON for updating one of my Google Sheets by php. But what is the proper way to do that in 2018? Should I select in Google Cloud API call for web applications or for platform without UI (but then access only for data generated by app)? And should I create credentials as a service account? What about refreshing tokens when using a service account access?

Generally it will be my private functionality, only for me. My task should be realized by cron, but I'm completely out of this topic, I've never used Google API before. I've read many docs, but the most of them is about standard oauth2 access with user prompt (even from time to time). Maybe someone could recommend some good practices in this case?

PS. I'm using googleapis/google-api-php-client


Solution

  • The first thing you need to do is decide whos data you are going to be accessing.

    • is this your account or your sheet something that you as the developer have access to.
    • is this a sheet owned by another user account.

    If this is the first option then you should take advantage of using a service account. The google apis php client library will handle refreshing the access foryou you will not need to worry about it. Simply take the service account email address and share the sheet you want it to access with the service account user.

    If this is the second option and you need access to a users account. Then you will need to go with browser based probably. The user will need to authenticate your application once you can save the refresh token and then the php client library will help you by getting a new access token when ever it needs. You will need to watch this solution as refresh tokens should be long lived and not expire however in my experience they can expire from time to time and you will need to request authorization again from the user.

    require_once __DIR__ . '/vendor/autoload.php';
    // Use the developers console and download your service account
    // credentials in JSON format. Place the file in this directory or
    // change the key file location if necessary.
    putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
    /**
     * Gets the Google client refreshing auth if needed.
     * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
     * Initializes a client object.
     * @return A google client object.
     */
    function getGoogleClient() {
        return getServiceAccountClient();
    }
    /**
     * Builds the Google client object.
     * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
     * Scopes will need to be changed depending upon the API's being accessed. 
     * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
     * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
     * @return A google client object.
     */
    function getServiceAccountClient() {
        try {   
            // Create and configure a new client object.        
            $client = new Google_Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope([YOUR SCOPES HERE]);
            return $client;
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
    

    code ripped from ServiceAccount.php