Laravel调用YouTube Data API获取私有/未列出播放列表遇问题
问题:Laravel中无法获取YouTube私有/未列出播放列表
在Laravel应用里,我想获取关联YouTube频道的所有播放列表(公开、私有、未列出),现在只能拿到公开的,就算配置了OAuth也拿不到私有和未列出的。
我的代码如下:
public function getPlaylist() { $client = new Client(); $client->setLogger(new \Monolog\Logger('google-api')); $client->setApplicationName('Playlists'); $client->setAuthConfig(base_path('youtube.json')); // 用授权码交换访问令牌 if (Session::has('google_oauth_token')) { $client->setAccessToken(Session::get('google_oauth_token')); } $service = new YouTube($client); $queryParams = [ 'channelId' => config('scraper.channelId'), 'maxResults' => 50, 'mine' => 1, ]; $response = $service->playlists->listPlaylists('snippet, contentDetails, status, id', $queryParams); dd($response); }
遇到的错误:
{ "error": { "code": 400, "message": "Incompatible parameters specified in the request: channelId, mine", "errors": [ { "message": "Incompatible parameters specified in the request: channelId, mine", "domain": "youtube.parameter", "reason": "incompatibleParameters", "location": "parameters.", "locationType": "other" } ] } }
移除mine参数后,只能获取公开播放列表;保留mine移除channelId时,出现以下错误:
{ "error": { "code": 404, "message": "Channel not found.", "errors": [ { "message": "Channel not found.", "domain": "youtube.playlist", "reason": "channelNotFound", "location": "channelId", "locationType": "parameter" } ] } }
请问哪里操作错了?能不能获取私有和未列出的播放列表?
解决方案
- 参数冲突问题
YouTube Data API明确规定,channelId和mine参数不能同时使用:
mine=1代表获取当前授权用户的所有播放列表(包括私有/未列出)channelId则是指定某个公开频道的播放列表(只能拿到公开的)
- 解决404错误的关键
用mine=1时出现404,说明当前OAuth授权的用户和你要获取的频道不是同一个账号,或者授权流程有问题:
- 确保OAuth授权的账号就是目标YouTube频道的所有者
- 检查授权时的scope权限,必须包含
https://www.googleapis.com/auth/youtube.readonly或更高级的https://www.googleapis.com/auth/youtube,否则无法访问私有内容
- 修正后的代码示例
public function getPlaylist() { $client = new Client(); $client->setLogger(new \Monolog\Logger('google-api')); $client->setApplicationName('Playlists'); $client->setAuthConfig(base_path('youtube.json')); // 必须设置正确的权限范围 $client->addScope('https://www.googleapis.com/auth/youtube.readonly'); // 处理令牌过期自动刷新 if (Session::has('google_oauth_token')) { $client->setAccessToken(Session::get('google_oauth_token')); if ($client->isAccessTokenExpired()) { // 刷新令牌(前提是auth配置里有refresh_token) $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); Session::put('google_oauth_token', $client->getAccessToken()); } } else { // 无令牌则跳转到授权页面 $authUrl = $client->createAuthUrl(); return redirect($authUrl); } $service = new YouTube($client); $queryParams = [ 'maxResults' => 50, 'mine' => 1, ]; $response = $service->playlists->listPlaylists('snippet, contentDetails, status, id', $queryParams); dd($response); }
- 额外注意事项
- 确保你的OAuth客户端ID已完成验证,否则可能存在访问限制
- 如果使用服务账号,不能用
mine=1,需要先通过Google Workspace授权访问指定频道,或者直接将服务账号关联到目标频道
内容的提问来源于stack exchange,提问作者Flo Saurus
相关产品推荐
相关产品推荐

