Я пытаюсь с примером. Прежде всего, клиент Google
композитор требует "google / apiclient"
В console.developers.google.com:
- включить аналитику API
- определить проект (например: идентификатор проекта)
2) файл credentials_file
Создать учетную запись службы в:
https://console.developers.google.com/iam-admin/serviceaccounts?project=project-id
, с помощью которого вы создадите файл учетных данных в "путь / к / / service-account-credentials.json"
{
"type": "service_account",
"project_id": "project-id",
"private_key_id": "1234567890abcderf1234567890abcderf1234567890abcderf",
"private_key": "-----BEGIN PRIVATE KEY-----\nBASE64KEY=\n-----END PRIVATE KEY-----\n",
"client_email": "service-user@some.domain.gserviceaccount.com",
"client_id": "000000000000000000000000000000",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/cront-reriever-search-stats%40redooc-dot-com.iam.gserviceaccount.com"
}
3) определение того, что вы хотите ($ infos), для нужного вам представления ведьмы ($ viewId) и файла учетных данных($ credentials_file) и диапазон дат, вы запросите API и получите результаты в $ response
$infos= [
'users' => 'ga:users',
'pageviews' => 'ga:pageviews',
'pageviewsPerSession' => 'ga:pageviewsPerSession',
'unique page view' => 'ga:uniquePageviews',
'organicSearches' => 'ga:organicSearches',
'avgSessionDuration' => 'ga:avgSessionDuration',
'avgTimeOnPage' => 'ga:avgTimeOnPage',
];
$credentials_file='path/to/the/service-account-credentials.json';
$viewId='1600000'; // the view ID see imgae
$client = new \Google_Client();
$credentials_file = $this->checkServiceAccountCredentialsFile()) {
$client->setAuthConfig($credentials_file);
$client->addScope("https://www.googleapis.com/auth/analytics.readonly");
$analytics = new \Google_Service_AnalyticsReporting($client);
$response = getReport($viewId, $analytics, $infos, $DateStart, $DateEnd);
ADD getReport funtion
function getReport($viewId, $analytics, $dataAnalytics, $startDate, $endDate)
{
$dateRange = new \Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate($startDate);
$dateRange->setEndDate($endDate);
// Create the ReportRequest object.
$request = new \Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($viewId);
$request->setDateRanges($dateRange);
// Create the Metrics object.
$_metrics = [];
foreach ($dataAnalytics as $gaLabel => $gaValue) {
$metric = new \Google_Service_AnalyticsReporting_Metric();
$metric->setExpression($gaValue);
// $metric->setAlias($gaLabel);
$_metrics[] = $metric;
}
$request->setMetrics($_metrics);
$body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));
return $analytics->reports->batchGet($body);
}