index.php 6.22 KB
<?php
/**
 * Created by PhpStorm.
 * User: Alex Savenko
 * Date: 28.12.2016
 * Time: 21:52
 */

use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;

/* @var $this yii\web\View */

$this->title = Yii::t('app', 'Report');
$this->params['breadcrumbs'][] = $this->title;
?>

    <div>
        <h1><?= Html::encode($this->title) ?></h1>
    </div>

    <div id="embed-api-auth-container"></div>
    <div id="chart-container"></div>
    <div id="view-selector-container"></div>

    <script>
        (function(w,d,s,g,js,fs){
            g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
            js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
            js.src='https://apis.google.com/js/platform.js';
            fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
        }(window,document,'script'));
    </script>

    <script>

        gapi.analytics.ready(function() {

            /**
             * Authorize the user immediately if the user has already granted access.
             * If no access has been created, render an authorize button inside the
             * element with the ID "embed-api-auth-container".
             */
            gapi.analytics.auth.authorize({
                container: 'embed-api-auth-container',
                clientid: '119240817'
            });


            /**
             * Create a new ViewSelector instance to be rendered inside of an
             * element with the id "view-selector-container".
             */
            var viewSelector = new gapi.analytics.ViewSelector({
                container: 'view-selector-container'
            });

            // Render the view selector to the page.
            viewSelector.execute();


            /**
             * Create a new DataChart instance with the given query parameters
             * and Google chart options. It will be rendered inside an element
             * with the id "chart-container".
             */
            var dataChart = new gapi.analytics.googleCharts.DataChart({
                query: {
                    metrics: 'ga:sessions',
                    dimensions: 'ga:date',
                    'start-date': '30daysAgo',
                    'end-date': 'yesterday'
                },
                chart: {
                    container: 'chart-container',
                    type: 'LINE',
                    options: {
                        width: '100%'
                    }
                }
            });


            /**
             * Render the dataChart on the page whenever a new view is selected.
             */
            viewSelector.on('change', function(ids) {
                dataChart.set({query: {ids: ids}}).execute();
            });

        });
    </script>

<?php

// Загрузка клиентской библиотеки PHP для Google API.


$client = new Google_Client();
$client->setAuthConfig('./client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);


// Если пользователь уже авторизовал это приложение, предоставьте токен доступа.
// В противном случае перенаправьте пользователя на страницу авторизации доступа в Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    // Установка токена доступа на клиентском компьютере.
    $client->setAccessToken($_SESSION['access_token']);

    // Создание авторизованного объекта службы аналитики.
    $analytics = new Google_Service_AnalyticsReporting($client);

    // Вызов the Analytics Reporting API V4.
    $response = getReport($analytics);

    // Вывод ответа.
    printResults($response);

} else {
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/admin/report/callback';
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


function getReport($analytics) {

    // Замена на свой идентификатор представления, напр. XXXX.
    $VIEW_ID = "119240817";

    // Создание объекта DateRange.
    $dateRange = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange->setStartDate("7daysAgo");
    $dateRange->setEndDate("today");

    // Создание объекта Metrics.
    $sessions = new Google_Service_AnalyticsReporting_Metric();
    $sessions->setExpression("ga:sessions");
    $sessions->setAlias("sessions");

    // Создание объекта ReportRequest.
    $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");
                }
            }
        }
    }
}