1

我有一个网络应用程序,我希望通过它能够创建播放列表、将视频添加到播放列表、删除视频等到我的 youtube 频道。我创建了一个服务帐户并下载了服务帐户凭据密钥文件,并在 Google Developer Console 中设置了我的 OAuth 2.0 客户端 ID。为了验证我的应用程序,我按照此处https://github.com/googleapis/google-api-nodejs-clientREADME.md中的说明进行操作- 在服务帐户凭据下google-api-nodejs-client

这是我的控制器文件...我应该注意该项目使用 ES 模块,因此"type": "module"设置在package.json. 这就是为什么您会注意到例如我__dirname作为实用程序导入的原因,因为 ES 模块不支持常规的__dirname.

import googleapi from "googleapis";
const { google } = googleapi;
import Auth from "@google-cloud/local-auth";
const { authenticate } = Auth;
import path from "path";
import __dirname from "../utils/dirname.js";

async function initialize() {
  try {
    const auth = await authenticate({
      keyfilePath: path.join(__dirname, "../service_account_credentials.json"),
      scopes: ["https://www.googleapis.com/auth/youtube"],
    });
    console.log("Auth details");
    console.log(auth);
    google.options({ auth });
  } catch (e) {
    console.log(e);
  }
}
initialize();

const oauth2Client = new google.auth.OAuth2(
  "YOUR_CLIENT_ID",
  "YOUR_CLIENT_SECRET",
  "http://localhost:5000/oauth2callback"
);

// initialize the Youtube API library
const youtube = google.youtube({ version: "v3", auth: oauth2Client });

class YoutubeController {
  static async createPlaylist(req, res) {
    const { name } = req.body;
    const playlist = await youtube.playlists.insert({
      part: "snippet,status",
      resource: {
        snippet: {
          title: name,
          description: `${name} videos.`,
        },
        status: {
          privacyStatus: "private",
        },
      },
    });

    res.json(playlist);
  }
}

initialize函数是引发错误的函数,我无法弄清楚。我想正因为如此,当我POST向调用createPlaylist类内部方法的路由发出请求时,我会回来No access, refresh token or API key is set.

我一直在阅读文档,试图了解一切是如何流动的,但我有点卡住了。

这里提出了一个类似的问题 - TypeError: Cannot read property 'redirect_uris' of undefined但没有答案,建议的工作流程不适用于我的情况,因此非常感谢您对此提供的帮助。

4

1 回答 1

2

服务帐户

YouTube API 不支持您需要使用 OAuth2 的服务帐户身份验证。

OAuth2 授权

您可能需要考虑遵循nodejs 的 YouTube API 快速入门。

问题是您正在使用它不支持的 YouTube API 的服务帐户身份验证。

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the YouTube API.
  authorize(JSON.parse(content), getChannel);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
    if (err) throw err;
    console.log('Token stored to ' + TOKEN_PATH);
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function getChannel(auth) {
  var service = google.youtube('v3');
  service.channels.list({
    auth: auth,
    part: 'snippet,contentDetails,statistics',
    forUsername: 'GoogleDevelopers'
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var channels = response.data.items;
    if (channels.length == 0) {
      console.log('No channel found.');
    } else {
      console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
                  'it has %s views.',
                  channels[0].id,
                  channels[0].snippet.title,
                  channels[0].statistics.viewCount);
    }
  });
}

YouTube API 快速入门 nodejs 中无耻地撕下代码。

后端访问

由于 YouTube API 不支持服务帐户。从后端服务访问数据可能很棘手,但并非不可能。

  1. 在本地运行您的应用程序一次。
  2. Aurhtoirze 访问您的帐户数据。
  3. 在您的代码中找到存储的凭据,它们应包含刷新令牌。
  4. 将此刷新令牌保存为应用程序的一部分。
  5. 设置您的代码以在加载时读取此刷新令牌。

不幸的是,我不是 node.js 开发人员,所以我无法帮助您编写所需的代码。如果您可以找到该库以及如何加载该库,则该库应该将其存储到凭据对象中,那么您应该能够执行我的建议。

我将首先深入研究storeToken(token);正在做的事情。

于 2020-08-17T06:23:15.980 回答