问题
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