0
votes

I'm creating a small YouTube Analytics API script and i'm stuck trying to exchange a user authorization code for an access token.

I've managed to get to the point of obtaining the authorization token, but I don't know how to "Submit a POST request to Google".

What i think will work:

if (isset($_GET['code'])) {
    // Send Post Request To Exchange Access Code
}

But i don't know what to put between the condition to actually swap the code. When i visit the location

https://accounts.google.com/o/oauth2/code={CODE}&client_id={ID}&client_secret={SECRET}&redirect_uri={REDIRECTURL}&grant_type=authorization_code

I get an unknown URL.

1
Your URL has to be https://accounts.google.com/o/oauth2/token?code={CODE}&client_id={ID}&client_secret={SECRET}&redirect_uri={REDIRECTURL}&grant_type=authorization_code - paolo
Understood! How do i send a POST_REQUEST with it? I don't want my client secret to be visible. - Conor Reid

1 Answers

0
votes

You need to use cURL (or a similar library), as that's the way your server talks directly to Google to exchange the access code. Your users won't see your secret, as cURL does the request from your end. cURL will then let you take the response that comes back and extract and extract the access token, which you'll then send in the header of every request to the Analytics API (or, if you had access_type set to offline, you'll be able to extract a refresh token). Code might look something like this (tailor for your particular needs):

function get_oauth2_token($code) {

global $client_id;
global $client_secret;
global $redirect_uri;

$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
"code" => $code,
"client_id" => $client_id,
"client_secret" => $client_secret,
"redirect_uri" => $redirect_uri,
"grant_type" => "authorization_code"
);

$curl = curl_init($oauth2token_url);

curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$json_response = curl_exec($curl);
curl_close($curl);

$authObj = json_decode($json_response);

if (isset($authObj->refresh_token)){
    //refresh token only granted on first authorization for offline access
    //save to db for future use (db saving not included in example)
    global $refreshToken;
    $refreshToken = $authObj->refresh_token;
}

$accessToken = $authObj->access_token;
return $accessToken;
}

With that access token returned, you can then make your API calls.