Posted on: 01.09.2020 Posted by: Alex D Comments: 0

Example code for connecting to API Analytics Google

Registering an OAuth 2.0 application with the Google API Console

1) Go to the Google Developers Console and create a new project.

2) After creating a project, go to the management page of this project and go to the control panel of the “API and services” section.

3) In the control panel, enable the API and services that you plan to use.

You must include Google Search Console API.

4) Go to the “Credentials” section. Click on “Create Credentials” – “OAuth Client ID” .

5) Specify the application type “Web Application”.

6) After creating the “Web Application”, you will receive a client ID and a secret key. Save this data.

Set php library composer google/apiclient.

You must install the php library to work with the Google API in PHP on your server ubuntu/linux.

You can get information about the php library and download for work here: github.com.
cd /var/www
composer require google/apiclient:"^2.0"

An example of obtaining an access token for accessing the Google API in PHP

Create file get_start_google_token.php

We connect the library to work with the Google API

require_once '../../../../../vendor/autoload.php';

Entering application parameters

ID application. (substitute your data)

define('GOOGLE_CLIENT_ID', '0000000-fgfhfhfghfghfghg.apps.googleusercontent.com');

Secret application. (substitute your data)

define('GOOGLE_CLIENT_SECRET', 'jhjhjhjhjhjhjhjhjhjhjhghj');

The address to which the user will be redirected after authorization. (substitute your address)

define('GOOGLE_CLIENT_REDIRECT_URL', 'https://spage.me/user/token/get_end_google_token.php');

Select the areas to which access will be requested.

Find out about it here.
define( 'SCOPES', implode( ' ', [
		'https://www.googleapis.com/auth/analytics'
		//Google_Service_Sheets::SPREADSHEETS,
		//Google_Service_Webmasters::WEBMASTERS,
		//'https://www.googleapis.com/auth/userinfo.profile',
		//'https://www.googleapis.com/auth/userinfo.email',
		//'https://www.googleapis.com/auth/plus.me'
	] ) );

Initializing Google Client.

$client = new Google_Client();
	$client->setClientId( GOOGLE_CLIENT_ID );
	$client->setClientSecret( GOOGLE_CLIENT_SECRET );
	$client->setRedirectUri( GOOGLE_CLIENT_REDIRECT_URL );
	$client->setScopes( SCOPES );
	$client->setAccessType( 'offline' );
	$client->setApprovalPrompt('force');

We display a link to open the authorization dialog window.

echo '<P>To do this, click the link: <A href="' .  $client->createAuthUrl() . '" target="_blank">Get statistics analytics.google.com</A></P>';

The user clicks on the link. The Google authorization window appears. The user is logged in.

Full code get_start_google_token.php.

<?php
require_once '../../../../../vendor/autoload.php';
$_SESSION['id_site'] = $id_site;
define('GOOGLE_CLIENT_ID', '00000');
define('GOOGLE_CLIENT_SECRET', '000000');
define('GOOGLE_CLIENT_REDIRECT_URL', 'https://spage.me/user/token/get_end_google_token.php');
define( 'SCOPES', implode( ' ', [
	'https://www.googleapis.com/auth/analytics'

] ) );
$client = new Google_Client();
$client->setClientId( GOOGLE_CLIENT_ID );
$client->setClientSecret( GOOGLE_CLIENT_SECRET );
$client->setRedirectUri( GOOGLE_CLIENT_REDIRECT_URL );
$client->setScopes( SCOPES );
$client->setAccessType( 'offline' );
$client->setApprovalPrompt('force');
echo '<H2>Connect statistics analytics.google.com to the site spage.me.</H2>
<P>To do this, click the link": <A href="'. $client->createAuthUrl().'">Get statistics analytics.google.com</A></P>";
?>

The system switches to php file get_end_google_token.php.

Create a php file get_end_google_token.php.

File logic.

require_once '../../../../../vendor/autoload.php';
define('GOOGLE_CLIENT_ID', '0000000-fgfhfhfghfghfghg.apps.googleusercontent.com');
define('GOOGLE_CLIENT_SECRET', 'jhjhjhjhjhjhjhjhjhjhjhghj');
define('GOOGLE_CLIENT_REDIRECT_URL', 'https://spage.me/user/token/get_end_google_token.php');
define( 'SCOPES', implode( ' ', [
   'https://www.googleapis.com/auth/analytics'
] ) );
$client = new Google_Client();
$client->setClientId( GOOGLE_CLIENT_ID );
$client->setClientSecret( GOOGLE_CLIENT_SECRET );
$client->setRedirectUri( GOOGLE_CLIENT_REDIRECT_URL );
$client->setScopes( SCOPES );
$client->setAccessType( 'offline' );
$client->setApprovalPrompt('force');

File get_start_google_token.php will transfer the parameter code to file get_end_google_token.php.

Now, knowing the parameter code, you can get a token.

Use function fetchAccessTokenWithAuthCode() and you will receive a token.

$response = $client->fetchAccessTokenWithAuthCode( $_GET['code'] );
$accessToken = $response['access_token']; // access token
$expiresIn = $response['expires_in']; // expires in 3600 (sec.) (1 hour)
$refreshToken = $response['refresh_token']; // refresh token - used to update access token
$scope = $response['scope']; // areas accessed
$tokenType = $response['token_type']; // type token
$idToken = $response['id_token']; // id token
$created = $response['created']; // token creation time

The token ($accessToken) is valid for only one hour.

But you know refresh token ($refreshToken) and you can always renew the token.

You must save $accessToken and $refreshToken in your database.

Full code get_end_google_token.php.

<?php
require_once '../../../../../vendor/autoload.php';
define('GOOGLE_CLIENT_ID', '00000');
define('GOOGLE_CLIENT_SECRET', '111111');
define('GOOGLE_CLIENT_REDIRECT_URL', 'https://spage.me/user/token/get_end_google_token.php');
define( 'SCOPES', implode( ' ', [
	'https://www.googleapis.com/auth/analytics',

] ) );
$client = new Google_Client();
$client->setClientId( GOOGLE_CLIENT_ID );
$client->setClientSecret( GOOGLE_CLIENT_SECRET );
$client->setRedirectUri( GOOGLE_CLIENT_REDIRECT_URL );
$client->setScopes( SCOPES );
$client->setAccessType( 'offline' );
$client->setApprovalPrompt('force');
if ( isset( $_GET['code'] ) ) {
	$response = $client->fetchAccessTokenWithAuthCode( $_GET['code'] );
	if (isset($response['error'])) {
		throw new Exception('<P>An error occurred while getting the token. Error: '.$response["error"].'. Error description: '.$response["error_description"].'</P>');
	}
	$accessToken = $response['access_token'];
	$expiresIn = $response['expires_in'];
	$refreshToken = $response['refresh_token'];
	$scope = $response['scope'];
	$tokenType = $response['token_type'];
	$idToken = $response['id_token'];
	$created = $response['created'];
	if ($accessToken) {
		echo "<P>Google Analytics statistics connected successfully.</P>";
		$link = mysqli_connect("localhost", $LG, $PS, $NM);
		mysqli_set_charset($link, 'utf8');
		$id_site = $_SESSION['id_site'];
		$id_user = $_SESSION['id_user'];
		$query_id_site_user = "UPDATE `site` SET `google_token`='".$accessToken."',`refresh_token`='".$refreshToken."' WHERE `id`='".$id_site."' AND `id_user`='".$id_user."'";
		$DB_id_site_user = mysqli_query($link, $query_id_site_user);
		mysqli_close($link);
	} else {
		echo "<P>Google Analytics statistics are not connected. Token not found.</P>";
	}
}
?>

How to refresh Google token.

Create a php file get_new_google_token.php.

File logic.

require_once '../../../../../vendor/autoload.php';
$clientId = '0000000-fgfhfhfghfghfghg.apps.googleusercontent.com'; // from google developer console
$clientSecret = 'jhjhjhjhjhjhjhjhjhjhjhghj'; // from google developer console
$refreshToken = '1/Kp0nrn2C7pjZHXM_gYDfjuekcPVx2UDKszrlcxzyvgw';// Get it from your database.
$client = new Google_Client();
$client->setClientId($clientId);
$client->setClientSecret($clientSecret);
$client->refreshToken($refreshToken);
$access_token = $client->getAccessToken();
$client->setAccessToken($access_token);

Now you can get a new token.

$new_token = $access_token[access_token];

Save the new token ($new_token) in your database.

Full code get_new_google_token.php.

<?php
$link = mysqli_connect("localhost", $LG, $PS, $NM);
mysqli_set_charset($link, 'utf8');
$query_id_site_user = "SELECT * FROM `site` WHERE `id`='".$id_site_user."' AND `id_user`='".$id_user_sp."'";
$DB_id_site_user = mysqli_query($link, $query_id_site_user);
$row = mysqli_fetch_array($DB_id_site_user);
$refreshToken = $row[refresh_token];
$old_Token = $row[google_token];
if ( $refreshToken ) {
	require_once '../../../../../vendor/autoload.php';
	$clientId = '0000';
	$clientSecret = '1111';
	$client = new Google_Client();
	$client->setClientId($clientId);
	$client->setClientSecret($clientSecret);
	$client->refreshToken($refreshToken);
	$access_token = $client->getAccessToken();
	$client->setAccessToken($access_token);
	$new_token = $access_token[access_token];
	if ( $new_token ) {
		$query_id_site_user = "UPDATE `site` SET `google_token`='".$new_token."' WHERE `id`='".$id_site_user."' AND `id_user`='".$id_user_sp."'";
		$DB_id_site_user = mysqli_query($link, $query_id_site_user);
		if ($DB_id_site_user){
			echo '<P>Token successfully updated.</P>';
		} else {
			echo '<P>Attention! Token NOT SAVED in the database.</P>';
		}
	} else {
	        echo '<P>Mistake! Token NOT UPDATED.</P>';
	}
} else {
	echo '<P>Database access denied. RefreshToken not received.</P>';
}
mysqli_close($link);
?>

How to access Google Analytics from API.

Create a php file get_analitics_google.php.

File logic.

$Google_ids = '12345678'; //Site ID from Google Analitics
$start_data = '2020-08-27';
$end_data = '2020-08-28';
$webpage = '/'; //URL page your site. May be '/user'
$tokenG = ''; //From your database
$postData = file_get_contents('https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A' . $Google_ids . '&start-date=' . $start_data . '&end-date=' . $end_data . '&metrics=ga%3Ausers&dimensions=ga%3AfullReferrer%2Cga%3AlandingPagePath&filters=ga%3AlandingPagePath%3D%40' . $webpage.'&access_token=' . $tokenG);
$obj_Google=json_decode($postData, true);//true - now it's an array
$obj_google_totals = $obj_Google['totalsForAllResults']['ga:users'];//API Google Total from day
echo '<BR>Google_totals='.$obj_google_totals;

You can look at the keys of the array $obj_Google. And access the fields of the array.

Echo 'https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A' . $Google_ids . '&start-date=' . $start_data . '&end-date=' . $end_data . '&metrics=ga%3Ausers&dimensions=ga%3AfullReferrer%2Cga%3AlandingPagePath&filters=ga%3AlandingPagePath%3D%40' . $webpage . '&access_token=' . $tokenG;

You will receive a link.

Install the plugin / extension JSON Viewer Awesome in your Chrome browser.

Now paste the link into the browser and at JSON Viewer Awesome you will see the structure of your array, fields and keys.

Now you know the structure of your array. Now you can build a graph. How to plot a graph from an array? Look here.

DEMO

Categories:

Leave a Comment