加载令牌脚本时: token.php
<?php
require_once 'vendor/autoload.php';
session_start();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* 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 = '516195178663-5pgnd88unc38khttmgj67scinlhk7caf.apps.googleusercontent.com'; // Enter your Client ID here
$OAUTH2_CLIENT_SECRET = 'QLsIeOBhHLIee4_d-OOqjblK'; // Enter your Client Secret here
$REDIRECT = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$APPNAME = "BrickFame";
$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');
$client->setApprovalPrompt('force');
// 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'])) {
$client->setAccessToken($_SESSION['token']);
echo "Access Token: " . json_encode($_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('contentDetails', array('mine' => 'true'));
$htmlBody = '';
foreach ($channelsResponse['items'] as $channel) {
// Extract the unique playlist ID that identifies the list of videos
// uploaded to the channel, and then call the playlistItems.list method
// to retrieve that list.
$uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads'];
$playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
'playlistId' => $uploadsListId,
'maxResults' => 50
));
$htmlBody .= "<h3>Videos in list $uploadsListId</h3><ul>";
foreach ($playlistItemsResponse['items'] as $playlistItem) {
$htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'],
$playlistItem['snippet']['resourceId']['videoId']);
}
$htmlBody .= '</ul>';
}
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to <a href="$authUrl">authorise access</a> before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>My Uploads</title>
</head>
<body>
<?php echo $htmlBody;?>
</body>
</html>
我可以获取访问令牌并显示刷新令牌,并将其保存在token.txt
下
Access Token: {"access_token":"ya29.Ci8tA-3KvN7LE03mLLWsJJOsKHPr3ArvEw9xDaCX8wpFxGM-VpLswYwR1Mnhc7wS1Q","token_type":"Bearer","expires_in":3600,"refresh_token":"1\/BopX8bClCDuDkg0WO9KKyvxKMC-y1GiFhFOO8JQ5HkU","created":1469621552}
但是在访问上传脚本时: api.php
<?php
$key = file_get_contents('token.txt');
require_once 'vendor/autoload.php';
$client_id = '516195178663-5pgnd88unc38khttmgj67scinlhk7caf.apps.googleusercontent.com'; // Enter your Client ID here
$client_secret = 'QLsIeOBhHLIee4_d-OOqjblK'; // Enter your Client Secret here
$videoPath = "videos/example.mkv";
$videoTitle = "Just an Example Title";
$videoDescription = "This is the YouTube video's description";
$videoCategory = "22";
$videoTags = array("first tag","second tag","third tag");
try{
// Client init
$client = new Google_Client();
$client->setClientId($client_id);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAccessToken($key);
$client->setClientSecret($client_secret);
if ($client->getAccessToken()) {
/**
* Check to see if our access token has expired. If so, get a new one and save it to file for future use.
*/
if($client->isAccessTokenExpired()) {
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents($key, $client->getAccessToken());
}
$youtube = new Google_Service_YouTube($client);
// Create a snipet with title, description, tags and category id
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle($videoTitle);
$snippet->setDescription($videoDescription);
$snippet->setCategoryId($videoCategory);
$snippet->setTags($videoTags);
$snippet->setDefaultLanguage("en");
$snippet->setDefaultAudioLanguage("en");
$recordingDetails = new Google_Service_YouTube_VideoRecordingDetails();
$recordingDetails->setLocationDescription("United States of America");
$recordingDetails->setRecordingDate("2016-01-20T12:34:00.000Z");
$locationdetails = new Google_Service_YouTube_GeoPoint();
$locationdetails->setLatitude("38.8833");
$locationdetails->setLongitude("77.0167");
$recordingDetails->setLocation($locationdetails);
// Create a video status with privacy status. Options are "public", "private" and "unlisted".
$status = new Google_Service_YouTube_VideoStatus();
$status->setPrivacyStatus("public");
$status->setPublicStatsViewable(false);
$status->setEmbeddable(false); // Google defect still not editable https://code.google.com/p/gdata-issues/issues/detail?id=4861
// Create a YouTube video with snippet and status
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setRecordingDetails($recordingDetails);
$video->setStatus($status);
// Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
// for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
$chunkSizeBytes = 1 * 1024 * 1024;
// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);
// Create a request for the API's videos.insert method to create and upload the video.
$insertRequest = $youtube->videos->insert("status,snippet,recordingDetails", $video);
// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
/**
* Video has successfully been uploaded, now lets perform some cleanup functions for this video
*/
if ($status->status['uploadStatus'] == 'uploaded') {
// Actions to perform for a successful upload
}
// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(true);
} else{
// @TODO Log error
echo 'Problems creating the client';
}
} catch(Google_Service_Exception $e) {
print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
print "Stack trace is ".$e->getTraceAsString();
}catch (Exception $e) {
print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
print "Stack trace is ".$e->getTraceAsString();
}
?>
Caught Google service Exception 0 message is refresh token must be passed in or set as part of setAccessTokenStack trace is #0 /home/vol11_2/freecluster.eu/fceu_18534127/htdocs/vendor/google/apiclient/src/Google/Client.php(246): Google_Client->fetchAccessTokenWithRefreshToken(NULL) #1 /home/vol11_2/freecluster.eu/fceu_18534127/htdocs/api.php(29): Google_Client->refreshToken(NULL) #2 {main}
我可能错过了什么?可能是我的文件错误吗? 我不明白这句话:刷新令牌必须传入或设置为setAccessTokenStack跟踪的一部分#0
任何人都可以指导我吗? 谢谢 ! :)