Home » Php » php – Google YouTube API Refresh Token not being sent

php – Google YouTube API Refresh Token not being sent

Posted by: admin July 12, 2020 Leave a comment


I’m attempting to use the Google YouTube Data API with PHP based on Google’s documentation here: https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Refreshing_a_Token. My problem comes in when authenticating with OAuth. I’m using the following authorization URL which is identical to the one the docs say to use except for my redirect uri and application key, obviously.

$this->authorizationUrl = 'https://accounts.google.com/o/oauth2/auth?';
$this->authorizationUrl .= 'client_id=' . $this->applicationKey . '&';
$this->authorizationUrl .= 'redirect_uri=' . $this->redirect_uri . '/account.php?action=youtube_oauth&';
$this->authorizationUrl .= 'scope=https://gdata.youtube.com&';
$this->authorizationUrl .= 'response_type=code&';
$this->authorizationUrl .= 'access_type=offline';

Then, as the docs say to, I cURL the following:

$curl_options = Array(
            CURLOPT_POSTFIELDS => Array(
                'code' => $code,
                'client_id' => $this->applicationKey,
                'client_secret' => $this->applicationSecret,
                'redirect_uri' => $this->redirect_uri . '/account.php?action=youtube_oauth',
                'grant_type' => 'authorization_code'
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL => 'https://accounts.google.com/o/oauth2/token'

However, my response never gives me a refresh_token like their documentation says it should. I just get the other three response items.

Some questions like this one: Get refresh token google api have said to use approval_prompt=force, but that doesn’t work either and entirely defeats the purpose of having access_type=offline.

Any ideas as to why I’d get a valid response with 3 of the 4 response items?

How to&Answers:

From the offline access portion of the OAuth2.0 docs:

When your application receives a refresh token, it is
important to store that refresh token for future use. If your
application loses the refresh token, it will have to re-prompt the
user for consent before obtaining another refresh token. If you need
to re-prompt the user for consent, include the approval_prompt
parameter in the authorization code request, and set the value to

So, when you have already granted access, subsequent requests for a grant_type of authorization_code will not return the refresh_token, even if access_type was set to offline in query string of the consent page.

As stated in the quote above, in order to obtain a new refresh_token after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt to force.


PS This change was announced in a blog post as well.


You can try google oauth2 playground (https://code.google.com/oauthplayground/) and see what the differences are between your params and there.