是否可以通过Google API服务帐户访问Google电子表格API?如何在PHP中做到这一点


Is it possible to access the Google Spreadsheets API via an Google API Service account? How to do so in PHP?

我成功地使用带有服务帐户的Google PHP API来操作Google CloudDNS记录,如下所示:

$permisson = 'https://www.googleapis.com/auth/ndev.clouddns.readwrite';
$client = new Google_Client();
$client->setApplicationName("foo");
$credentials = new Google_Auth_AssertionCredentials(
    $googleApiServiceAccount,
    array($permission),
    file_get_contents($googleApiKeyFile)
);
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($credentials);
}
$accessToken = $client->getAccessToken();
[..]

是否可以使用类似的方案访问谷歌应用程序电子表格?使用什么作为$permission?我必须在Google开发者控制台中启用什么类型的API?

请注意:我完全知道通过oAuth2访问API很容易,我正在寻找通过服务帐户访问它的方法。

关于权限部分:

$permissions = array(
    "https://spreadsheets.google.com/feeds",
    "https://docs.google.com/feeds"
);
$credentials = new Google_Auth_AssertionCredentials(
    $googleApiServiceAccount,
    $permissions,
    file_get_contents($googleApiKeyFile)
);

Google API控制台服务帐户需要作为合作者添加到您想要访问的电子表格中!您可以创建/查看此处的服务帐户电子邮件地址:

https://console.developers.google.com/project/YOUR-PROJECT-NAME/permissions/projectpermissions

这是要使用的服务:

$service = new 'Google'Spreadsheet'SpreadsheetService();