目标:
我有一个适用于 Google 表单的公共 Google Workspace Marketplace 编辑器插件。 我想通过 Google Apps 脚本中的 Google Workspace Marketplace API 查询安装和卸载。
方法:
脚本:
const serviceAccount = {
"type": "service_account",
"project_id": "<<MY PROJECT ID>>",
"private_key_id": "<<MY PRIVATE KEY>>",
"private_key": "<<MY PRIVATE KEY>>",
"client_email": "<<MY CLIENT EMAIL>>",
"client_id": "<<MY CLIENT ID>>",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "<<MY CERT URL>>"
};
const { private_key, client_email, project_id } = serviceAccount;
const createService = (name, serviceAccount, scopes, userToImpersonate) => {
return OAuth2.createService(name)
.setSubject(userToImpersonate)
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(serviceAccount.private_key)
.setIssuer(serviceAccount.client_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setCache(CacheService.getUserCache())
.setLock(LockService.getUserLock())
.setScope(scopes);
};
const sendRequest = (url, oauthParams) => {
const { serviceName, serviceAccount, scopes, userToImpersonate } =
oauthParams;
const oauthService = createService(
serviceName,
serviceAccount,
scopes,
userToImpersonate
);
if (!oauthService.hasAccess()) {
console.log('ERROR IS ' + oauthService.getLastError());
return;
}
const headers = {
Authorization: `Bearer ${oauthService.getAccessToken()}`,
};
const options = {
method: 'get',
headers,
muteHttpExceptions: true,
};
return UrlFetchApp.fetch(url, options).getContentText();
};
const getLicenseNotifications = () => {
const url = 'https://appsmarket.googleapis.com/appsmarket/v2/licenseNotification/<<MY APP ID>>?maxResults=2';
const oauthParams = {
serviceName: 'GWMservice',
serviceAccount,
scopes: ['https://www.googleapis.com/auth/appsmarketplace.license'],
userToImpersonate: '<<MY USER>>@<<MY DOMAIN>>.com',
};
console.log(sendRequest(url, oauthParams));
};
Google Apps 脚本清单:
{
"timeZone": "Europe/Berlin",
"dependencies": {
"libraries": [
{
"userSymbol": "OAuth2",
"version": "43",
"libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF"
}
]
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"oauthScopes": [
"https://www.googleapis.com/auth/appsmarketplace.license",
"https://www.googleapis.com/auth/script.external_request"
]
}
错误:
我收到以下错误:
{
"error": {
"code": 503,
"message": "Temporary error. Please try later.",
"errors": [
{
"message": "Temporary error. Please try later.",
"domain": "global",
"reason": "backendError"
}
]
}
}
HTTP status code of 503
通常表示已超过 API 配额。谷歌文档说:
对于所有基于时间的错误(每个线程 X 秒内最多 N 件事),尤其是 503 状态代码错误,我们建议您的代码捕获异常并使用 exponential backoff 算法,等待一个小的延迟重试失败的呼叫。
您可以在这里阅读此信息。
可以在GCP控制台下看到quota limit,按步骤操作:
配额限制将显示在那里,您可以根据该信息设置指数退避。最后,作为最后的资源,如果您有 Google Workspace 帐户,您可以联系支持帮助您查看配额限制。
参考: