注意:尽管此答案涉及 YouTube 报告 api,但所有 Google api 的流程应该相同,其中未提供高级 Google 服务包装器。
AFAICT,YouTube 报告 API 不能直接用作高级 Google 服务。您也许可以使用YouTubeanalytics api, which is provided as a advanced Google service。要访问报告api,您需要directly connect to the api through HTTP calls和urlfetch。
必读:
解决办法:
- 可以使用
UrlFetchApp 从 Google 应用脚本访问 YouTube 报告 API
- 可以使用
ScriptApp 提供的 oauth 令牌绕过完整的 OAuth 流程
- 在 appsscript.json 清单文件中包含范围。
- 切换到标准 GCP 并为此项目启用 YouTube 报告 API。否则将返回 403。
片段:
/**
* @description A wrapper for accessing Google apis from apps script
* @param {string} url Google URL endpoint
* @param {string} method HTTP method
* @param {object} requestBody Requestbody to send
* @param {object} pathParameters Parameters to modify in the url
* @param {object} queryParameters Queryparameters to append to the url
* @return {object} response
*/
function accessGoogleApiHTTP_(
url,
method,
requestBody = {},
pathParameters = {},
queryParameters = {}
) {
const modifiedUrl = Object.entries(pathParameters).reduce(
(acc, [key, value]) => acc.replace(key, value),
url
);
const queryUrl = Object.entries(queryParameters).reduce(
(acc, param) => acc + param.map(e => encodeURIComponent(e)).join('='),
'?'
);
const options = {
method,
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}` /*Need to set explicit scopes*/,
},
muteHttpExceptions: true,
payload: JSON.stringify(requestBody),
};
const res = UrlFetchApp.fetch(
modifiedUrl + queryUrl,
options
).getContentText();
console.log(res);
return JSON.parse(res);
}
/**
* @see https://developers.google.com/youtube/reporting/v1/reference/rest/v1/jobs/create
* @description POST https://youtubereporting.googleapis.com/v1/jobs
*/
function createYtReportingJob() {
const reportTypeId = 'id',
name = 'name';
const jsonRes = accessGoogleApiHTTP_(
'https://youtubereporting.googleapis.com/v1/jobs',
'POST',
{ reportTypeId, name },
undefined,
{ onBehalfOfContentOwner: 'contentOwnerId' }
);
}
清单范围:
"oauthScopes": [
"https://www.googleapis.com/auth/yt-analytics",
"https://www.googleapis.com/auth/script.external_request"
]