简体   繁体   中英

How to query data from Google Analytics of a site?

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:

  1. 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?
  2. 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?
  3. 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 (eg, 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM