1

我正在尝试找出一种方法来创建播放列表、上传视频等,而无需自己进行用户身份验证,而是让服务器使用我的 YouTube 帐户为他们执行此操作。

我开始只是做一个添加mine参数的频道列表,因为这需要身份验证。

这是我使用的代码,结果可以在http://www.daysofthedead.net/testing/playlist.php看到

您可以在底部看到代码有效,因为我可以从不需要身份验证的搜索中提取结果。但是频道列表是空的,需要认证。

<?php
require_once 'GoogleClient/Google_Client.php';
require_once 'GoogleClient/contrib/Google_YoutubeService.php';

// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'xxxxxxxxxx.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = 'xxxxxxxxxx8@developer.gserviceaccount.com';

// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = 'xxxxxxxxxx-privatekey.p12';

$client = new Google_Client();
$client->setApplicationName("Google YouTube Sample");

// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
if (isset($_SESSION['token'])) {
 $client->setAccessToken($_SESSION['token']);
}

// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
    SERVICE_ACCOUNT_NAME,
    array('https://www.googleapis.com/auth/youtube'),
    $key)
);

$client->setClientId(CLIENT_ID);
$service = new Google_YouTubeService($client);

# User to search Youtube for.
$search_user = "BruceLeeOfficialPage";

# listSearch optional parameters
$search_optParams = array('part' => 'snippet', 'q' => $search_user, 'maxResults' => 2, 'type' => 'video');
# Search YouTube
$search = $service->search->listSearch($search_optParams);

# listChannels optional parameters.
$channel_optParams = array('maxResults' => 50, 'mine' => 'true');
# Get YouTube user's channel information
$channel = $service->channels->listChannels('snippet', $channel_optParams);

// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
if ($client->getAccessToken()) {
  $_SESSION['token'] = $client->getAccessToken();
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <link rel='stylesheet' href='style.css' />
</head>
<body>
<header><h1>YouTube API v3 Sample App</h1></header>
<div class="box">

<?php if(isset($search)): ?>
<div class="search"><H1>Search:</H1>
<pre><?php print_r($search); ?></pre></div>
<?php endif ?>

<?php if(isset($channel)): ?>
<div class="channel"><H1>Channel:</H1>
<pre><?php print_r($channel); ?></pre></div>
<?php endif ?>

</div>
</body>
</html>

有人能帮我解决这个问题吗?有什么解决办法吗?代码示例将非常感激。谢谢你。

4

1 回答 1

3

您正在尝试使用 OAuth 2 for Service Accounts 流程,YouTube API 不支持该流程。支持的流程列表记录在https://developers.google.com/youtube/v3/guides/authentication

通常,您需要使用 Web 浏览器完成一次支持流程,从那时起,您可以在无需用户干预的情况下提出请求。

于 2013-02-04T22:51:20.077 回答