Patrioticcow
Patrioticcow

Reputation: 27038

PHP. How to get the access token. Authenticating with OAuth 2.0 for Google API

I found this function that supposedly gets the accessToken, but I get nothing. I do have the $_REQUEST['code'], and the other information needed in this function.

Any ideas what is wrong here? Thanks.

//Oauth 2.0: exchange token for session token so multiple calls can be made to api
if(isset($_REQUEST['code'])){
    $_SESSION['accessToken'] = get_oauth2_token($_REQUEST['code']);
}

//returns session token for calls to API using oauth 2.0
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;
}

Upvotes: 3

Views: 45413

Answers (5)

John Slegers
John Slegers

Reputation: 47081

This is what I did to get my access token and refresh token.

Create a file that contains the following code :

<?php

if (isset($_GET['code'])) {
    // try to get an access token
    $code = $_GET['code'];
    $url = 'https://accounts.google.com/o/oauth2/token';
    $params = array(
        "code" => $code,
        "client_id" => YOUR_CLIENT_ID,
        "client_secret" => YOUR_CLIENT_SECRET,
        "redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
        "grant_type" => "authorization_code"
    );

    $ch = curl_init();
    curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
    curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
    curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
    $output = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    if ($info['http_code'] === 200) {
        header('Content-Type: ' . $info['content_type']);
        return $output;
    } else {
        return 'An error happened';
    }
} else {

    $url = "https://accounts.google.com/o/oauth2/auth";

    $params = array(
        "response_type" => "code",
        "client_id" => YOUR_CLIENT_ID,
        "redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
        "scope" => "https://www.googleapis.com/auth/plus.me"
    );

    $request_to = $url . '?' . http_build_query($params);

    header("Location: " . $request_to);
}

Now, replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your client ID and client secret.

Make sure your scope is correct. For example, it should be https://www.googleapis.com/auth/analytics if you want to get access to Analytics.

If you run the file, you should get an OAuth2 approval screen.

If you now press Accept, you should get a result that looks like this:

{
  "access_token" : YOUR_ACCESS_TOKEN,
  "token_type" : "Bearer",
  "expires_in" : 3600,
  "refresh_token" : YOUR_REFRESH_TOKEN
}

The result may contain additional fields, depending on which scope you're applying for.

Upvotes: 5

Fred
Fred

Reputation: 41

I had the same error, and I found that adding

curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);

to allow the request follow a redirect solved it quickly. I hope that helps someone else!

Upvotes: 0

user2883217
user2883217

Reputation: 1

From section 4.4.2 of "The OAuth 2.0 Authorization Protocol draft-ietf-oauth-v2-20"

The client makes a request to the token endpoint by adding the following parameters using the "application/x-www-form-urlencoded" format in the HTTP request entity-body:

So the POSTed parameters should be submitted in the form of a string, not an array. This is mentioned in the PHP manual for curl_setopt too.

So instead of posting $clienttoken_post, you might want to post http_build_query($clienttoken_post,'','&').

This might not solve all your problems, but it's probably a step in the right direction.

Upvotes: 0

Paul S Chapman
Paul S Chapman

Reputation: 832

that code looks familiar - I'm using roughly the same code - there are two things you can try.

  1. Use echo to echo the response to the Browser

    echo $json_response;

  2. Get hold of Fiddler and use the following line before the call to curl_exec

    curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:8888');

'fraid I've not got it working either - the response I am getting is

{ 
     "error" : "invalid_request" 
}

Now if anyone knows how what is wrong with this ;)

Upvotes: 1

groffhibbitz
groffhibbitz

Reputation: 96

I don't see anything wrong with your code, but you may want to try refreshing the client secret and see if that helps. Additionally, I would suggest you see exactly what the response is coming back from your curl command, I suspect it's "invalid_grant".

A much better way to do this is to use google's php api client:

https://code.google.com/p/google-api-php-client/

which handles most of the communication for you. The examples there are very easy to use. It mostly depends on which google service you are trying to access.

Upvotes: 2

Related Questions