为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用带有访问令牌的php将文件上传到谷歌驱动器

如何使用带有访问令牌的php将文件上传到谷歌驱动器

PHP
慕的地6264312 2021-11-13 16:20:18
我正在尝试使用 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 并且我已经分配了客户端 ID和密码,但是当我运行代码时,它说凭据无效,如下所示{ "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 访问令牌。欢迎任何解决方案。谢谢
查看完整描述

1 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

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


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

像您在此处所做的那样使用客户端 IDclientID=xxxxxxx&secret=xxxxxxx是基本授权,而不是 Oauth2,您缺少授权步骤。


您应该考虑在此处遵循 php 快速入门


<?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());

    }

}


查看完整回答
反对 回复 2021-11-13
  • 1 回答
  • 0 关注
  • 117 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信