Please someone help me, I'm stuck in this problem since last 7 days...
I want to do something like this. Suppose i have multiple users property id, Client ID and Client secret and i using this API :
$apiEndpoint = 'https://analyticsdata.googleapis.com/v1beta/properties/'.env('ANALYTICS_PROPERTY_ID').':runReport';
Now I want to get Google Analytics data of particular user. And My Curl code this :
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $apiRequestEndpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $requestData,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer '.$accessToken
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
$requestData = [
'dateRanges' => [
[
'startDate' => $request->startDate,
'endDate' => $request->endDate
]
],
'dimensions' => [
[
'name' => 'sessionDefaultChannelGroup'
],
[
'name' => 'date'
]
],
'metrics' => [
[
'name' => 'totalUsers'
],
],
'dimensionFilter' => [
'filter' => [
'fieldName' => 'sessionDefaultChannelGroup',
'inListFilter' => [
'values' => ['Organic Search']
]
]
],
'orderBys' => [
[
'dimension' => [
'orderType' => 'NUMERIC',
'dimensionName' => 'date'
]
]
],
'keepEmptyRows' => true,
'metricAggregations' => [
'TOTAL'
]
];
Generate access token code here :
use Google_Client;
use Google_Service_Analytics;
$client = new Google_Client();
// Set OAuth2 credentials
$client->setClientId($request->client_id);
$client->setClientSecret($request->client_secret);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// Set the correct redirect URI
$client->setRedirectUri('http://127.0.0.1:8000/goback');
if (!isset($_GET['code'])) {
$authUrl = $client->createAuthUrl();
return redirect($authUrl);
}
// Exchange authorization code for an access token
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$jsonData = $client->getAccessToken();
// Get the access token
if (isset($jsonData['access_token'])) {
$accessToken = $jsonData['access_token'];
return $accessToken;
} else {
return 'Access token not found in the JSON data.'
}
Note : Whenever I get google analytics date from a client. I have to login my google account every time.
So, I wish I don't have to login to my Gmail Account and get an access token for call a API. Can I do this and how ?
And I'm doing this feature in backend side PHP Laravel framework
composer require google/apiclient