使用服务帐户从 PHP 调用 google 应用程序脚本执行 api

imb*_*ebe 2 php google-apps-script service-accounts

我正在尝试使用服务帐户从 php 调用一个非常简单的谷歌应用程序脚本,以便只有我的服务器可以访问它,而不是网站的用户。

这是我的做法。我在这里创建脚本https://script.google.com

function get() {
    return  ContentService.createTextOutput('get method');
}
Run Code Online (Sandbox Code Playgroud)

当我保存它时会自动关联一个新项目。然后我打开File > Project Properties得到scriptId = MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt

Resources > Project Developers console通过单击显示的弹出窗口顶部的项目链接来访问相关项目的开发人员控制台。

然后我点击“激活和管理 API”并激活“Google Apps Script Execution API”。我单击“凭据”并看到之前的操作自动创建了 OAuth2 凭据。但我需要的是服务帐户凭据。然后我创建一个Add credentials > Service account并下载生成的 p12 文件。我得到了这个服务帐户的clientId = 109160023321840004240clientMail = account-1@project-id-uokwrcpiqeewhwvpdhb.iam.gserviceaccount.com

我返回到我的脚本并与具有读写访问权限的服务帐户电子邮件共享它File > Share。首先,我在我的个人邮箱中收到一封电子邮件,通知我

Delivery to the following recipient failed permanently:

 account-1@project-id-uokwrcpiqeewhwvpdhb.iam.gserviceaccount.com
Run Code Online (Sandbox Code Playgroud)

然后我将脚本发布Publish > Publish as an execution API为每个人都可以访问的执行 API 。

现在让我们进入 PHP 服务器端。使用此处提供的“适用于 PHP 的 Google API 客户端库” https://github.com/google/google-api-php-client我尝试从 PHP 调用我的脚本函数:

$client = new Google_Client();
$client->setClientId('109160023321840004240');
$client->setApplicationName('myScript');

$cred = new Google_Auth_AssertionCredentials(
    'account-1@project-id-okwrcpiqeewhwvpdhb.iam.gserviceaccount.com',
    [/*no scope nedeed for this simple script*/],
    file_get_contents('path_to_myScript.p12')
);
$client->setAssertionCredentials($cred);

if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
}

$service = new Google_Service_Script($client);
$scriptId = 'MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt';

// Create an execution request object.
$request = new Google_Service_Script_ExecutionRequest();
$request->setFunction('get');
$response = $service->scripts->run($scriptId, $request);
Run Code Online (Sandbox Code Playgroud)

这是我一直得到的回应

Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (403) The caller does not have permission
Run Code Online (Sandbox Code Playgroud)

如果在部署脚本时选择授予“仅限我”的访问权限,则会收到以下响应。

Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (404) Requested entity was not found.
Run Code Online (Sandbox Code Playgroud)

如果你们中的一个有想法来帮助我,我会很高兴:)

Zig*_*del 5

应用程序脚本尚不支持具有执行 API 的服务帐户。见https://code.google.com/p/google-apps-script-issues/issues/detail?id=5461

谷歌表示他们正在调查它,但显然不会很快发生(基于谷歌对 google+ 帖子的回复,如https://plus.google.com/+MartinHawksey/posts/Zquix9XqzkK