【问题标题】:how to upload files to google drive using php with access token如何使用带有访问令牌的 php 将文件上传到谷歌驱动器
【发布时间】:2019-08-04 20:10:34
【问题描述】:

我正在尝试使用 php 和 curl 将文件上传到我的谷歌驱动器帐户。我不希望所有这些冗长的身份验证流程成为一件事情。为此,我实现了下面的代码

$secret ="xxxxxx";
$clientid  ="xxxxxxx";

$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => "https://www.googleapis.com/upload/drive/v3/files?uploadType=media&clientID=xxxxxxx&secret=xxxxxxx",
CURLOPT_HTTPHEADER => array (
'Content-Type: image/png'),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents ('iconc.png' ),
 CURLOPT_RETURNTRANSFER => 1 
) );


$res = curl_exec($ch); 
$err = curl_error($ch);
echo $res;
var_dump($res);
echo "<br>";
echo "<br>";
echo $err ;

我已经启用了我的 google Drive Api,并且我被分配了 client idsecret,但是当我运行代码时,它会显示如下所示的无效凭据

{ "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } } string(238) "{ "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } } "

请问我在上面的代码中在哪里传递客户端 ID 和密码,或者我需要访问令牌之类的东西。如果是的话,我在哪里可以获得谷歌驱动 API 访问令牌。欢迎任何解决方案。谢谢

【问题讨论】:

标签: php google-drive-api


【解决方案1】:

您有两个选择,第一个是将访问令牌添加到请求中

https://www.googleapis.com/upload/drive/v3/files?access_token={YourToken}

第二种是在请求中作为header添加

curl -H 'Accept: application/json' -H "Authorization: Bearer ${TOKEN}" 
https://www.googleapis.com/upload/drive/v3/files

使用您在此处所做的客户端 ID clientID=xxxxxxx&amp;secret=xxxxxxx 是基本授权而不是 Oauth2,您缺少授权步骤。

您应该考虑遵循 php 快速入门here

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

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * 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", $file->getName(), $file->getId());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 2022-12-15
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多