Google 驱动器 API 无法写入文件夹
Google Drive API Unable to Write Folder
我从 Google 文档中拼凑了这个我正在尝试将测试文件夹写入 Google Drive APP 但我收到此错误:
An error occurred: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
网上查了一下好像是作用域的问题?这就是为什么我在下面添加了这么多:
require_once 'vendor/autoload.php';
date_default_timezone_set('Europe/London');
define('APPLICATION_NAME', 'Pauls Google Drive');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret_paul.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE,
Google_Service_Drive::DRIVE_FILE,
Google_Service_Drive::DRIVE_APPDATA,
Google_Service_Drive::DRIVE_READONLY,
Google_Service_Drive::DRIVE_METADATA,
Google_Service_Drive::DRIVE_METADATA_READONLY
)
));
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(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} 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);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* @param string $path the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
function getFolderExistsCreate($service, $folderName, $folderDesc) {
// List all user files (and folders) at Drive root
$files = $service->files->listFiles();
$found = false;
// Go through each one to see if there is already a folder with the specified name
foreach ($files['items'] as $item) {
if ($item['title'] == $folderName) {
$found = true;
return $item['id'];
break;
}
}
// If not, create one
if ($found == false) {
$folder = new Google_Service_Drive_DriveFile();
//Setup the folder to create
$folder->setName($folderName);
if(!empty($folderDesc))
$folder->setDescription($folderDesc);
$folder->setMimeType('application/vnd.google-apps.folder');
//Create the Folder
try {
$createdFile = $service->files->create($folder, array(
'mimeType' => 'application/vnd.google-apps.folder',
));
// Return the created folder's id
return $createdFile->id;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
getFolderExistsCreate( $service, 'Test', 'This is a test folder' );
getFolderExistsCreate 是实际创建文件夹的方法,它刚刚超过代码的一半。请帮忙!! :) 我已经能够 return 驱动器中的文件列表而没有错误,所以我很高兴凭据和连接都正常。
以下确认如何?
- 再次确认驱动器 API 已启用。
- 你说你添加了作用域。所以请删除
~/.credentials/drive-php-quickstart.json
的文件一次。然后,运行 您的脚本并再次创建 drive-php-quickstart.json
。这样,添加的范围就会反映到访问令牌和刷新令牌中。
如果这些对您没有用,我很抱歉。
"code": 403,
"message": "Insufficient Permission"
此错误指向文件夹权限。
为了让您的应用程序与文件夹通信(写入或读取),您必须与服务帐户电子邮件 ID 共享文件夹。
要遵循的步骤要设置文件夹权限:
例如,
Google Drive API 使用的凭据是服务帐户密钥,
(其他选项是 API 密钥,OAuth 密钥),
从 service-account.json 文件复制 'client_email'。
[创建服务帐号时生成,
用于设置google驱动认证的文件:$client->setAuthConfig('service-account.json'),
client_email 要查找的模式:SERVICE_ACCOUNT_NAME @ PROJECT_IDiam.gserviceaccount.com
]
在google驱动器中,右击选中需要上传文件的文件夹,选择'Share'。添加 client_email 。单击 'Done'。此过程是为 client_email 提供文件夹访问权限。
获取此文件夹的 folderId(rt。单击 - 选择可共享 link - 仅 id)。在文件调用中使用此 folderId
新 Google_Service_Drive_DriveFile(数组(
'name' => $文件名,
'parents' => array($folderId), '$mimeType' => $ftype)
注意上传的文件也匹配 mimeType。
希望对您有所帮助!
我从 Google 文档中拼凑了这个我正在尝试将测试文件夹写入 Google Drive APP 但我收到此错误:
An error occurred: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
网上查了一下好像是作用域的问题?这就是为什么我在下面添加了这么多:
require_once 'vendor/autoload.php';
date_default_timezone_set('Europe/London');
define('APPLICATION_NAME', 'Pauls Google Drive');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret_paul.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE,
Google_Service_Drive::DRIVE_FILE,
Google_Service_Drive::DRIVE_APPDATA,
Google_Service_Drive::DRIVE_READONLY,
Google_Service_Drive::DRIVE_METADATA,
Google_Service_Drive::DRIVE_METADATA_READONLY
)
));
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(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} 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);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* @param string $path the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
function getFolderExistsCreate($service, $folderName, $folderDesc) {
// List all user files (and folders) at Drive root
$files = $service->files->listFiles();
$found = false;
// Go through each one to see if there is already a folder with the specified name
foreach ($files['items'] as $item) {
if ($item['title'] == $folderName) {
$found = true;
return $item['id'];
break;
}
}
// If not, create one
if ($found == false) {
$folder = new Google_Service_Drive_DriveFile();
//Setup the folder to create
$folder->setName($folderName);
if(!empty($folderDesc))
$folder->setDescription($folderDesc);
$folder->setMimeType('application/vnd.google-apps.folder');
//Create the Folder
try {
$createdFile = $service->files->create($folder, array(
'mimeType' => 'application/vnd.google-apps.folder',
));
// Return the created folder's id
return $createdFile->id;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
getFolderExistsCreate( $service, 'Test', 'This is a test folder' );
getFolderExistsCreate 是实际创建文件夹的方法,它刚刚超过代码的一半。请帮忙!! :) 我已经能够 return 驱动器中的文件列表而没有错误,所以我很高兴凭据和连接都正常。
以下确认如何?
- 再次确认驱动器 API 已启用。
- 你说你添加了作用域。所以请删除
~/.credentials/drive-php-quickstart.json
的文件一次。然后,运行 您的脚本并再次创建drive-php-quickstart.json
。这样,添加的范围就会反映到访问令牌和刷新令牌中。
如果这些对您没有用,我很抱歉。
"code": 403, "message": "Insufficient Permission"
此错误指向文件夹权限。
为了让您的应用程序与文件夹通信(写入或读取),您必须与服务帐户电子邮件 ID 共享文件夹。
要遵循的步骤要设置文件夹权限: 例如, Google Drive API 使用的凭据是服务帐户密钥, (其他选项是 API 密钥,OAuth 密钥),
从 service-account.json 文件复制 'client_email'。
[创建服务帐号时生成, 用于设置google驱动认证的文件:$client->setAuthConfig('service-account.json'), client_email 要查找的模式:SERVICE_ACCOUNT_NAME @ PROJECT_IDiam.gserviceaccount.com ]
在google驱动器中,右击选中需要上传文件的文件夹,选择'Share'。添加 client_email 。单击 'Done'。此过程是为 client_email 提供文件夹访问权限。
获取此文件夹的 folderId(rt。单击 - 选择可共享 link - 仅 id)。在文件调用中使用此 folderId 新 Google_Service_Drive_DriveFile(数组( 'name' => $文件名, 'parents' => array($folderId), '$mimeType' => $ftype)
注意上传的文件也匹配 mimeType。
希望对您有所帮助!