2015-11-11 80 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

查看不同的應用腳本發佈選項。你可以做你自己的服務。 –

相關問題