The aim is to create a Watch Later button using the YouTube API. When a user clicks the button, the video is saved into the user\'s Watch Later playlist. Simila
The Watch Later playlist is the playlist with id WL
. You can add a video to this playlist the same way as the other Youtube playlists.
You will first need to go to your Google developer console :
Oauth Client ID
Then you can use the code below which will authenticate, retrieve an access token with https://www.googleapis.com/auth/youtube
scope and then add a video to your watch later playlist.
For the following Javascript & PHP samples, when a button is pressed, it logs-in the user if not already authenticated and add the video to the watch later playlist of the authenticated user.
This is based on api-samples provided by Google here.
Here is a live demo with the source code (as below)
Here is a fiddle. Replace your client id and add as Authorized JavaScript origins in developer console : https://fiddle.jshell.net
index.html :
Add to Watch Later playlist
Replace OAUTH2_CLIENT_ID
with your own client ID
In the API response, I check the following status code :
409
: the video already on playlist404
: the video isn't foundBased on google-api php sample :
install google-api client :
composer require google/apiclient:~2.0
The php script watchlater.php :
* For more information about using OAuth 2.0 to access Google APIs, please see:
*
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = 'YOUR_CLIENT_ID';
$OAUTH2_CLIENT_SECRET = 'YOUR_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);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
$videoId = "";
if (isset($_GET['video'])){
$videoId = $_GET['video'];
}
else if(isset($_SESSION['video'])){
$videoId = $_SESSION['video'];
}
if(isset($videoId) && !isset($_GET['state'])) {
file_put_contents('php://stderr', print_r("adding video to watch later playlist " . $videoId . "\n", TRUE));
$playlistId = "WL";
// 5. Add a video to the playlist. First, define the resource being added
// to the playlist by setting its video ID and kind.
$resourceId = new Google_Service_YouTube_ResourceId();
$resourceId->setVideoId($videoId);
$resourceId->setKind('youtube#video');
// Then define a snippet for the playlist item. Set the playlist item's
// title if you want to display a different value than the title of the
// video being added. Add the resource ID and the playlist ID retrieved
// in step 4 to the snippet as well.
$playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
$playlistItemSnippet->setTitle('First video in the test playlist');
$playlistItemSnippet->setPlaylistId($playlistId);
$playlistItemSnippet->setResourceId($resourceId);
// Finally, create a playlistItem resource and add the snippet to the
// resource, then call the playlistItems.insert method to add the playlist
// item.
$playlistItem = new Google_Service_YouTube_PlaylistItem();
$playlistItem->setSnippet($playlistItemSnippet);
$playlistItemResponse = $youtube->playlistItems->insert(
'snippet,contentDetails', $playlistItem, array());
$response = json_encode($playlistItem);
$_SESSION['video'] = "";
}
else{
file_put_contents('php://stderr', print_r("no video was specified", TRUE));
}
} catch (Google_Service_Exception $e) {
$response = htmlspecialchars($e->getMessage());
} catch (Google_Exception $e) {
$response = htmlspecialchars($e->getMessage());
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} else {
if(isset($_GET['video'])){
$_SESSION["video"] = $_GET['video'];
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
}
}
?>
Add to Watch Later playlist
Replace $OAUTH2_CLIENT_ID
and $OAUTH2_CLIENT_SECRET
with their respective value. Also, you have to set a redirect_uri in google console, here it will be http://localhost/watchlater.php
In the PHP version, you can see that I store video id in $_SESSION["video"]
to be able to add it immediately when google authentication redirect to watchlater.php
Here is a screen of google console Oauth Client ID
for this project (valid for the Javascript & PHP version above) :
Note that :
CLIENT_ID
and set Javascript OriginCLIENT_ID
, CLIENT_SECRET
, set Javascript Origin and set Redirect URINote for testing, I noticed that it can take some time to delete the video when doing it manually if you want to re-add it again