我已经设置并运行了 Google Sheets API(如果共享到我的凭据,我可以读取和更新现有电子表格),并且我需要将一些数据从我的网站导出到 Google Sheet。为了防止用户看到其他人的工作表,当用户想要导出数据时,我需要创建一个新的电子表格。我设法创建了这样的新电子表格:
public function init(){
$user = Socialite::driver('google')->stateless()->user();
$token = [
'access_token' => $user->token,
'refresh_token' => $user->refreshToken,
'expires_in' => $user->expiresIn
];
$client = new \Google_Client();
$client->setApplicationName('Sheets');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig('../credentials.json');
$client->setAccessToken($token);
$service = new Google_Service_Sheets($client);
$serviceDrive = new Google_Service_Drive($client);
$spreadsheet = new Google_Service_Sheets_Spreadsheet([
'properties' => [
'title' => 'Testing Sheet'
]
]);
$spreadsheet = $service->spreadsheets->create($spreadsheet, [
'fields' => 'spreadsheetId'
]);
$this->insertPermission($serviceDrive, $spreadsheet->spreadsheetId, $user->email, 'user', 'owner');
}
当我dd($spreadsheet)看到它实际上已创建并且我可以检索它的 id 时。但问题是,如果我尝试打开它,我会收到一条通知,提示我需要访问权限,因为我没有权限。我寻找了很多解决方案并尝试了多种方法。我试图传递这样一个角色:
$spreadsheet = $service->spreadsheets->create($spreadsheet, [
'fields' => 'spreadsheetId',
'role' => 'owner'
'email' => 'useremail@gmail.com'
]);
还尝试使用此方法插入权限:
function insertPermission($service, $fileId, $value, $type, $role) {
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setEmailAddress($value);
$newPermission->setType($type);
$newPermission->setRole($role);
try {
return $service->permissions->create($fileId, $newPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
但是这个方法在调用create()函数时给了我一个错误,上面写着"code": 403, "message": "Insufficient Permission: Request had insufficient authentication scopes.". 有没有办法让经过身份验证的用户访问新创建的电子表格,我的错误在哪里?
月关宝盒