YouTube Data API - 检索我的上传内容(入门教程)

时间:2017-06-06 21:47:20

标签: javascript youtube youtube-api youtube-data-api

我尝试开始使用YouTube Data v3 API。我在官方网站上找到了this example

我的尝试(审查了API密钥和其他敏感数据):

的index.html

DrawText

my_upload.js

<!doctype html>
<html>
  <head>
    <title>My Uploads</title>
    <link rel="stylesheet" type="text/css" href="my_uploads.css">
  </head>
  <body>

    <!--Add buttons to initiate auth sequence and sign out-->
    <button id="authorize-button" style="display: none;">Authorize</button>
    <button id="signout-button" style="display: none;">Sign Out</button>

    <div id="content"></div>

    <div id="login-container" class="pre-auth">
      This application requires access to your YouTube account.
      Please <a href="#" id="login-link">authorize</a> to continue.
    </div>

    <div id="video-container"></div>
    <div class="button-container">
      <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
      <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="auth.js"></script>
    <script type="text/javascript" src="my_uploads.js"></script>
    <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
  </body>
</html>  

auth.js

// Define some variables used to remember state.
var playlistId, nextPageToken, prevPageToken;

// After the API loads, call a function to get the uploads playlist ID.
function handleAPILoaded() {
  requestUserUploadsPlaylistId();
}

// Call the Data API to retrieve the playlist ID that uniquely identifies the
// list of videos uploaded to the currently authenticated user's channel.
function requestUserUploadsPlaylistId() {
  // See https://developers.google.com/youtube/v3/docs/channels/list
  var request = gapi.client.youtube.channels.list({
    mine: true,
    part: 'contentDetails'
  });
  request.execute(function(response) {
    playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
    requestVideoPlaylist(playlistId);
  });
}

// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
  $('#video-container').html('');
  var requestOptions = {
    playlistId: playlistId,
    part: 'snippet',
    maxResults: 10
  };
  if (pageToken) {
    requestOptions.pageToken = pageToken;
  }
  var request = gapi.client.youtube.playlistItems.list(requestOptions);
  request.execute(function(response) {
    // Only show pagination buttons if there is a pagination token for the
    // next or previous page of results.
    nextPageToken = response.result.nextPageToken;
    var nextVis = nextPageToken ? 'visible' : 'hidden';
    $('#next-button').css('visibility', nextVis);
    prevPageToken = response.result.prevPageToken
    var prevVis = prevPageToken ? 'visible' : 'hidden';
    $('#prev-button').css('visibility', prevVis);

    var playlistItems = response.result.items;
    if (playlistItems) {
      $.each(playlistItems, function(index, item) {
        displayResult(item.snippet);
      });


 } else {
      $('#video-container').html('Sorry you have no uploaded videos');
    }
  });
}

// Create a listing for a video.
function displayResult(videoSnippet) {
  var title = videoSnippet.title;
  var videoId = videoSnippet.resourceId.videoId;
  $('#video-container').append('<p>' + title + ' - ' + videoId + '</p>');
}

// Retrieve the next page of videos in the playlist.
function nextPage() {
  requestVideoPlaylist(playlistId, nextPageToken);
}

// Retrieve the previous page of videos in the playlist.
function previousPage() {
  requestVideoPlaylist(playlistId, prevPageToken);
}

my_uploads.css

var myInfos = {
    "web":{
        "client_id":"censored",
        "project_id":"censored",
        "auth_uri":"https://accounts.google.com/o/oauth2/auth",
        "token_uri":"https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
        "client_secret":"censored",
        "redirect_uris":["https://localhost/ex/YouTube/index.html"],
        "javascript_origins":["http://localhost"]
    }
}

  // Enter an API key from the Google API Console:
  //   https://console.developers.google.com/apis/credentials
  var apiKey = "censored";

  // Enter the API Discovery Docs that describes the APIs you want to
  // access. In this example, we are accessing the People API, so we load
  // Discovery Doc found here: https://developers.google.com/people/api/rest/
  var discoveryDocs = ["https://people.googleapis.com/discovery/rest?version=v1"];

  // Enter a client ID for a web application from the Google API Console:
  //   https://console.developers.google.com/apis/credentials?project=_
  // In your API Console project, add a JavaScript origin that corresponds
  //   to the domain where you will be running the script.
  var clientId = myInfos.web.client_id;

  // Enter one or more authorization scopes. Refer to the documentation for
  // the API or https://developers.google.com/people/v1/how-tos/authorizing
  // for details.
  var scopes = 'profile';
  var authorizeButton = document.getElementById('authorize-button');
  var signoutButton = document.getElementById('signout-button');
  function handleClientLoad() {
    // Load the API client and auth2 library
    gapi.load('client:auth2', initClient);
  }
  function initClient() {
    gapi.client.init({
        apiKey: apiKey,
        discoveryDocs: discoveryDocs,
        clientId: clientId,
        scope: scopes
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
      signoutButton.onclick = handleSignoutClick;
    });
  }
  function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
      authorizeButton.style.display = 'none';
      signoutButton.style.display = 'block';
    } else {
      authorizeButton.style.display = 'block';
      signoutButton.style.display = 'none';
    }
  }
  function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
  }
  function handleSignoutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
  }

但我只得到一个空白页面,结果如下:

此应用程序需要访问您的YouTube帐户。请authorize继续。

如果我点击链接,则没有任何反应。可能是什么问题?

1 个答案:

答案 0 :(得分:1)

您的错误似乎与此相关:

  

&#34;在页面加载后立即尝试立即OAuth 2.0客户端流程。   如果当前登录的Google帐户之前已获得授权   客户端指定为OAUTH2_CLIENT_ID,然后是授权   成功,无需用户干预。否则,它会失败并且是用户   提示授权的界面需要显示&#34;

function checkAuth() { gapi.auth.authorize({ client_id: OAUTH2_CLIENT_ID, scope: OAUTH2_SCOPES, immediate: true }, handleAuthResult); }

  

&#34;否则,它会失败并提示用户界面   授权需要显示&#34;。

^^给你:

  

&#34;此应用程序需要访问您的YouTube帐户。请   授权继续。&#34;

您需要授权当前登录的Google帐户。

使用这些来源,它可以解决您的问题:

https://developers.google.com/youtube/v3/guides/authentication

https://developers.google.com/youtube/registering_an_application

相关问题