如何通过google api获取订阅列表:错误401无效凭据

时间:2014-03-05 10:45:00

标签: youtube-api oauth-2.0 google-api

我正在尝试通过google api获取订阅列表

我试过了 https://developers.google.com/youtube/v3/docs/subscriptions/list#try-it

它返回 ERROR

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}

我也使用google lib作为api,一切都与示例一致 但是当我想获得订阅列表时,它会给我这个错误。 https://code.google.com/p/google-api-php-client/

include_once "templates/base.php";
session_start();

set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';


 $client_id = '#################################';
 $client_secret = '########################';
 $redirect_uri = 'http://#########.com/authentications';


$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes(array (
                    "https://www.googleapis.com/auth/youtube",
                    "https://www.googleapis.com/auth/youtubepartner",
                    "https://www.googleapis.com/auth/youtube.readonly")
                    );
$client->setAccessType('offline');
$client->setApprovalPrompt('force');

$service = new Google_Service_YouTube($client);


if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = $redirect_uri ; //'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}


if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}


if ($client->getAccessToken()) {

  $list = $service->subscriptions->listSubscriptions('snippet');
  $_SESSION['access_token'] = $client->getAccessToken();
}

 ?>



<div class="box">
  <div class="request">
    <?php if (isset($authUrl)): ?>
      <a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
    <?php else: ?>
      <a class='logout' href='?logout'>Logout</a>
      <?php

        var_dump($list);

    ?>
    <?php endif ?>
  </div>


</div>

1 个答案:

答案 0 :(得分:0)

您可以使用YouTube API v2.0 – Subscriptions

使用此网址:gdata.youtube.com/feeds/api/users/<userId>/subscriptions?v=2

您可以将&max-results=50添加到网址以获得最大可能结果。

保存您获得的页面。然后你必须使用某种xml工具用yt:username提取元素并获取用户名列表。

我这样使用HTML-XML-utils

hxextract -x yt:username Subscriptions.xht > users.xht
hxpipe users.xht | grep - > users.txt

但是从元素中提取字符串可能是一个更好的解决方案。