Jump to content

Youtube refresh token


bravo14

Recommended Posts

Hi all

 

I am trying to use the YouTube API, and have the site built in such a way that a user deosn't need to authorise access every time.  Below is the code I am using, however I am not getting a refresh token generated.

 

 

<?php
 require '../../library/config.php';
// Call set_include_path() as needed to point to your client library.
set_include_path($shopConfig['url'] . 'fullthrottle/videos/google-api/');
require_once 'google-api/src/Google/Client.php';
require_once 'google-api/src/Google/Service/YouTube.php';
 
/*
 * 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 = $youtube['client_id'];
$OAUTH2_CLIENT_SECRET = $youtube['client_secret'];
$REDIRECT = $shopConfig['url'].'fullthrottle/videos/upload.php';
$APPNAME = $youtube['app_name'];
$ACCESS_TOKEN = $youtube['access_token'];
 
$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'])) {
    $client->setAccessToken($_SESSION['token']);
    //echo '<code>' . $_SESSION['token'] . '</code>';
}
 
// 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'];
            //print_r ($channel);

            $playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
                'playlistId' => $uploadsListId,
                'maxResults' => 50
            ));
 
            $htmlBody .= "<h3>Videos in list $uploadsListId</h3><ul>";
            foreach ($playlistItemsResponse['items'] as $playlistItem) {
            print_r($playlistItem);
                $htmlBody .= sprintf('<li>'. $playlistItem['snippet']['title'].' <img src="'.$playlistItem['snippet']['thumbnails']['high']['url'].'" style="max-width:200px"/>'.$playlistItem['snippet']['description'].'</li>');
            }
            $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>

 

Also do I need to store the access tokens in a database at all for them to be used in the future?

 

Thanks in advance

Link to comment
Share on other sites

I have added that to

 

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
    echo '<code>' . $_SESSION['token'] . '</code>';
    $client->getRefreshToken();
//echo '<code>'.$this->token['refresh_token'].'</code>';
}

but I am still not getting a refresh token, and am having to login every time

Link to comment
Share on other sites

$client->getRefreshToken() returns the refresh token. You're not doing anything with the return value.

 

From the docs:

/**
* Get the OAuth 2.0 refresh token.
* @return string $refreshToken refresh token or null if not available
*/
public function getRefreshToken()
{
    return $this->getAuth()->getRefreshToken();
}
Edited by scootstah
Link to comment
Share on other sites

Simply acquiring the refresh token does nothing on its own. The refresh token is used to "refresh" the access token. Normally in OAuth2, the access token is short-lived and expires quickly, usually in a few hours. You must send the access token in an Authorization header for each request so that the endpoint can authenticate you. When the access token expires, you would then send a different request to refresh it and get a new access token, without having to enter credentials again.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.