我正在尝试使用服务帐户从php调用一个非常简单的google apps脚本,以便只有我的服务器可以访问它,而不是网站的用户。
这是我的方法。我在这里https://script.google.com创建脚本
function get() {
return ContentService.createTextOutput('get method');
}
当我保存一个新项目时,它会自动关联。然后我打开File > Project Properties
以获取scriptId = MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt
Resources > Project Developers console
通过单击显示的弹出窗口顶部的项目链接,我可以访问相关项目的开发者控制台。
然后,我点击“激活和管理API”并激活“ Google Apps脚本执行API”。我单击“凭据”,然后看到先前的操作自动创建了OAuth2凭据。但是我需要的是服务帐户凭据。然后创建一个Add credentials > Service account
并下载生成的p12文件。我得到了该服务帐户的clientId = 109160023321840004240
和clientMail = [email protected]
。
我返回脚本并与具有读写访问权限的服务帐户电子邮件共享该脚本File > Share
。首先,我在个人邮箱中收到一封电子邮件,通知我
Delivery to the following recipient failed permanently:
[email protected]
然后,我将脚本发布为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(
'[email protected]',
[/*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.
如果你们中的一个人有帮助我的想法,我会很高兴:)
apps脚本尚不支持带有执行api的服务帐户。请参阅https://code.google.com/p/google-apps-script-issues/issues/detail?id=5461
谷歌表示,他们正在调查,但显然不会很快发生(基于谷歌对google +帖子的回复,例如https://plus.google.com/+MartinHawksey/posts/Zquix9XqzkK)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句