【发布时间】:2015-04-05 02:35:56
【问题描述】:
我正在尝试创建一个 Youtube 上传脚本,该脚本不需要最终用户登录即可将视频上传到我的频道。问题是我可以获得访问令牌,但它会在一个小时不活动后过期。 我也不确定你可以从哪里得到“refresh_token”。
所以基本上我希望这个 Google API v3 脚本不需要任何客户端身份验证来上传视频。
根据我从谷歌的 API 文档中收集到的信息,如果我有“refresh_token”,我可以在不需要用户交互的情况下更新令牌。
请参阅下面我现有的代码。
<?php
$key = json_decode(file_get_contents('the_key.txt'));
require_once 'Client.php';
require_once 'Service/YouTube.php';
session_start();
$OAUTH2_CLIENT_ID = 'YOUR_CLIENT_ID.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = 'YOUR_SECRET_KEY';
$REDIRECT = 'http://example.com/test.php';//Must be exact as setup on google API console
$APPNAME = "Test upload app";
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setRedirectUri($REDIRECT);
$client->setApplicationName($APPNAME);
$client->setAccessType('offline');
// 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();
}
if (isset($_SESSION['token'])) {
//if session current save to file updates token key
$client->setAccessToken($_SESSION['token']);
echo '<code>' . $_SESSION['token'] . '</code><br>';
file_put_contents('the_key.txt', $_SESSION['token']);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
if($client->isAccessTokenExpired()) {
echo "Token Expired<br>Attempt Refresh: ";
$client->refreshToken($key->access_token);
//refresh token, now need to update it in session
$_SESSION['access_token']= $client->getAccessToken();
}
$_SESSION['token'] = $client->getAccessToken();
///////////////////////////////////////////////////////////////////////
//Run Upload script here from google Youtube API v3
//https://developers.google.com/youtube/v3/code_samples/php#resumable_uploads
///////////////////////////////////////////////////////////////////////
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = '<h3>Authorization Required</h3><p>You need to <a href="$authUrl">authorise access</a> before proceeding.<p>';
}
?>
<!doctype html>
<html>
<head>
<title>My Uploads</title>
</head>
<body>
<?php echo $htmlBody?>
</body>
</html>
如果有人可以查看此代码并告诉我我缺少什么,那就太好了。
【问题讨论】:
标签: php upload access-token google-api-php-client youtube-data-api