簡體   English   中英

使用服務帳戶從PHP調用Google Apps腳本執行API

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

我正在嘗試使用服務帳戶從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 = 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

然后,我將腳本Publish > Publish as an execution API執行API Publish > Publish as an execution API可以訪問所有人Publish > Publish as an execution API

現在,讓我們進入PHP服務器端。 使用https://github.com/google/google-google-api-php-client上提供的“ PHP的Google API客戶端庫”,我嘗試從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.

如果你們中的一個人有幫助我的想法,我會很高興:)

apps腳本尚不支持帶有執行api的服務帳戶。 請參閱https://code.google.com/p/google-apps-script-issues/issues/detail?id=5461

谷歌表示,他們正在調查,但顯然不會很快發生(基於谷歌對google +帖子的回復,例如https://plus.google.com/+MartinHawksey/posts/Zquix9XqzkK

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM