如何从Google+ ID获取YouTube频道信息

时间:2014-07-20 06:10:53

标签: youtube youtube-api

该网站正在进行Google OAuth 2授权。

scope: "profile https://www.googleapis.com/auth/youtube "

登录后,Google向我提供了此用户数据:

{
    id: 107055280208390515,
    name: Name,
    link: https://plus.google.com/107055208390515542,
    picture: https://lh3.googleusercontent.com/-q1Smh9d8d0g/AAAAAAAAAAM/AAAAAAAAAAA/3YaTIPc/photo.jpg,
    locale: en
}

但结果中不包含YouTube频道信息。是否有不同的范围或API?搜索了Google文档&一无所获。

1 个答案:

答案 0 :(得分:4)

好吧,身份验证只是第一步(Google+ oAuth不会返回任何Youtube渠道信息)我相信会访问使用Youtube API所需的经过身份验证的用户渠道信息(https://developers.google.com/youtube/v3/docs/channels )。

您没有指定要使用的平台,但这里有一个经过修改的Google示例代码,可以使用PHP访问Youtube频道信息:

<?php

// Call set_include_path() as needed to point to your client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google Developers Console <https://console.developers.google.com/>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
  FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  try {
    // Call the channels.list method to retrieve information about the
    // currently authenticated user's channel.
    $channelsResponse = $youtube->channels->listChannels('brandingSettings', array(
      'mine' => 'true',
    ));

//example: print title and descriptions for the user default (first)

信道

$defChannel = $channelsResponse->getItems()[0]->getBrandingSettings()->getChannel();;
$channelTitle= $defChannel->title;
$channelDesc = $defChannel->description;

$htmlBody .= "<h3>Your Channel</h3>";
$htmlBody .= sprintf('Title: %s <br />',$channelTitle);
$htmlBody .= sprintf('Descriptions: %s <br />',$channelDesc);

END;


?>

<!doctype html>
<html>
<head>
<title>Channel Info</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>

我还没有测试过这段代码,但我希望你能得到一般的想法。

我可以在上面给出的链接上找到更多频道属性。