PHP Google Drive API V3:“需要登录”错误

时间:2019-09-09 04:28:59

标签: php google-api google-drive-api google-oauth google-api-php-client

我在我的应用中使用Google Drive API v3。我想使用API​​上传一个简单的文件。但是,即使登录并重定向后,也会出现错误消息“需要登录”。

gdrive_auth.php

<?php

    require_once __DIR__ . '/vendor/autoload.php';

    $client = new Google_Client();
    // Get your credentials from the console
    $client->setClientId('MY CLIENT ID');
    $client->setClientSecret('MYS SECRET');
    $client->setRedirectUri('http://localhost/gdriveapi/index.php');
    $client->setScopes(array('https://www.googleapis.com/auth/drive'));

    session_start();

    if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
        if (isset($_GET['code'])) {
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
        } else
            $client->setAccessToken($_SESSION['access_token']);

    } else {
        $authUrl = $client->createAuthUrl();
        header('Location: ' . $authUrl);
        exit();
    }

index.php (授权后我将重定向到该地址)

<?php

    require_once __DIR__ . '/vendor/autoload.php';

    $client = new Google_Client();
    // Get your credentials from the console
    $client->setClientId('MY CLIENT ID');
    $client->setClientSecret('MY SECRET');
    $client->setScopes(array('https://www.googleapis.com/auth/drive'));

    $service = new Google_Service_Drive($client);

    //Insert a file
    $file = new Google_Service_Drive_DriveFile();
    $file->setName(uniqid().'.jpg');
    $file->setDescription('A test document');
    $file->setMimeType('image/png');

    $data = file_get_contents('Capture.png');

    $createdFile = $service->files->create($file, array(
        'data' => $data,
        'mimeType' => 'image/png',
        'uploadType' => 'multipart'
        ));

    print_r($createdFile);

错误消息:

  

致命错误:未捕获的Google_Service_Exception:{“ error”:{“ errors”:   [{“ domain”:“ global”,“ reason”:“ required”,“ message”:“登录   必需”,“ locationType”:“标头”,“位置”:“授权”}

有什么解决办法吗?

0 个答案:

没有答案