Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Query data from google analytics data api without google library and without composer

Hello,

I am coding an app in php and i want to query google analytics data api without the google library and without composer. I cannot use composer because i am on a shared server and cannot install it. I cannot use the google library because the library cannot query without using Google\Analytics\Data\V1beta\BetaAnalyticsDataClient, Google\Analytics\Data\V1beta\DateRange, Google\Analytics\Data\V1beta\Dimension, and Google\Analytics\Data\V1beta\Metric classes because they all use other classes that require composer.

I believe i have already mostly bypassed the BetaAnalyticsDataClient class with the code below (but not 100%). So it seems i have completed oauth2 requirements by asking for authorization code, trading that code for a token and now i want to take that token and get some actual data from the google database.

I have looked at doc after doc and video after video and git after git, cannot find anything that tells me how to do this. All seems to work but i am not getting any data back.

Just FYI this is my code, its original and took me days to write it reading docs. It is not copied from anywhere, i am the author.  I realize this may be custom but is it possible to get data without using the library?  Any  suggestions will be greatly appreciated.  🙂

<?php

session_start();


include_once('includes/functions.php'); //just one sanitation function (clearInput)

//init arrays

$response = [];
$analytics_data = [];
$ch = [];
$req_token_array = [];
$header_array = [];
$header_anal = [];
$cha = [];
$anal_post_data = [];
$anal_date_ranges = [];
$anal_dimension = [];
$anal_metrics = [];
$anal_order_by = [];

 

$propertyID = (int) 'ADD PROPERTY ID HERE';


$key_file_location = '/home/googlefiles/dashboard-plugin-454157.json';
putenv("GOOGLE_APPLICATION_CREDENTIALS=".$key_file_location);

//we will hard code the client id and client secret first in the
//cURL below and then use these vars when we know it works

$client_id = 'ADD CLIENT ID HERE'; //replace with a real id

$client_secret = 'ADD SECRET HERE';//replace with a real secret

$grant_type = 'authorization_code';

$redirect_uri = "https://www.example.com/dashboard.php";

$scope = "https://www.googleapis.com/auth/analytics.readonly";


//html link to start the process is on the bottom of this file

/*
**************************************
Part 2 - received permission from user
**************************************
*/


//if we get back the auth and scope from google
//then the user has allowed the app access to their
//google analytics account data

if(isset($_GET['code']) && isset($_GET['scope']))
{

//we received auth code and correct scope
//Now lets send the authcode back and exchange for a token
//using cURL

$google_authcode = cleanInput($_GET['code']);
$google_scope = cleanInput($_GET['scope']);
$token_endpoint = "https://www.googleapis.com/oauth2/v4/token";


if($google_scope != $scope)
{

echo "<pre>";
echo "Google scope is not correct - please contact support";
exit;
}

if(empty($google_authcode))
{

echo "<pre>";
echo "Google authcode is not correct - please contact support";
exit;
}

 

/*
*************************************
Part 3 trade auth code for use token
*************************************
*/

//state attribute can be whatever you want
//its just a value that is returned to prevent cross site request forgery attacks

//store cURL post values that we send to google into an array

$req_token_array = ['code' => $google_authcode,
'client_id' => $client_id,
'client_secret' => '$client_secret,
'grant_type' => 'authorization_code',
'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
'redirect_uri' => 'https://www.example.com/dashboard.php',
'response_type' => 'token'
];


//convert the array into a query string
$make_query = http_build_query($req_token_array);

//concat client_id : $client_secret and base64 the value
$cid_csecret = base64_encode($client_id.':'.$client_secret);


//predefine the header sent in cURL for token (step 3)
$header_array = ['Content-Type: application/x-www-form-urlencoded', 'Authorization: Basic '.$cid_csecret];


//alternative endpoint for token untested
//https://oauth2.googleapis.com/token

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v4/token'); //different endpoint for token than for auth key
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
//curl_setopt($ch, CURLINFO_HEADER_OUT, true);// for testing only
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); //dont really need
curl_setopt($ch, CURLOPT_POSTFIELDS, $make_query);


//$info = curl_getinfo($ch); //testing only

$response = curl_exec($ch); //returns json format
$response = json_decode($response);

if($e = curl_error($ch))
{

//if cURL error

echo "<pre>";
echo $e;
curl_reset($ch);
curl_close($ch);
exit;

}else{

//else no cURL error

curl_reset($ch);
curl_close($ch);

//did cURL return an object
//this is default
if(is_object($response))
{

$anal_token = cleanInput($response -> access_token);
$refresh_token = cleanInput($response -> refresh_token);
$token_scope = cleanInput($response -> scope);
$token_type = cleanInput($response -> token_type);


}elseif(is_array($response))
{

//did cURL return an array
//this is just in case google
//changes their process

$anal_token = cleanInput($response['access_token']);

if(isset($response['refresh_token']))
{
$refresh_token = cleanInput($response['refresh_token']);
}

$token_scope = cleanInput($response['scope']);
$token_type = cleanInput($response['token_type']);


}else{

echo "Google token not received - contact support";
exit;

}//close if elseif response


/*
*************************************
Part 4 use token or refresh token
and get some google analytics data
*************************************
*/

if(isset($_GET['state']) && !empty($_GET['state']) && $token_scope == $scope && $_GET['state'] == $_SESSION['random_state'] )
{


//valid returned token response

//reset state field and session value
$random_state = '';
$_SESSION['random_state'] = '';

//todo
//if there is a refresh token
//store the refresh token


$startdate = "2023-04-01";
$enddate = "2023-06-01";

//possible alternate endpoint ?
//$endpoint_data = "https://analyticsdata.googleapis.com/properties/".$propertyID.":runReport";

$endpoint_data = "https://analyticsdata.googleapis.com/v1beta/properties/".$propertyID.":runReport";

//predefine the header sent in cURL for analytic data (step 4)
$header_anal = ['Content-Type: application/json', 'Accept: application/json', 'Authorization: Bearer '.$anal_token];


//i am better at coding arrays freehand than i am doing json so i will
//make an array then convert it to json
//===============================================

//cannot use these classes below because google library classes require composer

//what is an alternative ??
//==================================================

$anal_date_ranges = [ new DateRange([
'startDate' => "23-04-01",
'endDate' => "today"
])
];

$anal_dimension = [ new Dimension([
'name' => "date"
]),

new Dimension([
'name' => "pagePath"
])
];

$anal_metrics = [ new Metric([
'name' => "screenPageViews"
])

];

 

$anal_post_data = [
'property' => 'properties/'.$propertyID,
'dateRanges' => $anal_date_ranges,
'dimensions' => $anal_dimension,
'metrics' => $anal_metrics
];

 

$anal_post_json = json_encode($anal_post_data);


$cha = curl_init();
curl_setopt($cha, CURLOPT_URL, $endpoint_data); //different endpoint
curl_setopt($cha, CURLOPT_HTTPHEADER, $header_anal);
//curl_setopt($cha, CURLINFO_HEADER_OUT, true);// for testing only
curl_setopt($cha, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cha, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($cha, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($cha, CURLOPT_TIMEOUT, 20);
curl_setopt($cha, CURLOPT_POST, 1);
curl_setopt($cha, CURLOPT_FORBID_REUSE, 1); //dont really need
curl_setopt($cha, CURLOPT_POSTFIELDS, $anal_post_json);


//$info = curl_getinfo($cha); //testing only

$analytics_data = curl_exec($cha); //returns json format

//test to see if we have data in repsonse

print_r($analytics_data);
echo "hello there";
//print_r($anal_post_data);

curl_reset($cha);

curl_close($cha);
exit;

 

$analytics_data = json_decode($analytics_data, true);

if($e = curl_error($cha))
{

//if cURL error

echo "<pre>";
echo $e;
curl_reset($cha);
curl_close($cha);
exit;

}else{

//else no cURL error

curl_reset($cha);
curl_close($cha);

//did cURL return an object
//this is default
if(is_object($analytics_data))
{

print_r($analytics_data);

//i stopped the process here until we have data
exit;


}elseif(is_array($analytics_data))
{

//did cURL return an array
//this is just in case google
//changes their process


print_r($analytics_data);
exit;

 

 

}else{

echo "Google Analytics Data not received - contact support";
exit;

}//close if elseif analytics_data


}//close else $e

}else{

//not valid

echo "<pre>";
echo "Invalid response from token server - please contact support";
exit;

}//close else state

}//close else $e

}else{


/*
*************************************
Step 1 ask customer for access
to their google data
*************************************
*/


//set up a random value for the state attribute
//this value will be stored in session and is sent
//back with the cURL response value
//then we compare it to the session value
//this will ensure that the response is value
//and secure against cross site scripting

$random_state = uniqid('ABC', true);

$_SESSION['random_state'] = $random_state;


//with authorization code we use this endpoint
$request_consent = "https://accounts.google.com/o/oauth2/v2/auth?client_id=".$client_id."&redirect_uri=https://www.example.com/dashboard.php&scope=https://www.googleapis.com/auth/analytics.readonly&respo...".$random_state;


//first we need to request access to the analytics account data

echo "<p>This analytics plugin needs access to your google analyics account for data viewing. This app only views data and displays it on the page.
It does not record, store, or use your analyics data in any other way. It has readonly access. Please click the link below to allow access.</p>";

echo "<br>";

echo "<a href=".$request_consent.">Authorize Access</a>";

echo "<br>";

}//close else code and scope

//display data in html below

 

2 0 2,539
0 REPLIES 0