How to query data from Google Analytics of a site? - php

First of all I've never worked with google analytics before and now when I need to its a bit confusing to grasp the flow.
I did a lot of research online. What I come across is that, you need to have secret key which is created at developer console to authenticate. If I have this key, I can follow the standard examples found to retrieve any data I want for a site.
However I have a few doubts:
I'm working on freelance basis. So my client has given me access to their site's google analytics. So how to I read the analytical data like number of visitors and so on? Since my email already been allowed to access the data, I can query or do I still need the authentication key which should be in json format?
If I need to have the json key, how does it work? Is it like I create a key in my developer console https://console.developers.google.com and use this key to read the client data? Does this key act like a one stop center to authenticate myself in accessing any api from any site as long as they have added me inside their account?
I access my client's google analytical data here: https://analytics.google.com/analytics/web
Please explain to me the correct flow on how to read someone else's site data via PHP..I just need the overall idea.
Thank you in advance.

I try with an example
First of all the google client
composer require "google/apiclient"
In console.developers.google.com:
enable analytics api
define a project (eg: project-id)
2) the credentials_file
Create a service account at:
https://console.developers.google.com/iam-admin/serviceaccounts?project=project-id
By wich you will create the credential file at "path/to/the/service-account-credentials.json"
{
"type": "service_account",
"project_id": "project-id",
"private_key_id": "1234567890abcderf1234567890abcderf1234567890abcderf",
"private_key": "-----BEGIN PRIVATE KEY-----\nBASE64KEY=\n-----END PRIVATE KEY-----\n",
"client_email": "service-user#some.domain.gserviceaccount.com",
"client_id": "000000000000000000000000000000",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/cront-reriever-search-stats%40redooc-dot-com.iam.gserviceaccount.com"
}
3) defining what you want ($infos), for witch view you want ($viewId) and a credentials file ($credentials_file) and a date range, you will query the API and got results in $response
$infos= [
'users' => 'ga:users',
'pageviews' => 'ga:pageviews',
'pageviewsPerSession' => 'ga:pageviewsPerSession',
'unique page view' => 'ga:uniquePageviews',
'organicSearches' => 'ga:organicSearches',
'avgSessionDuration' => 'ga:avgSessionDuration',
'avgTimeOnPage' => 'ga:avgTimeOnPage',
];
$credentials_file='path/to/the/service-account-credentials.json';
$viewId='1600000'; // the view ID see imgae
$client = new \Google_Client();
$credentials_file = $this->checkServiceAccountCredentialsFile()) {
$client->setAuthConfig($credentials_file);
$client->addScope("https://www.googleapis.com/auth/analytics.readonly");
$analytics = new \Google_Service_AnalyticsReporting($client);
$response = getReport($viewId, $analytics, $infos, $DateStart, $DateEnd);
ADD getReport funtion
function getReport($viewId, $analytics, $dataAnalytics, $startDate, $endDate)
{
$dateRange = new \Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate($startDate);
$dateRange->setEndDate($endDate);
// Create the ReportRequest object.
$request = new \Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($viewId);
$request->setDateRanges($dateRange);
// Create the Metrics object.
$_metrics = [];
foreach ($dataAnalytics as $gaLabel => $gaValue) {
$metric = new \Google_Service_AnalyticsReporting_Metric();
$metric->setExpression($gaValue);
// $metric->setAlias($gaLabel);
$_metrics[] = $metric;
}
$request->setMetrics($_metrics);
$body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));
return $analytics->reports->batchGet($body);
}

You have two options to use Site Search for POST-based search engines:
Option 1: Configure your web application to append the query keywords to the end of the URL (e.g., http://www.example.com/search_results.php?q=keyword) and then set up Site Search as described in the previous section.
Option 2: Customize the tracking code on your results page to dynamically specify a virtual page path that includes the query keywords. The tracking code on the results page would look something like:
analytics.js: ga('send', 'pageview', '/search_results.php?q=keyword');
reference: https://support.google.com/analytics/answer/1012264?hl=en

Related

How to get Business Locations (and Reviews) via Service Account authentication

I can't get the Locations list from my business under my code (PHP using the "Google APIs Client Library for PHP" together with "Google_Service_MyBusiness" Classes) when I use the "Service Account" authentication, the API returns an empty Location List.
I already have the Prerequisites and did the Basic setup, by the way, I got the information with success on OAuth Playground, under a specific AccountId, Eg: 1111111111, provided by another response there on the "OAuth Playground".
(PS: I tested with my "PERSONAL" and "LOCATION_GROUP" accounts and got success with both).
But when I try to do it over my code via Server Account authentication, I can't get all the information, just the Account data that return another AccoundId, Eg: 2222222222, different of the Accounts that I got on OAuth Playground.
I did the Authentication process on OAuth Playground, using the same project where I created the "Service Account", by the way, the Permission of this "Service Account" is OWNER.
Previously, my role in my company on the Google My Business was "SITE_MANAGER", so I saw a forum answer where just "MANAGER" level/role can list the Locations, so I requested to change my permission, but continues as not the success on Locations listing.
So, I saw another Google My Business support article recommending create a "Location Group" and put my current "Location" into this group to make easy handle it, I did it and no success again.
My code is simple, based on Google guide, OAuth 2.0 for Server to Server Applications, and some Forum Questions (BTW the author's question have the same issue than me):
<?php
putenv('GOOGLE_APPLICATION_CREDENTIALS=service-account-credentials.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope("https://www.googleapis.com/auth/plus.business.manage");
require_once('Google_Service_MyBusiness.php');
$mybusinessService = new Google_Service_MyBusiness($client);
$accounts = $mybusinessService->accounts;
$accountsList = $accounts->listAccounts()->getAccounts();
foreach ($accountsList as $accKey => $account) {
var_dump('$account->name', $account->name);
$locations = $mybusinessService->accounts_locations;
$locationsList = $locations->listAccountsLocations($account->name)->getLocations();
var_dump('$locationsList', $locationsList);
// Final Goal of my Code
if (empty($locationsList)===false) {
foreach ($locationsList as $locKey => $location) {
$reviews = $mybusinessService->accounts_locations_reviews;
$listReviewsResponse = $reviews->listAccountsLocationsReviews($location->name);
$reviewsList = $listReviewsResponse->getReviews();
var_dump('$reviewsList', $reviewsList);
}
}
}
I expected the Location of my business (also the reviews, but it a next step), but I just got the empty Location list.
Finally, I got success using the ClientId/ClientSecret keys together with Refresh Token previously received on Google OAuth 2 Playground on the first time that I give permission to (my) App, instead "Service Account" authentication way :)
$client = new Google_Client();
$client->setClientId($clientId);
$client->setClientSecret($clientSecret);
$client->addScope("https://www.googleapis.com/auth/plus.business.manage");
$client->setSubject('my email user on GMB');
$client->refreshToken(' ###### ')
Now I got all the needed data for my application.

Get the number of visitors from script

I know how to access Google Analytics data with Data Studio or with Google Apps script in Javascript:
var account = Analytics.Management.Accounts.list().items[0];
var webProperties = Analytics.Management.Webproperties.list(account.id);
...
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
But in PHP, how is it possible to retrieve the number of visitors of a specific website or specific page, from a Google Analytics account / property / view? i.e.:
input: analytics account login/password/website code 'UA-XXXXX-Y'
output: [19873, 17873, 13999, 21032, ..., 16321] (i.e. the number of visits on www.example.com for each of the 30 last days, as a list of integers or JSON)
You can use Google Analytics API client in PHP.
Google analytic api client library
You can use the Query Explorer to create the queries to check.
Code Example:
$analytics = new analytics('username', 'password');
$analytics->setProfileByName('user.name');
//set the date range for which you want stats for
$analytics->setMonth(date('n'), date('Y'));
// it could also be $analytics->setDateRange('YYYY-MM-DD', 'YYYY-MM-DD'))
print_r($analytics->getVisitors());
print_r($analytics->getPageviews());
The above example used the Google Analytics API client in PHP. It was the first library released in PHP. Six years later, this software is outdated. Google changed the API.
As an alternative you can use GAPI library.
Above is the example how it would work, you can include gapi class to make it functional.
GAPI Analytic Library
Another way is that you can use the Google Analytics Reporting API v4 for PHP.
You can obtain this using composer:
composer require google/apiclient:^2.0
Guide to usage of this library is at github
I use this package:
https://github.com/google/google-api-php-client
You can use it to access all the Google APIs from PHP, including of course Google Analytics
Here's an example of how to use it:
// create client object and set app name
$client = new Google_Client();
$client->setApplicationName('Your app name'); // name of your app
// set assertion credentials
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'your_analytics_email#gmail.com', // email you added to GA
[
'https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents('/your/key/file.p12') // keyfile you downloaded
]
)
);
// other settings
$client->setClientId('your-client-id'); // from API console
$client->setAccessType('offline_access'); // this may be unnecessary?
// create service and get data
$service = new Google_AnalyticsService($client);
$from_date = date("Y-m-d",strtotime("-30 days")); // A month
$to_date = date("Y-m-d");
$response = $service->data_ga->get(
"ga:profile_id", // profile id
"$from_date", // start date
"$to_date", // end date
"ga:uniquePageviews",
[
'dimensions' => 'ga:pagePath', // Dimensions you want to include, pagePath in this example
'sort' => '-ga:uniquePageviews', // Sort order, order by unique page views from high to low in this case
'filters' => 'ga:pagePath=~\/articles\/[a-zA-Z0-9\-]+', // example url filter
'max-results' => '50' // Max results
]
);
foreach ($response["rows"] as $row) {
// ...do whatever you want with the results
}
Also, here's a guide on how to use the Google APIs:
https://developers.google.com/api-client-library/php/start/get_started
EDIT: You need to create credentials to access the Analytics API. You do it here: https://console.cloud.google.com/flows/enableapi?apiid=analyticsreporting.googleapis.com&credential=client_key. You need to register a project first, and then create the credentials. There are three options: API key, OAuth client ID and Service Account Key. I didn't want to use OAuth, so I used the Service Account Key. You can try using the API Key, in which case replace the $client->setAssertionCredentials(...) call for $client->setDeveloperKey(your_api_key). You can't use username and password directly AFAIK.

How can I access full referral path for one session/user through Google Reporting API V4

How can I access the full referral path for one session/user through Google Reporting API V4 ? In this case in PHP.
For example we have following code found on Google's Reporting API V4 Documentation.
(https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php)
function getReport(&$analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "<REPLACE_WITH_VIEW_ID>";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
This part is interesting:
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
Dimensions & Metrics Explorer
(https://developers.google.com/analytics/devguides/reporting/core/dimsmets)
The path of the referring URL (e.g., document.referrer). If someone
places on their webpage a link to the property, this is the path of
the page containing the referring link.
The full referring URL including the hostname and path.
I am assuming that I have to go this way just fetching the desired dimensions/metrics:
$sessions->setExpression("ga:referralPath");
$sessions->setAlias("referral_path");
or
$sessions->setExpression("ga:fullReferrer");
$sessions->setAlias("full_referrer");
Would be this the right approach?
If not is there another way to accomplish this?
And another question:
When making a request with this metrics/dimensions:
$sessions->setExpression("ga:referralPath");
$sessions->setAlias("referral_path");
How Google knows from which session to take the referralPath?
Try to read through Traffic Sources - Dimensions and Metrics, this reference document lists and describes all the dimensions and metrics available through the Real Time Reporting API.
Here's a sample of dimension: rt:referralPath - The path of the referring URL (e.g. document.referrer). If someone places a link to your property on their website, this element contains the path of the page that contains the referring link. This value is only set when rt:medium=referral.
Note: Use Google Analytics superProxy to handle many of the implementation details of working with Google Analytics APIs on authentication, caching, and transforming API responses to formats used directly with visualization and chart libraries.
You may also try to read Management API, this API is a guides that will help you initially get an application up and running and then the documentation will dive into the various topics which should help you interact with the API to perform such things as account, user, and data management. There is also a complete set of reference documents, which give details of every parameter of each API endpoint and include API sample code.

Getting campaign stats (e.g. Clicks, CTR, CPC, etc.) via AdWords API

What I'm trying to currently do is fetch Campaign statistics such as Clicks, Impressions, CTR, Average CPC and etc for a particular campaign. Unfortunately, I can't find how to do it via the AdWords API.
What I've found up till now is that,
Maybe, in an earlier version of the CampaignService, we were able to obtain stats by doing something like $campaign->campaignStats. Unluckily, I'm using V201506 and in it there is no campaignStats object/variable.
I probably can get these stats using the 'CAMPAIGN_PERFORMANCE_REPORT' but it needs to be downloaded and I don't want to download the report. I just want an array or something similar returned so that I can process it. Also, I don't want to give any time frame, I just want all time stats to be returned for that campaign. Is it even possible?
If any one could help me out, I would really appreciate it. Kind of been stuck here for a few hours, skimmed through the whole AdWords API documentation but couldn't understand what would be the best and easy approach to this.
Now, Adwords API allowing stats only By reporting service.
And stats can be get using two methods.
1) By using reporting service as described
here
2) You can use Adwords Query Language. See
this
i don't know if you still need this but the API V201806 I found a solution. In this version of API exist the function getAsString() which returns the data in String and not download file, I request data in format XML and in PHP transform the response into a XML Object.
This is code I used:
class DownloadCriteriaReportWithAwql {
public static function runExample(AdWordsSession $session, $reportFormat){
// Create report query to get the data for last 7 days.
$query = (new ReportQueryBuilder())
->select([
'CampaignId',
'AdGroupId',
'Id',
'Criteria',
'CriteriaType',
'Impressions',
'Clicks',
'Cost',
'Conversions'
])
->from(ReportDefinitionReportType::CRITERIA_PERFORMANCE_REPORT)
->where('Status')->in(['ENABLED'])
->duringDateRange(ReportDefinitionDateRangeType::LAST_7_DAYS)
->build();
// Download report as a string.
$reportDownloader = new ReportDownloader($session);
// Optional: If you need to adjust report settings just for this one
// request, you can create and supply the settings override here.
// Otherwise, default values from the configuration
// file (adsapi_php.ini) are used.
$reportSettingsOverride = (new ReportSettingsBuilder())->includeZeroImpressions(false)->build();
$reportDownloadResult = $reportDownloader->downloadReportWithAwql(
sprintf('%s', $query),
$reportFormat,
$reportSettingsOverride
);
//print "Report was downloaded and printed below:\n";
$datos = $reportDownloadResult->getAsString();
return ($datos);
}
public static function main(){
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
// See: AdWordsSessionBuilder for setting a client customer ID that is
// different from that specified in your adsapi_php.ini file.
// Construct an API session configured from a properties file and the
// OAuth2 credentials above.
$session = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
$string = self::runExample($session, DownloadFormat::XML);
$xml = new \SimpleXMLElement($string);
return $xml;}}
The question was asked in 2015, since then they renamed the API to Google Ads API. The current version is V6 where getting clicks, CTR, CPC and other metrics is relatively simple.
The documentation here states:
This page shows all metrics and segments that can be put in the same SELECT clause as the fields of campaign
Based on that the AWQL for getting campaign together with clicks will look like this (tested):
$query = "SELECT campaign.id, campaign.name, campaign.status, metrics.clicks FROM campaign ORDER BY campaign.name"
Example in PHP how to iterate through results:
$stream = $googleAdsServiceClient->searchStream($customerId, $query);
foreach ($stream->iterateAllElements() as $googleAdsRow) {
/** #var GoogleAdsRow $googleAdsRow */
$data['campaigns'][] = [
'id' => $googleAdsRow->getCampaign()->getId(),
'clicks' => $googleAdsRow->getMetrics()->getClicks(),
];
}

How to update Google Sheets file with API PHP Client

I've been taking a look at the Google API PHP Client and would like to use it to add rows to a Google Sheet. From the code, it looks like one would use this method:
public function insert($fileId, Google_Service_Drive_Property $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_Drive_Property");
}
but I can't really tell what the parameters would be. Am I heading in the right direction? Also, not quite sure on how to connect to a specific Sheet. Please advise.
Thanks!
Use Google sheets class from zend framework 1.12. They have very nicely coded library for Google Spreadsheets
https://github.com/zendframework/zf1/tree/master/library/Zend/Gdata/Spreadsheets
I figured out how to work this and wanted to share with you guys. As I stated in a comment, I did not think using Zend's GData class was a good way for me since it's very dependent on other classes throughout the framework, thus being too heavy.
So I ended up using this Spreadsheet Client on top of Google's API. Google's API is used to authenticate my service, then I start calling the Spreadsheet Client library afterwards.
After spending over a day of Googling for various problems I had for the authentication process, here's what I did to make things work:
Created a new project for Google API here
Clicked "APIs" menu on the left side under "APIs & Auth"
Searched the Drive API and enabled it (can't remember if it was necessary)
Clicked the "Credentials" menu on the left
Clicked "Create new Client ID" button under OAuth
Selected "Service Account"
After info showed & json downloaded (not needed), I clicked "Generate new P12 Key" button
I saved the p12 file somewhere I could access it through PHP
Then in the code, I added the following lines:
$email = 'somethingsomethingblahblah#developer.gserviceaccount.com';
$CLIENT_ID = $email;
$SERVICE_ACCOUNT_NAME = $email;
$KEY_FILE = 'path/to/p12/file';
$SPREADSHEETS_SCOPE = 'https://spreadsheets.google.com/feeds';
$key = file_get_contents($KEY_FILE);
$auth = new Google_Auth_AssertionCredentials(
$SERVICE_ACCOUNT_NAME,
array($SPREADSHEETS_SCOPE),
$key
);
$client = new Google_Client();
$client->setScopes(array($SPREADSHEETS_SCOPE));
$client->setAssertionCredentials($auth);
$client->getAuth()->refreshTokenWithAssertion();
$client->setClientId($CLIENT_ID);
$accessToken = $client->getAccessToken();
Also, I had to make sure I:
Shared my spreadsheet specifically with the email address on my service account in the code above
Synced my server's time (I'm running Vagrant CentOS so it's slightly different)
I believe you can run this code with other services beyond Spreadsheets, such as Youtube, Analytics, etc., but you will need to get the correct scope link (see $SPREADSHEETS_SCOPE above). Remember, this is only when using the Service Account on the Google Console, which means you are programmatically getting data from your code. If you are looking to have others users sign in using the API, then it's different.

Categories