0

I'm creating a node.js app using google-api-nodejs-client library. Users can allow OAuth2 access to their YouTube channels for my app, and here is scopes that I'm requesting:

https://www.googleapis.com/auth/youtube
https://www.googleapis.com/auth/youtube.readonly
https://www.googleapis.com/auth/yt-analytics.readonly
https://www.googleapis.com/auth/yt-analytics-monetary.readonly

Access and refresh tokens are stored in DB, and program needs it to update channel statistics (it is done by node tasks.js in cron).

The problem is when I do it from localhost (my development machine) it is working fine and collects all necessary data. But when I run it from my server SSH, it is returning this:

{"domain":"global","reason":"forbidden","message":"Forbidden"}

What is this and how to fight this?


Here is my code:

const oauth2Client = new OAuth2(
    config.auth.youtube.client_id,
    config.auth.youtube.client_secret,
    config.auth.youtube.redirect_uri
);

oauth2Client.setCredentials({
    access_token: profile.access_token,
    refresh_token: profile.refresh_token
});

let params = {
    'ids': 'channel==MINE',
    'metrics': 'views',
    'dimensions': 'subscribedStatus,country',
    'start-date': '1970-01-01',
    'end-date': moment().format('YYYY-MM-DD'),
    'auth': oauth2Client
};

youtubeAnalytics.reports.query(params, (err, response) => {
    if (err) {
        return;
    }

    if (!response.rows || response.rows.length <= 0) {
        return;
    }

    let sql = '';

    for (let i = 0; i < response.rows.length; i++) {
        let r = response.rows[i];

        if (r[0] == 'UNSUBSCRIBED') {
            sql += `,(${profile.profile_id}, ${profileMetricTypeKeys.viewers_by_country.id}, '${r[1]}', ${r[2]}, now())`;
        } else {
            sql += `,(${profile.profile_id}, ${profileMetricTypeKeys.subscribers_by_country.id}, '${r[1]}', ${r[2]}, now())`;
        }
    }

    sql = `
        INSERT INTO profile_metrics (profile_id, type_id, key, value, updated_on)
        VALUES ${sql.substr(1)}
        ON CONFLICT (profile_id, type_id, key) DO UPDATE
            SET value = excluded.value, updated_on = excluded.updated_on
    `;

    db.query(sql)
        .catch((error) => {
            logger.error(`Profile (${profile.profile_id}): Query error: ${error.message}`);
        });
});
StackTracer
  • 45
  • 2
  • 7

1 Answers1

0

Instead of

'ids': 'channel==MINE',
'metrics': 'views',
'dimensions': 'subscribedStatus,country',
'start-date': '1970-01-01',
'end-date': moment().format('YYYY-MM-DD'),
'auth': oauth2Client

try using

let params = {
'ids': 'channel==ChannelID',
'metrics': 'views',
'dimensions': 'subscribedStatus,country',
'start-date': '1970-01-01',
'end-date': moment().format('YYYY-MM-DD'),
'auth': oauth2Client }

Replace channelID with your channel id.

Andre Hofmeister
  • 3,185
  • 11
  • 51
  • 74
45456
  • 1