4

I want to upload files to Google Drive using the API, but I need to do this using a cron job (autobackup of webfiles+sql to Google drive).

That means (I suppose) that I need to authenticate using something else than the user interaction method.

The example that I have been using: https://developers.google.com/api-client-library/php/auth/web-app to get me going, and its working with user authenticating.

I would appreciate some tips on how to do this without user interaction, so it can run on a cronjob.

Here are the PHP code for authenticate and upload file (working example with manual user auth and single file upload)

  <?php

    require_once 'google-api-php-client/vendor/autoload.php';

    /* Config */
    $servername = 'content here';
    $redirect_uri = 'https://example.com/';

    $client = new Google_Client();
    $client->setAuthConfig('client_manual_authentiation.json');
    $client->addScope(Google_Service_Drive::DRIVE);

    if(isset($_SESSION['access_token']) && $_SESSION['access_token']) {

        $client->setAccessToken($_SESSION['access_token']);
        $drive = new Google_Service_Drive($client);

        foreach($drive->files->listFiles(array("q" => "name = '{$servername}'"))->getFiles() as $key => $element){

            if($element->name == $servername){

                //create todays folder on Google Drive
                $today_folder_meta = new Google_Service_Drive_DriveFile(array(
                    'name' => 'myfile.txt',
                    'mimeType' => 'application/vnd.google-apps.folder',
                    'parents' => array($element['id'])
                ));

                $today_folder = $drive->files->create($today_folder_meta, array(
                    'fields' => 'id'
                ));

            }
        }
    }else{

        if (!isset($_GET['code'])) {
            $auth_url = $client->createAuthUrl();
            header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
        } else {
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
        }
    }

?>
Grokify
  • 15,092
  • 6
  • 60
  • 81
sdfgg45
  • 1,232
  • 4
  • 22
  • 42
  • see https://stackoverflow.com/questions/19766912/how-do-i-authorise-an-app-web-or-installed-without-user-intervention/19766913#19766913 – pinoyyid Jul 01 '18 at 21:44

1 Answers1

2

To do this, you want to create a Google OAuth2 Service Account. You can then download a set of JSON credentials that your app will use to authenticate without user interaction.

This is described in the following article:

Using OAuth 2.0 for Server to Server Applications

You will then be able to download credentials like the following to use in your app:

{
    "type":"service_account",
    "project_id":"your-project-id",
    "private_key_id":"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
    "private_key":"-----BEGIN PRIVATE KEY-----\nMIIEv...4XIk=\n-----END PRIVATE KEY-----\n",
    "client_email":"foobar@bazqux.iam.gserviceaccount.com",
    "client_id":"12345678901234567890",
    "auth_uri":"https://accounts.google.com/o/oauth2/auth",
    "token_uri":"https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/foobar%40bazqux.iam.gserviceaccount.com"
}

Here is a Google PHP example of how to use this:

You can create the Service Account in the Google API Console as shown here:

enter image description here

Grokify
  • 15,092
  • 6
  • 60
  • 81
  • Allright, right now I use the OAuth, so i will try the service one. I do run a json file now: $client->setAuthConfig('client_secret.json'); so i guess I need to replace this with service key? – sdfgg45 May 31 '18 at 10:09
  • Yes, you should be able to just swap the file. Note the JSON I included above has the following property: `"type":"service_account"`. The Google PHP service account example code I linked above includes the following: `$client->setAuthConfig($credentials_file);` on line 45. I've used service accounts for the Google Drive, Sheets, Slides and Speech APIs. – Grokify May 31 '18 at 10:13
  • I will try it ASAP. – sdfgg45 May 31 '18 at 10:15
  • Do i have to use app service account or compute service account? – sdfgg45 May 31 '18 at 13:19
  • I haven't seen any differentiation for app and compute service accounts. Can you point to where you see this? I create them here using "Google Cloud Platform - IAM & admin": https://console.cloud.google.com/iam-admin/serviceaccounts/ . Google's documentation for various uses all seem to lead to this one place, e.g. https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances , https://cloud.google.com/iam/docs/service-accounts , etc. – Grokify May 31 '18 at 17:00
  • When replacing the file web secret key (OAuth 2.0) with the service key i get: Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI. Code is updated in the main text aboue. – sdfgg45 Jun 06 '18 at 10:30