如何使用google api创建电子表格并使用PHP设置适当的权限?

SER*_*ERG 6 php google-spreadsheet-api

我有这个

define('CLIENT_SECRET_PATH', __DIR__ . '/config_api.json');
define('ACCESS_TOKEN', '0b502651********c52b3');
Run Code Online (Sandbox Code Playgroud)

我可以使用它创建一个电子表格并获取id和url.

$requestBody = new Google_Service_Sheets_Spreadsheet();
$response = $service->spreadsheets->create($requestBody);
print_r($response);
$new_spr_id = $response['spreadsheetId'];
Run Code Online (Sandbox Code Playgroud)

但是这个电子表格没有出现在谷歌表单列表中,因为它是" 受保护的 "或其他东西.我试图用这个设置权限,但得到一个错误:致命错误:调用未定义的方法Google_Service_Drive_Permission :: setValue()

insertPermission($service, $new_spr_id, '**@gmail.com' , 'user', 'owner');
function insertPermission($service, $fileId, $value, $type, $role) {
  $newPermission = new Google_Service_Drive_Permission();
  $newPermission->setValue($value);
  $newPermission->setType($type);
  $newPermission->setRole($role);
  try {
    return $service->permissions->insert($fileId, $newPermission);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return NULL;
}
Run Code Online (Sandbox Code Playgroud)

我需要一个创建新电子表格并为其设置适当权限的示例,以便我可以从我的帐户等修改此电子表格.

非常感谢!

Rey*_*cia 0

我认为你使用了错误的 API。文件的设置权限可在Drive API 权限中找到。

但为了回答您的问题,以下是如何使用Sheets API 中的 Spreadsheets.create创建新电子表格:

<?php
/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Google Sheets API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/sheets
 * 2. Install the PHP client library with Composer. Check installation
 *    instructions at https://github.com/google/google-api-php-client.
 */

// Autoload Composer.
require_once __DIR__ . '/vendor/autoload.php';

$client = getClient();

$service = new Google_Service_Sheets($client);

// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new Google_Service_Sheets_Spreadsheet();

$response = $service->spreadsheets->create($requestBody);

// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($response, true), '</pre>', "\n";

function getClient() {
  // TODO: Change placeholder below to generate authentication credentials. See
  // https://developers.google.com/sheets/quickstart/php#step_3_set_up_the_sample
  //
  // Authorize using one of the following scopes:
  //   'https://www.googleapis.com/auth/drive'
  //   'https://www.googleapis.com/auth/spreadsheets'
  return null;
}
?>
Run Code Online (Sandbox Code Playgroud)

创建文件并将其保存在 Google 云端硬盘后,您现在可以尝试使用 Drive REST API 设置权限。