【发布时间】:2015-11-11 12:33:24
【问题描述】:
我正在尝试使用服务帐户从 php 调用一个非常简单的谷歌应用程序脚本,以便只有我的服务器可以访问它,而不是网站的用户。
这是我的做法。我在这里创建脚本https://script.google.com
function get() {
return ContentService.createTextOutput('get method');
}
当我保存一个新项目时,它会自动关联。
然后我打开File > Project Properties 得到scriptId = MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt
我通过单击显示的弹出窗口顶部的项目链接访问相关项目的开发者控制台 throw Resources > Project Developers console。
然后我点击“激活和管理 API”并激活“Google Apps 脚本执行 API”。我单击“凭据”并看到之前的操作自动创建了 OAuth2 凭据。但我需要的是服务帐户凭据。然后我创建一个Add credentials > Service account 并下载生成的 p12 文件。我得到了此服务帐户的 clientId = 109160023321840004240 和 clientMail = 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 服务器端。使用此处提供的“适用于 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);
这是我一直得到的回应
Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (403) The caller does not have permission
如果我在部署脚本时选择授予“仅限我”的访问权限,我会收到以下响应。
Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (404) Requested entity was not found.
如果你们中的任何一个有想法可以帮助我,我会很高兴:)
【问题讨论】:
标签: php google-apps-script service-accounts