Exporting Google Sheets in the v2 PHP SDK (google/apiclient v2.0.0-RC4)
I’ve been playing around with the new google/apiclient (v2.0.0) for use with Google Drive and ran into some issues figuring out how to make use of the ability to export, for example, a Google Sheet as a CSV or Excel spreadsheet.
- $file_id refers to the file ID of a Google Sheet
- $path_to_keyfile contains the path to the JSON credentials for a service account from the Google Cloud Console
- $sub_account contains the email address of a user in our domain
// Setup the client $client = new Google_Client; $client->setAuthConfig($path_to_keyfile); // setup service account credentials $client->setScopes(array('https://www.googleapis.com/auth/drive')); $client->setSubject($sub_account); // act on behalf of someone else $api = new \Google_Service_Drive($client); // Grab the file metadata $file = $api->files->get($file_id); $links = $file->getExportLinks(); $export_uri = $links['text/csv']; // Export the document $http = $client->getHttpClient(); $response = $http->get($export_uri, array( 'auth' => 'google_auth' )); // $response->getBody()->getContents() returns a string containing the CSV
The important bit here is the
'auth' => 'google_auth' request option in the
get() call. Without that, the
GuzzleHttp\Client middleware that the Google SDK registers will not append the proper
Authorization header to the request, and Google will not consider your request authorized. I’ve not found this documented anywhere, but discovered it by looking at the implementation of the
Google\Auth\Middleware\AuthTokenMiddleware class contained within the google/auth package—specifically, at this.
The process that got me to this point also uncovered some rather annoying issues that result from this kind of application of the middleware concept. The short version: the order in which middleware is pushed onto the stack is important if you’re going to try to debug API calls using some sort of a logging middleware with the Google PHP SDK.