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

我正在尝试使用 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 访问令牌。欢迎任何解决方案。谢谢


慕的地6264312
浏览 118回答 1
1回答

阿晨1998

您有两个选择,第一个是将访问令牌添加到请求中https://www.googleapis.com/upload/drive/v3/files?access_token={YourToken}第二种是在请求中作为header添加curl -H 'Accept: application/json' -H "Authorization: Bearer ${TOKEN}"&nbsp;https://www.googleapis.com/upload/drive/v3/files像您在此处所做的那样使用客户端 IDclientID=xxxxxxx&secret=xxxxxxx是基本授权,而不是 Oauth2,您缺少授权步骤。您应该考虑在此处遵循 php 快速入门<?phprequire __DIR__ . '/vendor/autoload.php';if (php_sapi_name() != 'cli') {&nbsp; &nbsp; throw new Exception('This application must be run on the command line.');}/**&nbsp;* Returns an authorized API client.&nbsp;* @return Google_Client the authorized client object&nbsp;*/function getClient(){&nbsp; &nbsp; $client = new Google_Client();&nbsp; &nbsp; $client->setApplicationName('Google Drive API PHP Quickstart');&nbsp; &nbsp; $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);&nbsp; &nbsp; $client->setAuthConfig('credentials.json');&nbsp; &nbsp; $client->setAccessType('offline');&nbsp; &nbsp; $client->setPrompt('select_account consent');&nbsp; &nbsp; // Load previously authorized token from a file, if it exists.&nbsp; &nbsp; // The file token.json stores the user's access and refresh tokens, and is&nbsp; &nbsp; // created automatically when the authorization flow completes for the first&nbsp; &nbsp; // time.&nbsp; &nbsp; $tokenPath = 'token.json';&nbsp; &nbsp; if (file_exists($tokenPath)) {&nbsp; &nbsp; &nbsp; &nbsp; $accessToken = json_decode(file_get_contents($tokenPath), true);&nbsp; &nbsp; &nbsp; &nbsp; $client->setAccessToken($accessToken);&nbsp; &nbsp; }&nbsp; &nbsp; // If there is no previous token or it's expired.&nbsp; &nbsp; if ($client->isAccessTokenExpired()) {&nbsp; &nbsp; &nbsp; &nbsp; // Refresh the token if possible, else fetch a new one.&nbsp; &nbsp; &nbsp; &nbsp; if ($client->getRefreshToken()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Request authorization from the user.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $authUrl = $client->createAuthUrl();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printf("Open the following link in your browser:\n%s\n", $authUrl);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print 'Enter verification code: ';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $authCode = trim(fgets(STDIN));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Exchange authorization code for an access token.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $client->setAccessToken($accessToken);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Check to see if there was an error.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (array_key_exists('error', $accessToken)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new Exception(join(', ', $accessToken));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Save the token to a file.&nbsp; &nbsp; &nbsp; &nbsp; if (!file_exists(dirname($tokenPath))) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mkdir(dirname($tokenPath), 0700, true);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; file_put_contents($tokenPath, json_encode($client->getAccessToken()));&nbsp; &nbsp; }&nbsp; &nbsp; 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(&nbsp; 'pageSize' => 10,&nbsp; 'fields' => 'nextPageToken, files(id, name)');$results = $service->files->listFiles($optParams);if (count($results->getFiles()) == 0) {&nbsp; &nbsp; print "No files found.\n";} else {&nbsp; &nbsp; print "Files:\n";&nbsp; &nbsp; foreach ($results->getFiles() as $file) {&nbsp; &nbsp; &nbsp; &nbsp; printf("%s (%s)\n", $file->getName(), $file->getId());&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP