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

Calling a google apps script execution api from PHP using a service account

我正在尝试使用服务帐户从 php 调用一个非常简单的 google 应用程序脚本,这样只有我的服务器才能访问它,网站的用户不能访问它。

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

function get() {
    return  ContentService.createTextOutput('get method');
}

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

我通过单击显示的弹出窗口顶部的项目 link 访问引发 Resources > Project Developers console 的关联项目的开发人员控制台。

然后单击 'Activate and manage API' 并激活 'Google Apps Script Execution API'。我单击 'Credentials' 并看到之前的操作自动创建了 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

然后我将脚本作为执行 API Publish > Publish as an execution API 发布给所有人。

现在让我们进入 PHP 服务器端。使用此处可用的 'Google APIs Client Library for PHP' 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);

这是我一直收到的回复

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

如果我在部署脚本时选择授予对 'Me only' 的访问权限,我会收到以下响应。

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

如果你们中有人有什么想法可以帮助我,我将非常高兴:)

apps 脚本尚不支持执行服务帐户 api。见 https://code.google.com/p/google-apps-script-issues/issues/detail?id=5461

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