Posted on Leave a comment

How to Insert data in Google Spreadsheet using PHP?

Source: http://karl.kranich.org/2015/04/16/google-sheets-api-php/

Google has been sending out messages saying that several of their APIs are going to be discontinued (for example, the Document List API).  As a result, I tried to modify my custom Google Spreadsheet-populating PHP script to use the new Drive API.  After way too much wasted time, I discovered that the Drive API can create sheets and read their metadata, but can’t add rows — for that we can keep using the Spreadsheets API.

I was successful at converting the authentication portion of my script from the old ClientLogin to OAuth with a Service Account (the script runs behind the scenes of a web site and populates a Google spreadsheet that the web site user has no knowledge of).

It wasn’t as simple as I’d hoped because the Google-provided PHP client for the Drive API doesn’t know about the Spreadsheets API.  I had to dig around the PHP libraries to piece together authentication codes and Google_Http_Requests.

So, if anyone else out there is interested in the combination of PHP, the Spreadsheets API, and OAuth with Service Accounts, this could save you some time.

The code is available in a public Gist at https://gist.github.com/karlkranich/cbbfbdf5825217b2976f

Here are the step-by-step instructions to get this to work:

Create the Service Account

  1. Browse to https://console.developers.google.com
  2. Click “Create Project”, make up a name, and click “Create”
  3. Click “API” in the left column, then click “Drive API” and then “Enable API”. This is not needed for the Spreadsheets API, but you might want to use the Drive API also.
  4. Click “Credentials” in the left column.
  5. In the OAuth section, click “Create new Client ID”
  6. Choose “Service Account” and click “Create Client ID”
  7. Save the generated json file
  8. Click “Generate new P12 key”, save the file, and note the password on the screen.
  9. Note the Client ID and Email address – we’ll use them later

Create a Spreadsheet and share with the Service Account

  1. Create a Google Spreadsheet to play with
  2. Share the Google sheet with the gserviceacount email address from above (give edit permissions).

Get the PHP Drive API Client

git clone https://github.com/google/google-api-php-client.git google-api-php-client

Modify and run sheets-api-test.php

  1. Get the script from https://gist.github.com/karlkranich/cbbfbdf5825217b2976f
  2. Fill in the Client ID and Email address from the Google Developer Console
  3. Fill in the File ID of your spreadsheet from the URL in Chrome (see image below)
  4. Uncomment various sections of the script to see how they work

Let me know if any of this doesn’t work or doesn’t make sense!

file-id

 

<?php
session_start();
include_once "google-api-php-client/examples/templates/base.php";
/************************************************
  Make an API request authenticated with a service
  account.
 ************************************************/
require_once realpath(dirname(__FILE__) . '/google-api-php-client/src/Google/autoload.php');
$client_id = 'get your own from google developer console';
$service_account_name = 'get your own from google developer console';  // email address
$key_file_location = 'download your own.p12'; //key.p12
echo pageHeader("Service Account Access");
if (strpos($client_id, "googleusercontent") == false
    || !strlen($service_account_name)
    || !strlen($key_file_location)) {
  echo missingServiceAccountDetailsWarning();
  exit;
}
$client = new Google_Client();
$client->setApplicationName("Sheets API Testing");
$service = new Google_Service_Drive($client);
/************************************************
  If we have an access token, we can carry on.
  Otherwise, we'll get one with the help of an
  assertion credential. In other examples the list
  of scopes was managed by the Client, but here
  we have to list them manually. We also supply
  the service account
 ************************************************/
if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds'),
    $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
// Get access token for spreadsheets API calls
$resultArray = json_decode($_SESSION['service_token']);
$accessToken = $resultArray->access_token;
// The file ID was copied from a URL while editing the sheet in Chrome
$fileId = '15byt2tfdaHmaEpdwd4UYGWs70Eaej8edkQ2dS8x4mIk';
// Section 1: Uncomment to get file metadata with the drive service
// This is also the service that would be used to create a new spreadsheet file
// $results = $service->files->get($fileId);
// var_dump($results);
// Section 2: Uncomment to get list of worksheets
// $url = "https://spreadsheets.google.com/feeds/worksheets/$fileId/private/full";
// $method = 'GET';
// $headers = ["Authorization" => "Bearer $accessToken"];
// $req = new Google_Http_Request($url, $method, $headers);
// $curl = new Google_IO_Curl($client);
// $results = $curl->executeRequest($req);
// echo "$results[2]\n\n";
// echo "$results[0]\n";
// Section 3: Uncomment to get the table data
// $url = "https://spreadsheets.google.com/feeds/list/$fileId/od6/private/full";
// $method = 'GET';
// $headers = ["Authorization" => "Bearer $accessToken", "GData-Version" => "3.0"];
// $req = new Google_Http_Request($url, $method, $headers);
// $curl = new Google_IO_Curl($client);
// $results = $curl->executeRequest($req);
// echo "$results[2]\n\n";
// echo "$results[0]\n";
// Section 4: Uncomment to add a row to the sheet
$url = "https://spreadsheets.google.com/feeds/list/$fileId/od6/private/full";
$method = 'POST';
$headers = ["Authorization" => "Bearer $accessToken", 'Content-Type' => 'application/atom+xml'];
$postBody = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"><gsx:gear>more gear</gsx:gear><gsx:quantity>99</gsx:quantity></entry>';
$req = new Google_Http_Request($url, $method, $headers, $postBody);
$curl = new Google_IO_Curl($client);
$results = $curl->executeRequest($req);
echo "$results[2]\n\n";
echo "$results[0]\n";

 

Source: http://karl.kranich.org/2015/04/16/google-sheets-api-php/