GaController.php
2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
/**
* Created by PhpStorm.
* User: Alex Savenko
* Date: 09.02.2017
* Time: 18:12
*/
namespace App\Controllers;
use Google_Client;
use Google_Service_AnalyticsReporting;
use Google_Service_AnalyticsReporting_DateRange;
use Google_Service_AnalyticsReporting_GetReportsRequest;
use Google_Service_AnalyticsReporting_Metric;
use Google_Service_AnalyticsReporting_ReportRequest;
use PhalconRest\Mvc\Controllers\CrudResourceController;
class GaController extends CrudResourceController {
const SECRET_JSON = 'ca4a1bd8aa14.json';
const VIEW_ID = '119240817';
public function getAction() {
putenv('GOOGLE_APPLICATION_CREDENTIALS=/var/www/phalcon/'.self::SECRET_JSON);
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$api_key = 'AIzaSyBNYr7n7bcHbO-sJ9xuWwS9xQ2OY5aFAiE';
$client->setDeveloperKey($api_key);
$analytics = new Google_Service_AnalyticsReporting($client);
$param[] = ['metric' => 'ga:sessions', 'alias' => 'Сессии'];
$response = [];
foreach ($param as $item) {
// Создание объекта DateRange.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("30daysAgo");
$dateRange->setEndDate("today");
// Создание объекта Metrics.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression($item['metric']);
$sessions->setAlias($item['alias']);
// Создание объекта ReportRequest.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId(self::VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
$response = $analytics->reports->batchGet( $body );
}
return var_dump($response);
return $this->createArrayResponse($response, 'data');
}
}