Checking or get access user to sheet by token (or user id) for export sheet content. Google api php client libary

Hi and sorry for my bad English. I add to website OAuth 2.0 with google api php client and thanks Karl for instructions , how get access to sheets with google api php client. My code: index.php :

<?php
define('ROOT',$_SERVER['DOCUMENT_ROOT']);
require_once ROOT.'/lib/google-api-php-client/vendor/autoload.php';
include_once ROOT.'/lib/google-api-php-client/examples/templates/base.php';

$client = new Google_Client();

putenv("GOOGLE_APPLICATION_CREDENTIALS=service-account-credentials.json");
if ($credentials_file = checkServiceAccountCredentialsFile()) {
    // set the location manually
    $client->setAuthConfig($credentials_file);
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
    // use the application default credentials
    $client->useApplicationDefaultCredentials();
} else {
    echo missingServiceAccountDetailsWarning();
    exit;
}
$client->setApplicationName(APPLICATION_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setAuthConfigFile('client_secrets.json');
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);

if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
    $fileId = 'FILE_ID_HERE';
    $tokenArray = $client->fetchAccessTokenWithAssertion();
    $accessToken = $tokenArray["access_token"];
    $service = new Google_Service_Drive($client);
    $results = $service->files->get($fileId);
    $url = "https://spreadsheets.google.com/feeds/list/$fileId/od6/private/full";
    $method = 'GET';
    $headers = ["Authorization" => "Bearer {$accessToken}", "GData-Version" => "3.0"];
    $httpClient = new GuzzleHttp\Client(['headers' => $headers]);
    $resp = $httpClient->request($method, $url);
    $body = $resp->getBody()->getContents();
    $code = $resp->getStatusCode();
    $reason = $resp->getReasonPhrase();
    echo "$code : $reason\n\n";
    echo "$body\n";
}
else 
{
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

oauth2callback.php:

<?php
define('ROOT',$_SERVER['DOCUMENT_ROOT']);
require_once ROOT.'/lib/google-api-php-client/vendor/autoload.php';
session_start();

$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

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();
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

If i enter:

$fileId = 'FILE_ID_HERE';//RULE for sheet in google docs spreadsheets: access only with invite

Then i get error: Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "errors": [ { "domain": "global", "reason": "notFound", "message": "File not found: [FILE_ID_HERE].", "locationType": "parameter", "location": "fileId" } ].....

But, i logged(Google account) with user who has invited for view this document!

And if i enter:

$fileId = 'FILE_ID_HERE';///RULE for sheet in google docs spreadsheets: access for all, who have link

All ok, and i get : 200 : OK all data document

Question. How get access to the sheet, if i logged(Google account) with user who has invited for view this document. What i do wrong? Where i misstake? And not really important. Export to csv

Upvotes: 0

Views: 603

Answers (1)

abielita
abielita

Reputation: 13469

DriveFiles can be shared, so checking the access token of a user isn't really necessary.

The Share Files page of the documentation details how it can be done (with code snippets specific to PHP). Once shared, the User should be able to view and export the file.

The error message provided indicates that the File was not found, this can be due to either the user doesn't have access to the file or it doesn't exist (wrong file ID). Its suggested that the user talk to the file owner to be given permissions for the file.

Lastly, if you already have access to the file, you can download them. There are 3 ways of implementing it. But if you want it to be exported as a .csv file, you can use the export method and specifying the MIME Type (text/csv).

The PHP code snippet in the documentation is as like this:

$fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
$content = $driveService->files->export($fileId, 'application/pdf', array('alt' => 'media' ));

Note that this text/csv will only work for Sheets. Other MIME Types for exporting can be seen on the documentation.

Upvotes: 0

Related Questions