NodeJS对接YouTube直播Google OAuth2.0认证报错求助
解决YouTube直播推流NodeJS认证错误:"key must be a string, a buffer or an object"
问题根源
你当前用的google.auth.GoogleAuth是为服务账号设计的认证方式,但你下载的是**OAuth2客户端(web类型)**的credentials.json,两者不匹配,导致认证时解析密钥出错,抛出目标错误。个人YouTube账号需要通过OAuth2授权码流程获取用户授权,不能用服务账号的认证逻辑。
解决步骤
1. 替换认证代码为OAuth2客户端流程
修改你的index.js,改用OAuth2客户端完成授权:
const { google } = require('googleapis'); const fs = require('fs'); const readline = require('readline'); // 加载OAuth2客户端凭据 const credentials = JSON.parse(fs.readFileSync('credentials.json')); const { client_secret, client_id, redirect_uris } = credentials.web; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0] // 要和Google Console里配置的重定向URI一致,比如http://localhost:3000/oauth2callback ); // 检查本地是否有已保存的授权token const TOKEN_PATH = 'token.json'; fs.readFile(TOKEN_PATH, (err, token) => { if (err) return getNewToken(oAuth2Client); oAuth2Client.setCredentials(JSON.parse(token)); // 授权成功后,在这里调用YouTube API实现推流逻辑 initYouTubeStream(oAuth2Client); }); // 获取新的授权token function getNewToken(oAuth2Client) { const authUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', // 允许获取刷新token,避免频繁授权 scope: ['https://www.googleapis.com/auth/youtube.force-ssl'], }); console.log('请打开以下地址授权:', authUrl); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question('粘贴授权后得到的代码: ', (code) => { rl.close(); oAuth2Client.getToken(code, (err, token) => { if (err) return console.error('获取token失败:', err); oAuth2Client.setCredentials(token); // 保存token到本地,下次运行直接使用 fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => { if (err) return console.error(err); console.log('token已保存到', TOKEN_PATH); }); initYouTubeStream(oAuth2Client); }); }); } // 初始化YouTube API操作 function initYouTubeStream(auth) { const youtube = google.youtube({ version: 'v3', auth }); // 这里可以添加创建直播广播、获取推流地址等逻辑 // 示例:youtube.liveBroadcasts.insert({...}) }
2. 核对Google Console配置
- 确保你在Google Console的OAuth2客户端设置中,配置了代码里用到的重定向URI(比如
http://localhost:3000/oauth2callback),这个URI必须和credentials.json里的redirect_uris数组中的某一项完全一致 - 确认你的项目已经启用了YouTube Data API v3(在Google Console的API库中搜索启用)
3. 运行流程
- 执行
node index.js,控制台会输出一个授权链接 - 打开链接,用你的个人YouTube账号登录并授权
- 将页面跳转后显示的授权代码复制到控制台输入
- 程序会自动保存
token.json,后续运行无需重复授权
内容的提问来源于stack exchange,提问作者Manfredi P.
相关产品推荐
相关产品推荐

