1
votes

I'm trying to display the google analytics report in my web application which is to display top 10 pages and display browsers count, i am using this link Hello Analytics Reporting API v4; PHP quickstart for service account to develop it. I am getting below error,

Error calling POST https://analyticsreporting.googleapis.com/v4/reports:batchGet: (401) Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential

CODE :

$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);


function initializeAnalytics()
{

    // Use the developers console and download your service account
    // credentials in JSON format. Place them in this directory or
    // change the key file location if necessary.
    $KEY_FILE_LOCATION = __DIR__ . '/preprod-b18917fe321f.json';

    // Create and configure a new client object.
    $client = new Google_Client();
    $client->setApplicationName("Hello Analytics Reporting");
    $client->setAuthConfig('{"web":{}}'); // provided the .json credentials
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
    $analytics = new Google_Service_AnalyticsReporting($client);

    return $analytics;
}


function getReport($analytics) {

    // Replace with your view ID, for example XXXX.
    $VIEW_ID = "xxxxxx";

    // 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 );
}


/**
 * Parses and prints the Analytics Reporting API V4 response.
 *
 * @param An Analytics Reporting API V4 response.
 */
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($metrics); $j++) {
                $values = $metrics[$j]->getValues();
                for ($k = 0; $k < count($values); $k++) {
                    $entry = $metricHeaders[$k];
                    print($entry->getName() . ": " . $values[$k] . "\n");
                }
            }
        }
    }
}

Anyone please give me an idea to get rid of this error.

2
is the code prompting you for permissions to access the data?DaImTo
@DaImTo No, it shows Error calling POST analyticsreporting.googleapis.com/v4/reports:batchGet: (401) Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credentialUS-1234

2 Answers

1
votes

Error calling POST https://analyticsreporting.googleapis.com/v4/reports:batchGet: (401) Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential

Means that you are not logged in you are not properly authenticating the client before running the code.

posible issues with service accounts

  1. Check $client->setAuthConfig('{"web":{}}'); make sure this is the correct path to the json key file. should probably be $KEY_FILE_LOCATION
  2. Make sure that you created service account credentials on Google Developer console and not something else this code will only work with a service account key file.
  3. Make sure that you granted the service account access to your google analytics account. Take the service account email address and add it as a user in Google analytics at the account level.

Issue with json file location

If you still have issues with the file you can put the location into an env

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

ServiceAccount.php

0
votes

The error tells us that a user needs be logged in. You simply need to add the authentication part.

I suggest you to look at a sample Google Oauth & Analytics v4 in PHP.