Using OAuth 2.0 to access Analytics User Data?

Discussion in 'PHP' started by mokimofiki, Jan 6, 2012.

  1. #1
    I am currently working on a way to access and run Analytics reports using the PHP OAuth 2.0 method. I have the authentication working and it returns a token that is displayed at the end. My question is How do I use the Token it returns to access the data within Analytics?

    There is almost no documentation and what Google does provide is less than helpful.

    Here is the working part of the code currently:
    <?php
    session_start();
    
    $client_id = "of course my client id";
    $client_secret = "my client secret";
    $redirect_uri = "http://www.skytecsolutions.com/projects/GA/php2/index.php";
    $scope = "https://www.googleapis.com/auth/analytics.readonly";
    $state = "";
    $access_type = "offline";
    
    
    $loginUrl = "https://accounts.google.com/o/oauth2/auth?scope=$scope&state=$state&redirect_uri=$redirect_uri&response_type=code&client_id=$client_id&access_type=$access_type";
    echo "<a href='$loginUrl'>Login with Google account using OAuth 2.0</a>";
    
    
    //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)){
    		global $refreshToken;
    		$refreshToken = $authObj->refresh_token;
    	}
    
    	$accessToken = $authObj->access_token;
    	return $accessToken;
    }
    ?>
    
    <?php echo "<br />Token is: ".$_SESSION['accessToken']."<br />"; ?>
    Code (markup):
     
    mokimofiki, Jan 6, 2012 IP