Blame view

backend/views/report/index.php 4.9 KB
a3fa7958   Alex Savenko   base
1
2
3
4
5
6
7
8
9
10
11
  <?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;
7701ff7c   Alex Savenko   ga
12
  use yii\bootstrap\ActiveForm;
a3fa7958   Alex Savenko   base
13
14
  
  /* @var $this yii\web\View */
db981432   Alex Savenko   ga
15
  /* @var $model \backend\models\DateRange */
a3fa7958   Alex Savenko   base
16
17
18
19
  
  $this->title = Yii::t('app', 'Report');
  $this->params['breadcrumbs'][] = $this->title;
  ?>
a3fa7958   Alex Savenko   base
20
  
a194dccd   Alex Savenko   ga
21
22
23
      <div>
          <h1><?= Html::encode($this->title) ?></h1>
      </div>
acf5f3b7   Alex Savenko   ga
24
  
f97601c5   Alex Savenko   ga
25
      <div>
db981432   Alex Savenko   ga
26
27
          <?php $form = ActiveForm::begin(['id' => 'range-form']); ?>
  
43407791   Alex Savenko   ga
28
          <?= $form->field($model, 'date')->dropDownList([
db981432   Alex Savenko   ga
29
30
31
32
33
34
35
36
              'today' => 'Сегодня',
              'yesterday' => 'Вчера',
              '7daysAgo'=>'Последние 7 дней',
              '30daysAgo'=>'Последние 30 дней'
          ]);
          ?>
  
          <div class="form-group">
acf5f3b7   Alex Savenko   ga
37
              <?= Html::submitButton('Send', ['class' => 'btn btn-primary', 'name' => 'range-button']) ?>
db981432   Alex Savenko   ga
38
39
40
          </div>
  
          <?php ActiveForm::end(); ?>
f97601c5   Alex Savenko   ga
41
      </div>
a194dccd   Alex Savenko   ga
42
  
acf5f3b7   Alex Savenko   ga
43
  <?= Html::encode($model->date) ?>
88d016ad   Alex Savenko   testing
44
  <?php
add2d13e   Alex Savenko   ga
45
      var_dump($model);
f97601c5   Alex Savenko   ga
46
  
88d016ad   Alex Savenko   testing
47
  // Загрузка клиентской библиотеки PHP для Google API.
2d10f818   Alex Savenko   testing
48
  
2d10f818   Alex Savenko   testing
49
  
88d016ad   Alex Savenko   testing
50
  $client = new Google_Client();
5c42bcd6   Alex Savenko   ga
51
  $client->setAuthConfig('./client_secrets.json');
6981a7c2   Alex Savenko   ga
52
  $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
2d10f818   Alex Savenko   testing
53
  
2d10f818   Alex Savenko   testing
54
  
88d016ad   Alex Savenko   testing
55
56
  // Если пользователь уже авторизовал это приложение, предоставьте токен доступа.
  // В противном случае перенаправьте пользователя на страницу авторизации доступа в Google Analytics.
59a93b93   Alex Savenko   ga
57
58
59
60
61
62
63
64
  if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
      // Установка токена доступа на клиентском компьютере.
      $client->setAccessToken($_SESSION['access_token']);
  
      // Создание авторизованного объекта службы аналитики.
      $analytics = new Google_Service_AnalyticsReporting($client);
  
      // Вызов the Analytics Reporting API V4.
74a48fa5   Alex Savenko   ga
65
66
67
68
  
      $param[] = ['metric' => 'ga:sessions', 'alias' => 'Сессии'];
      $param[] = ['metric' => 'ga:users', 'alias' => 'Пользователи'];
      $param[] = ['metric' => 'ga:CTR', 'alias' => 'CTR'];
d24da82d   Alex Savenko   ga
69
      $param[] = ['metric' => 'ga:goal1Value', 'alias' => 'цель "Корзина"'];
74a48fa5   Alex Savenko   ga
70
71
72
73
74
75
76
77
  
      foreach ($param as $item) {
          $response = getReport($analytics, $item['metric'], $item['alias']);
  
          // Вывод ответа.
          printResults($response);
      }
  
59a93b93   Alex Savenko   ga
78
  
45aa4e58   Alex Savenko   ga
79
  
59a93b93   Alex Savenko   ga
80
  } else {
a2842f96   Alex Savenko   ga
81
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/admin/report/callback';
59a93b93   Alex Savenko   ga
82
83
84
85
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
  }
  
  
92c9fb64   Alex Savenko   ga
86
  function getReport($analytics, $metric, $alias) {
59a93b93   Alex Savenko   ga
87
88
89
90
91
92
  
      // Замена на свой идентификатор представления, напр. XXXX.
      $VIEW_ID = "119240817";
  
      // Создание объекта DateRange.
      $dateRange = new Google_Service_AnalyticsReporting_DateRange();
130dffde   Alex Savenko   ga
93
      $dateRange->setStartDate("30daysAgo");
f97601c5   Alex Savenko   ga
94
      $dateRange->setEndDate("today");
59a93b93   Alex Savenko   ga
95
96
97
  
      // Создание объекта Metrics.
      $sessions = new Google_Service_AnalyticsReporting_Metric();
130dffde   Alex Savenko   ga
98
      $sessions->setExpression($metric);
92c9fb64   Alex Savenko   ga
99
      $sessions->setAlias($alias);
d5ea26df   Alex Savenko   ga
100
101
  
  
59a93b93   Alex Savenko   ga
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
      // Создание объекта 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];
92c9fb64   Alex Savenko   ga
132
                  //print("Metric type: " . $entry->getType() . "\n" );
59a93b93   Alex Savenko   ga
133
134
                  for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
                      $value = $values->getValues()[ $valueIndex ];
d24da82d   Alex Savenko   ga
135
                      print("<b>" . $entry->getName() . "</b>: " . $value . '<br/>');
59a93b93   Alex Savenko   ga
136
137
138
139
140
                  }
              }
          }
      }
  }
ee720a54   Alex Savenko   ga

ee720a54   Alex Savenko   ga

5776b7c8   Alex Savenko   ga