Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> Google analytics API PHP
marcwars
post
Post #1





Grupa: Zarejestrowani
Postów: 70
Pomógł: 0
Dołączył: 14.02.2011
Skąd: Wawa

Ostrzeżenie: (0%)
-----


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.

Ten post edytował marcwars 18.04.2015, 20:58:39
Go to the top of the page
+Quote Post
IProSoft
post
Post #2





Grupa: Zarejestrowani
Postów: 479
Pomógł: 97
Dołączył: 6.09.2011
Skąd: php.net :)

Ostrzeżenie: (0%)
-----


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.

Ten post edytował IProSoft 18.04.2015, 21:07:03
Go to the top of the page
+Quote Post
marcwars
post
Post #3





Grupa: Zarejestrowani
Postów: 70
Pomógł: 0
Dołączył: 14.02.2011
Skąd: Wawa

Ostrzeżenie: (0%)
-----


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.
Go to the top of the page
+Quote Post
IProSoft
post
Post #4





Grupa: Zarejestrowani
Postów: 479
Pomógł: 97
Dołączył: 6.09.2011
Skąd: php.net :)

Ostrzeżenie: (0%)
-----


Nigdzie nie widzę u Ciebie w kodzie pliku autoload.php
  1. require_once 'Google/autoload.php';
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 23.08.2025 - 05:08