【发布时间】:2020-07-16 21:58:42
【问题描述】:
我正在使用 Apps Script API 使用服务帐户的凭据运行函数。 我添加了 Rest 资源 API https://developers.google.com/apps-script/api/reference/rest/v1/scripts/run 中所需的所有范围。
但是当我在下面运行这个脚本时它失败了。
function run(){
var CREDENTIALS = {
"private_key": "Your Private key",
"client_email": "Your Client email",
"client_id": "Your Client ID",
"user_email": "Your Email address",
"api_key": "Your API key"
};
var service = getService(CREDENTIALS.client_email,CREDENTIALS.private_key);
service.reset();
if (service.hasAccess()) {
var url = 'https://script.googleapis.com/v1/projects/[SCRIPT ID]:run';
var body = {
"function": [FUNCTION NAME]
};
var params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
method: 'post',
playload : JSON.stringify(body),
contentType: 'application/json',
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, params);
Logger.log(response);
}
else {
Logger.log(service.getLastError());
}
}
function getService(email, privateKey) {
return OAuth2.createService('Service Account')
// Set the endpoint URL.
.setTokenUrl('https://oauth2.googleapis.com/token')
// Set the private key and issuer.
.setPrivateKey(privateKey)
.setIssuer(email)
// Set the name of the user to impersonate. This will only work for
// Google Apps for Work/EDU accounts whose admin has setup domain-wide
// delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
.setSubject([USER EMAIL])
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope('https://www.googleapis.com/auth/script.external_request');
}
我有一个 404 错误,我认为它来自范围列表。 因此,我无法使用 OAuth2.0 令牌运行部署为 API 可执行文件的脚本。 我应该选择哪些范围来通过 HTTP 请求运行函数?
【问题讨论】:
-
嗨@yoxCL9,你确定网址是正确的吗?它是 script.googleapis.com/v1/ scripts /{scriptId}:run,而你的似乎错过了
/scripts/路径部分,因此是 404 错误代码。如果身份验证有问题,您应该收到 403 -
嗨@OlegValter,我以前用projects.get方法检查了一个请求,它工作正常。
-
嗨@yoxCL9 - 我明白了 - 虽然它似乎并不相关,因为 Tanaike 的回答详细介绍了实际的潜在问题(呵呵,我怎么会错过不支持的服务帐户的免责声明)
标签: google-apps-script google-oauth service-accounts google-apps-script-api