PHP Google API客户端无法获取访问令牌(getAccessToken)

时间:2016-01-05 05:58:17

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

我尝试使用Google提供的示例脚本创建与Google YouTube API的连接:

https://developers.google.com/youtube/v3/code_samples/php#resumable_uploads

我使用的脚本是上传视频。

我已经创建了OAuth2凭据(客户端ID和密钥),这些已经放入示例脚本中:

$OAUTH2_CLIENT_ID = 'MY CLIENT ID';
$OAUTH2_CLIENT_SECRET = 'MY CLIENT SECRET';

注意:这些只是示例,而不是我的真实凭据:)但只是为了证明我正确地将正确的凭据复制到正确的变量。

我已经仔细检查过这些是正确的。但是当我尝试获取访问令牌时,它返回NULL:

var_dump($client->getAccessToken()); exit;
if ($client->getAccessToken()) {
.
.
.

我对Google API有点新意,所以我想从示例脚本开始,但不知道如何从这里开始。我觉得我完全按照指示行事。有任何想法吗?感谢

===

下面是完整的脚本,直到我退出。我确实做了一些小改动(显示错误,使用composer加载库 - v2.0.0-RC4),但不应该对脚本产生太大影响:

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'vendor/autoload.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 = 'MY CLIENT ID';
$OAUTH2_CLIENT_SECRET = 'MY CLIENT SECRET';

$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);
//$redirect = '';

$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.
var_dump($client->getAccessToken()); exit;
if ($client->getAccessToken()) {
.
.
.

0 个答案:

没有答案