Невозможно получить файл Google Диска или его метаданные в моем приложении интернет-магазина

Я хочу, чтобы пользователи открывали файл, используя мой Интернет-магазин Chrome и затем я обработаю файл и метаданные, которые я получу. Я следил за официальной документацией Google, но пока не могу этого достичь.

Я добавил библиотеки из Google-api-php-клиент Github и это один из моих кодов, которые я пробовал:

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('xxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxx');
$client->setRedirectUri('https://my_site.com/path/driveapp.php');
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'email',
'profile'));
$client->setUseObjects(true);

// if there is an existing session, set the access token
if ($user = get_user()) {
$client->setAccessToken($user->tokens);
}

// initialize the drive service with the client.
$service = new Google_DriveService($client);

/**
* Gets the metadata and contents for the given file_id.
*/
$app->get('/svc', function() use ($app, $client, $service) {
checkUserAuthentication($app);
checkRequiredQueryParams($app, array('file_id'));
$fileId = $app->request()->get('file_id');
try {
// Retrieve metadata for the file specified by $fileId.
$file = $service->files->get($fileId);

// Get the contents of the file.
$request = new Google_HttpRequest($file->downloadUrl);
$response = $client->getIo()->authenticatedRequest($request);
$file->content = $response->getResponseBody();

renderJson($app, $file);
} catch (Exception $ex) {
renderEx($app, $ex);
}
});

Я следовал за всеми шагами, которые я должен; пошел в консоль, настроил Drive SDK, включил Drive API, создал Client ID, позаботился о параметрах в моем json моего веб-приложения Chrome. Но я все еще продолжаю получать синтаксические ошибки после того, как я использую методы, которые упомянуты в документе.

Из того, что я получаю, документация не обновляется, поэтому возникают проблемы с путями файлов библиотеки.

PS: я проверил Быстрый старт, Авторизовать запросы, а также Примеры‘коды, но ничего не помогло.

0

Решение

Его сложно использовать новейшую PHP-библиотеку для привода API. В интернете тоже не хватает документации.
Этот код работает для меня, он должен помочь вам:

<?php

session_start();
require_once 'google-api-php-client/src/Google/autoload.php';$client_id = '';
$client_secret = '';
$redirect_uri = '';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);

function printFile($service, $fileId) {
try {
$file = $service->files->get($fileId);

print "Title: " . $file->getTitle();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}

if (isset($_REQUEST['logout'])) {
unset($_SESSION['upload_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['upload_token'] = $client->getAccessToken();

}
if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) {
$client->setAccessToken($_SESSION['upload_token']);
if ($client->isAccessTokenExpired()) {
unset($_SESSION['upload_token']);
}
} else {
$authUrl = $client->createAuthUrl();
}

if ($client->getAccessToken()) {
// This is uploading a file directly, with no metadata associated.
if (isset($_GET['state'])) {
$a = urldecode(urldecode($_GET['state']));
$state = json_decode(stripslashes($a));
$_SESSION['mode'] = $state->action;

if (isset($state->ids)){
$_SESSION['fileIds'] = $state->ids;
} else {
$_SESSION['fileIds'] = array();
}
if (isset($state->parentId)) {
$_SESSION['parentId'] = $state->parentId;
} else {
$_SESSION['parentId'] = null;
}
$fileId = $_SESSION['fileIds'];
printFile($service, $fileId[0]);
}}

?>
1

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]