Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: Google analytics API PHP
Forum PHP.pl > Forum > PHP
marcwars
Witam
próbuję podłączyć się pod moje konto Google analytics przy pomocy php w celu pokazania wyników na stronie.
Niestety kod nie działa. Korzystałem z tutoriala: https://developers.google.com/analytics/sol...o-analytics-api. Generalnie potrzebuję tylko uzyskać aktualny wynik wejść na stronę.

Kod
?<?php

require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';

session_start();

$client = new Google_Client();
$client->setApplicationName('###');

// Visit https://console.developers.google.com/ to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('###');
$client->setClientSecret('###');
$client->setRedirectUri('');
$client->setDeveloperKey('###');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

// Magic. Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

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

if (!$client->getAccessToken()) {
  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";

} else {
  $analytics = new apiAnalyticsService($client);
runMainDemo($analytics);
}

function runMainDemo(&$analytics) {
  try {

    // Step 2. Get the user's first view (profile) ID.
    $profileId = getFirstProfileId($analytics);

    if (isset($profileId)) {

      // Step 3. Query the Core Reporting API.
      $results = getResults($analytics, $profileId);

      // Step 4. Output the results.
      printResults($results);
    }

  } catch (apiServiceException $e) {
    // Error from the API.
    print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();

  } catch (Exception $e) {
    print 'There wan a general error : ' . $e->getMessage();
  }
}

function getFirstprofileId(&$analytics) {
  $accounts = $analytics->management_accounts->listManagementAccounts();

  if (count($accounts->getItems()) > 0) {
    $items = $accounts->getItems();
    $firstAccountId = $items[0]->getId();

    $webproperties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

    if (count($webproperties->getItems()) > 0) {
      $items = $webproperties->getItems();
      $firstWebpropertyId = $items[0]->getId();

      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstWebpropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();
        return $items[0]->getId();
        
          } else {
        throw new Exception('No views (profiles) found for this user.');
      }
    } else {
      throw new Exception('No webproperties found for this user.');
    }
  } else {
    throw new Exception('No accounts found for this user.');
  }
}

function getResults(&$analytics, $profileId) {
   return $analytics->data_ga->get(
       'ga:###' . $profileId,
       '2012-03-03',
       '2012-03-03',
       'ga:sessions');
}

function printResults(&$results) {
  if (count($results->getRows()) > 0) {
    $profileName = $results->getProfileInfo()->getProfileName();
    $rows = $results->getRows();
    $sessions = $rows[0][0];

    print "<p>First view (profile) found: $profileName</p>";
    print "<p>Total sessions: $sessions</p>";

  } else {
    print '<p>No results found.</p>';
  }
}

?>


Dodam, iż ścieżki do plików sa dobre, zamiast krzyżyków wstawiam odpowiednie dane z Google console, chociaż nie wiem co wpisać jako redirectUri (stronę której statystyki podaję?).

Będę wdzięczny za wszelkie wskazówki. ale to się okazało lipą i skierowałem się do Google analytics API. Czuję, że rozwiązanie jest blisko...

Reasumując będę wdzięczny za ogólne wskazówki, ew.jaki odsyłacz do lepszego tutoriala oraz konkretnie co wpisać w parametr redirectUri.
IProSoft
Masz jasno opisany parametr:
Cytat
The Redirect URI should be the same URL that points to where your HelloAnalyticsApi.php file is hosted on. This value must also be configured in the Google Developers Console.

Czyli url do Twojego pliku HelloAnalyticsApi.php, który odpalasz z przeglądarki, tan sam adres musisz dodać w panelu aplikacji.
marcwars
Tym razem otrzymuję komunikat:

Fatal error: Class 'Google_Service' not found in /.../Google/Service/Analytics.php on line 32

Czytałem w sieci, że to błąd w starej wersji biblioteki do API, ale czy ktoś mi wskaże nowszą? Na githubie dalej ta wersja z błędem.
IProSoft
Nigdzie nie widzę u Ciebie w kodzie pliku autoload.php
  1. require_once 'Google/autoload.php';
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.