【发布时间】:2022-01-06 20:41:51
【问题描述】:
我是 Google Analytics api 的新手,并且正在关注此 tutorial 以获取 estimatedMinutesWatched 和 averageViewDuration,但是我总是收到 403 禁止代码作为响应。
我想先问一下,如何解决这个问题,我们只应该从我们自己的频道中检索数据吗?其次,有没有一种方法可以在不指定频道 ID 的情况下检索指标?我可能想从来自不同频道的许多视频中检索指标,我觉得指定一个频道是不必要的。谢谢!
以下是我目前拥有的代码:
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');
const { GoogleSpreadsheet } = require('google-spreadsheet');
const scope = ['https://www.googleapis.com/auth/youtube.readonly'];
const creds = require('./client_secret.json');
const doc = new GoogleSpreadsheet('1YNzey4giSw-29oFGPCfGLBkMHCFB1o2oLr3qLIQZTVQ');
(async () => {
await doc.useServiceAccountAuth(creds);
await doc.loadInfo();
const sheet = doc.sheetsByIndex[0];
const rows = await sheet.getRows();
// const ids = rows.map(r => r.id).join(',');
const ids = 'IKiAiD3SONw';
fs.readFile("oauth_client_creds.json", (err, content) => {
if (err) {
return console.log("Cannot load client secret file:", err);
}
// Authorize a client with credentials, then make API call.
const credentials = JSON.parse(content);
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
const authUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: scope
});
console.log("Visit this URL to authorize this app:", authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter the auth code from that URL: ", code => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
oAuth2Client.setCredentials(token);
callApi(oAuth2Client);
});
});
});
let callApi = auth => {
const youtubeAnalytics = google.youtubeAnalytics({ version: "v2", auth });
youtubeAnalytics.reports
.query({
startDate: "2019-01-01",
endDate: "2021-12-31",
ids: "channel==UCbXm_tde_rLHG8gv48wSULw",
filters: `video==${ids}`,
dimensions: "video",
metrics: "estimatedMinutesWatched,averageViewDuration"
})
.then(async response => {
console.log(response);
console.log(response.data.rows);
response.data.rows.forEach(async (row, index) => {
rows[index].minutes_watched = row[1];
rows[index].avd = row[2];
await rows[index].save();
});
})
.catch(error => console.log("The API returned an error: ", error.message));
};
})();
【问题讨论】:
-
错误代码
403可能表示您没有提供正确的凭据。
标签: node.js google-api youtube-api google-analytics-api