1
votes

I'm trying to write a code in PHP that will connect to my Google Analytics account, pull the data from there, and then I need to handle it on the code - insert into SQL tables etc.

This is the folder I downloaded: https://github.com/google/google-api-php-client/releases (google-api-php-client-2.0.2.zip)

I used this google guide: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php
Which is actually for accessing the API through a URL, so I made a few adjustments so I'll handle the data locally (such as refresh token etc).

this is my code:

<?php

define ("API_Key","MY_API_KEY");
define ("oAuth_Key","MY_oAUTH_KEY");

define ("refreshTokenKey","MY_REFRESH_TOKEN");
define('STORE_ON_DISK', true, true);

// Load the Google API PHP Client Library.
require_once dirname(__FILE__) . '/../Analytics/google-api-php-client-2.0.2/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setApplicationName("PrsstoAnalytics");
$client->setAuthConfigFile(dirname(__FILE__) . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessType('offline');

$client->refreshToken(refreshTokenKey);


//----------------------------------------------------------------------------------------------------------------------
// Create an authorized analytics service object.
$analytics = new Google_Service_AnalyticsReporting($client);

// Call the Analytics Reporting API V4.
$response = getReport($analytics);

// Print the response.
printResults($response);

function getReport(&$analytics) {

    // Replace with your view ID. E.g., XXXX.
    $VIEW_ID = "MY_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 );
}

function printResults(&$reports) {
    for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
        $report = $reports[ $reportIndex ];
        $header = $report->getColumnHeader();
        $dimensionHeaders = $header->getDimensions();
        $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
        $rows = $report->getData()->getRows();

        for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
            $row = $rows[ $rowIndex ];
            $dimensions = $row->getDimensions();
            $metrics = $row->getMetrics();
            for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
                print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
            }

            for ($j = 0; $j < count( $metricHeaders ) && $j < count( $metrics ); $j++) {
                $entry = $metricHeaders[$j];
                $values = $metrics[$j];
                print("Metric type: " . $entry->getType() . "\n" );
                for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
                    $value = $values->getValues()[ $valueIndex ];
                    print($entry->getName() . ": " . $value . "\n");
                }
            }
        }
    }
}

But I test the script, this is the error I get: enter image description here

Does anyone has any idea why I can't connext to the API?

What am I doing wrong in my connection? Are my credentials not right? Am I missing a key of some kind? I'd really appreciate any help.

Thank you!

1

1 Answers

2
votes

I've been working on this one myself. I had to go into the API Manager (https://console.developers.google.com/apis), create a project, create a service account (that's the account for building a backend analytics service like this), and generate credentials. That will give you a .json file that you need to link to in your code: $client->setAuthConfigFile(dirname(__FILE__) . '/{you-credential-file}.json');

In that credentials file, you'll find the service account email address in the json field "client_email". You'll need to go to analytics.google.com and go to "Admin" to add that address with read & analyze permissions.

You'll also need to replace the line $VIEW_ID = "MY_VIEW_ID"; with your view id. I found mine at https://ga-dev-tools.appspot.com/account-explorer/

That was enough for me to finally get the client library and the HelloAnalytics sample up and running. I'm not positive on this, but if you're writing a backend service that queries GA, you shouldn't need to use OAuth.