How do I find a users YouTube channel from Google gapi client authentication?

喜夏-厌秋 提交于 2021-02-11 12:47:03

问题


For the app I'm building I want the end user to login using gapi OAuth2 and from there I want the app to look for a playlist on their YouTube channel and load it.

The getAuthInstance method returns an object with a Google username. However for my own particular username, a query to find channel id by username returns no results. From some browsing online, this is apparently an issue with certain YouTube accounts.

Is there any workaround for this issue?


回答1:


If you have a valid OAuth 2.0 authentication via GAPI, then it's quite simple the determine the authenticated user's channel ID using the Channels.list API endpoint queried with the parameter mine=true:

mine (boolean)
This parameter can only be used in a properly authorized request. Set this parameter's value to true to instruct the API to only return channels owned by the authenticated user.

Upon invoking the endpoint, the property id of the returned Channels resource contains the channel ID of the authenticated user.


For what concerns a Javascript GAPI (i.e. Google’s Client Library for Browser-side JavaScript) implementation, the code would look like shown below (for a broader context look into this sample source file from Google: analytics_codelab.js):

var channelId;

function loadAPIClientInterfaces() {
  gapi.client.load('youtube', 'v3', function() {
    getUserChannel();
  });
}

function getUserChannel() {
  var request = gapi.client.youtube.channels.list({
    part: 'id',
    fields: 'items(id)',
    mine: true
  });
  request.execute(function(response) {
    if ('error' in response) {
      displayMessage(response.error.message);
    } else {
      channelId = response.items[0].id;
    }
  });
}

Note that the code above (unlike that in analytics_codelab.js) uses the fields request parameter for to obtain from the Channels.list endpoint only the channel's ID info (it is always good to ask from the API only the info that is of actual use).



来源:https://stackoverflow.com/questions/64295394/how-do-i-find-a-users-youtube-channel-from-google-gapi-client-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!