Friday, April 19, 2013

Get google analytics data using google service account

Create service account
https://developers.google.com/analytics/devguides/reporting/core/dimsmets/time
<?php 
    $startDate = "2013-03-07";
    $endDate = "2013-04-06";
    $location = APP."libs".DS."google_api".DS."src".DS;

    require_once($location . 'Google_Client.php');
    require_once($location . 'contrib/Google_AnalyticsService.php');

    $CLIENT_ID = 'something.apps.googleusercontent.com';
    $SERVICE_ACCOUNT_NAME = 'something@developer.gserviceaccount.com';
    $KEY_FILE = $location . "something.p12";


    $client = new Google_Client();
    $client->setApplicationName("Project Name");

    if (isset($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
    }

    $client->setAssertionCredentials(
        new Google_AssertionCredentials(
            $SERVICE_ACCOUNT_NAME, // email you added to GA
            array('https://www.googleapis.com/auth/analytics.readonly'),
            file_get_contents($KEY_FILE)
        )
    );
    $client->setClientId($CLIENT_ID);           // from API console
    $client->setAccessType('offline_access');  // this may be unnecessary?
    $client->setUseObjects(true);

    $service = new Google_AnalyticsService($client);

    $accounts = $service->management_accounts->listManagementAccounts();
    $items = $accounts->getItems();
    $firstAccountId = $items[0]->getId();

    $webProperties = $service->management_webproperties->listManagementWebproperties($firstAccountId);
    $items = $webProperties->getItems();
    $firstWebPropertyId = $items[0]->getId();

    $profiles = $service->management_profiles->listManagementProfiles($firstAccountId, $firstWebPropertyId);
    print_r($profiles);

    $data = $service->data_ga->get(
        "ga:51149337",
        $startDate,
        $endDate,
        "ga:visits,ga:bounces",
        array("dimensions" => "ga:date")
    );

    print_r($data); die();
?>

No comments:

Post a Comment