PHP Quickstart

Complete the steps described in the rest of this page, and in about five minutes you'll have a simple PHP command-line application that makes requests to the Google Apps Script Execution API.

Prerequisites

To run this quickstart, you'll need:

  • PHP 5.4 or greater with the command-line interface (CLI) and JSON extension installed.
  • The Composer dependency management tool.
  • Access to the internet and a web browser.
  • A Google account with Google Drive enabled.
  • A target Apps Script to call with the API.

Step 1: Turn on the Google Apps Script Execution API

  1. Open your target Apps Script in the editor and select Resources > Cloud Platform project.
  2. In the dialog that opens, click on the blue link (that starts with your script's name) at the top to open the console project associated with your script.
  3. The left sidebar should say API Manager. If it does not, click the icon in the upper-left to open a side panel and select API Manager. Select Library in the left sidebar.
  4. In the search bar under the Google APIs tab, enter "Google Apps Script Execution API". Click the same name in the list that appears. In the new tab that opens, click Enable API.
  5. Click Credentials in the left sidebar.
  6. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
  7. Select the application type Other, enter the name "Google Apps Script Execution API Quickstart", and click the Create button.
  8. Click OK to dismiss the resulting dialog.
  9. Click the file_download (Download JSON) button to the right of the client ID.
  10. Move this file to your working directory and rename it client_secret.json.

Step 2: Install the Google Client Library

Run the following command to install the library using composer:

php composer.phar require google/apiclient:1.1.x-dev

See the library's installation page for the alternative installation options.

Step 3: Set up the sample

Create a file named quickstart.php in your working directory and copy in the following code:


<?php
require_once __DIR__ . '/vendor/autoload.php';


define('APPLICATION_NAME', 'Google Apps Script Execution API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/script-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/script-php-quickstart.json
define('SCOPES', implode(' ', array(
  "https://www.googleapis.com/auth/drive")
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

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

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Script($client);

$scriptId = 'ENTER_YOUR_SCRIPT_ID_HERE';

// Create an execution request object.
$request = new Google_Service_Script_ExecutionRequest();
$request->setFunction('getFoldersUnderRoot');

try {
  // Make the API request.
  $response = $service->scripts->run($scriptId, $request);

  if ($response->getError()) {
    // The API executed, but the script returned an error.

    // Extract the first (and only) set of error details. The values of this
    // object are the script's 'errorMessage' and 'errorType', and an array of
    // stack trace elements.
    $error = $response->getError()['details'][0];
    printf("Script error message: %s\n", $error['errorMessage']);

    if (array_key_exists('scriptStackTraceElements', $error)) {
      // There may not be a stacktrace if the script didn't start executing.
      print "Script error stacktrace:\n";
      foreach($error['scriptStackTraceElements'] as $trace) {
        printf("\t%s: %d\n", $trace['function'], $trace['lineNumber']);
      }
    }
  } else {
    // The structure of the result will depend upon what the Apps Script
    // function returns. Here, the function returns an Apps Script Object
    // with String keys and values, and so the result is treated as a
    // PHP array (folderSet).
    $resp = $response->getResponse();
    $folderSet = $resp['result'];
    if (count($folderSet) == 0) {
      print "No folders returned!\n";
    } else {
      print "Folders under your root folder:\n";
      foreach($folderSet as $id => $folder) {
        printf("\t%s (%s)\n", $folder, $id);
      }
    }
  }
} catch (Exception $e) {
  // The API encountered a problem before the script started executing.
  echo 'Caught exception: ', $e->getMessage(), "\n";
}

Be sure to also replace the placeholder ENTER_YOUR_SCRIPT_ID_HERE with the script ID of your target script.

Step 4: Run the sample

Run the sample using the following command:

php quickstart.php

The first time you run the sample, it will prompt you to authorize access:

  1. Browse to the provided URL in your web browser.

    If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.

  2. Click the Accept button.
  3. Copy the code you're given, paste it into the command-line prompt, and press Enter.

Notes

  • Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.
  • The authorization flow in this example is designed for a command-line application. For information on how to perform authorization in a web application, see Using OAuth 2.0 for Web Server Applications.

Further reading

Send feedback about...

Apps Script
Apps Script