Google Drive PHP API - загрузка файлов - PullRequest
0 голосов
/ 20 марта 2020

Я пытаюсь загрузить файл на Google Drive с помощью API Google Drive в php. Я правильно получаю имя и идентификатор файла с диска Google. Но он не может загрузить файлы на диск Google и показать ошибку. Я не смог определить, отсутствует ли какой-либо пакет клиентской библиотеки или что-то еще происходит в нем

Fatal error: Uncaught Google_Service_Exception: { "error": { "errors": [ { "domain": "global", "reason": "insufficientPermissions", "message": "Insufficient Permission: Request had insufficient authentication scopes." } ], "code": 403, "message": "Insufficient Permission: Request had insufficient authentication scopes." } } in C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Http\REST.php:118 Stack trace: #0 C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Http\REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Task\Runner.php(181): Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Http\REST.php(58): Google_Task_Runner->run() #3 C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google in C:\xampp\htdocs\googledrive\vendor\google\apiclient\src\Google\Http\REST.php on line 118

Мой исходный код

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



/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } 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);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


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

// Print the names and IDs for up to 10 files.
$optParams = array(
  'pageSize' => 10,
  'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
    print "No files found.\n";
} else {
    print "Files:\n";
    foreach ($results->getFiles() as $file) {
        printf("%s (%s)\n</br>", $file->getName(), $file->getId());
    }
}



$pasta      = 'img';   
$arquivo    = 'photo.jpg'; // file.mp4
    printf("Folder: %s || File: %s\n", $pasta, $arquivo);


$parentId   = 'replace with Folder ID';


if ( !empty($arquivo) ) {

    //Define localização da pasta e arquivo
    $file_path = $pasta.'/'.$arquivo;

    //Conecta no Drive da sua conta
    $file = new Google_Service_Drive_DriveFile();

    //Define nome do arquivo
    $file->setName($arquivo);

    //Define Diretório Destino lá no Google Drive
    $file->setParents(array($parentId));

    //Cria o arquivo no GDrive
    $service->files->create(
      $file,
      array(
        'data'          => file_get_contents($file_path),
        'mimeType'      => 'application/octet-stream',
        'uploadType' => 'resumable'
      )
    );

    // Grava Log do que foi feito UTC -3 horas;
    $DateTime = new DateTime();
    $DateTime->modify('-3 hours');
    $now = $DateTime->format("Y-m-d H:i:s");
    $logfile = $now.' Upload OK :: '.$arquivo.PHP_EOL;

    $myfile = file_put_contents('logs.txt', $logfile, FILE_APPEND | LOCK_EX);

} else {

    //Grava Log
    $now = date("Y-m-d H:i:s");
    $logfile .=$now.' =====WITHOUT FILES========'.PHP_EOL;

    $myfile = file_put_contents('logs.txt', $logfile, FILE_APPEND | LOCK_EX);

}


Пожалуйста, помогите мне, в чем заключается проблема.

Ответы [ 2 ]

0 голосов
/ 20 марта 2020
  • диск. google .com
  • нажмите "новый"
  • , скопируйте и вставьте исходный код и сохраните
0 голосов
/ 20 марта 2020

Объем DRIVE_METADATA_READONLY равен https://www.googleapis.com/auth/drive.metadata.readonly. В этом случае метод Files: create не может быть использован. Я думаю, что причина вашего сообщения об ошибке заключается в следующем. Так что в этом случае, как насчет изменения следующим образом?

Я думаю, что другие части вашего скрипта работают.

От:

$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);

Кому:

$client->setScopes(Google_Service_Drive::DRIVE);

Примечание:

  • При изменении области действия удалите файл token.json из $tokenPath = 'token.json'; и снова авторизуйте области. Таким образом, новые области отражаются в токене доступа и обновляются sh токеном. Пожалуйста, будьте осторожны.

Ссылки:

Если я неправильно понял ваш вопрос, и это было не то направление, которое вы хотите, я прошу прощения.

...