2015-11-11 83 views
1

我正在尝试使用服务帐户从PHP调用一个非常简单的Google应用程序脚本,以便只有我的服务器才能访问它,而不是网站的用户。使用服务帐户从PHP调用Google应用程序脚本执行API

以下是我的工作方式。我在这里创建脚本https://script.google.com

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

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

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

然后我点击“激活并管理API”并激活“Google Apps Script Execution API”。我点击'Credentials',看到之前的操作自动创建了OAuth2凭证。但我需要的是服务帐户凭证。然后我创建一个Add credentials > Service account并下载生成的p12文件。我为此服务帐户获得了clientId = 109160023321840004240clientMail = [email protected]

我回到我的脚本,并与服务帐户电子邮件分享它与读取&写访问File > Share。首先,我得到我的个人邮箱的电子邮件,其中通知我,

Delivery to the following recipient failed permanently: 

[email protected] 

然后我发布脚本执行API Publish > Publish as an execution API访问给大家。

现在让我们继续在PHP服务器端。使用“谷歌API客户端库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(
    '[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. 

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

回答

4

Google Apps脚本还不支持与执行API服务帐户。看到https://code.google.com/p/google-apps-script-issues/issues/detail?id=5461

谷歌表示,他们正在寻找到它,但显然不会很快发生(基于谷歌在回复这个像谷歌https://plus.google.com/+MartinHawksey/posts/Zquix9XqzkK +职位)

+0

好齐格。非常感谢你的帮助,所以我不花更多的时间来调查我是错的:) – imbibinebe

+0

我做了,但我的投票只会出现时,我会有15票(对不起) 你知道一个解决方法我可以使用,以便我的服务器可以调用我自己的脚本,而不会提示我的网站用户进行授权?服务器密钥会起作用吗? https://console.developers.google.com/apis/credentials/key?type=SERVER_SIDE&project=project-id-uokwrcpiqeewhwvpdhb – imbibinebe

+0

查看不同的应用脚本发布选项。你可以做你自己的服务。 –

相关问题