Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: Pobieranie danych z API google analytics
Forum PHP.pl > Forum > PHP
chomikiki
Cześć,
Niestety przeszukując zasoby internetu nie mogę znaleźć tutoriala jak pobrać dane na swoją stronę. Jak już znalazłam jakieś kody to nie działają, albo ja ich nie potrafię użyć (to drugie bardziej prawdopodobne). Doszłam do przycisku logowania, ale tez wyskakuje błąd i nie bardzo wiem co dalej. Zna ktoś może jakieś tutoriale, albo powie co po kolei powinnam zrobić? Jestem wzrokowcem i najszybciej kumam o co chodzi jak widzę przykład. Niestety jedyne przykłady jakie znalazlam dotyczą umieszczenia wtyczki do pobierania danych przez google a nie pobierania danych Z google sad.gif Bardzo proszę o pomoc
viking
A te przykłady nie wystarczają? https://developers.google.com/analytics/dev...art/service-php
chomikiki
ok. robiłam tak jak kazali i znowu problem...

pobieram repozytorium git clone -b v1-master https://github.com/google/google-api-php-client.git

robię tak jak jest w instrukcji
  1. <?php
  2.  
  3. require_once 'google-api-php-client/src/Google/autoload.php';
  4.  
  5. $client = new Google_Client();
  6. $client->setApplicationName("Client_Library_Examples");
  7. $client->setDeveloperKey("YOUR_APP_KEY");
  8.  
  9. $service = new Google_Service_Books($client);
  10. $optParams = array('filter' => 'free-ebooks');
  11. $results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
  12.  
  13. foreach ($results as $item) {
  14. echo $item['volumeInfo']['title'], "<br /> \n";
  15. }
  16. ?>


a dostaje błąd: "Fatal error: Uncaught Google_Service_Exception: Error calling GET https://www.googleapis.com/books/v1/volumes...y=YOUR_APP_KEY: (400) Bad Request in C:\[...]\google-api-php-client\src\Google\Http\REST.php:110 Stack trace: #0 C:\[...]\google-api-php-client\src\Google\Http\REST.php(62): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request), Object(Google_Client)) #1 C:\[...]\google-api-php-client\src\Google\Task\Runner.php(174): Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request)) #2 C:\[...]\google-api-php-client\src\Google\Http\REST.php(46): Google_Task_Runner->run() #3 C:\[...]\google-api-php-client\src\Google\Client.php(593): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request)) #4 C:\[...]\google-api-php-client\src\Google\Service\Resource.php(240): Google_Client->execute(Object(Google_Http_Request)) #5 C:\[...] in C:\[...]\google-api-php-client\src\Google\Http\REST.php on line 110"
kapslokk
W miejscu "YOUR_APP_KEY" wstawiłaś swój klucz? Czy lecisz z copy-paste tak jak było i nawet nie czytałaś tego kodu?
chomikiki
nie zauważyłam tego... a gdzie ten klucz znajdę?
kapslokk
W googlach... biggrin.gif biggrin.gif

https://developers.google.com/api-client-li...art/get_started
tutaj cos jest opisane
chomikiki
mam cos takiego

  1. require_once 'google-api-php-client/src/Google/autoload.php'; // jest w głównym folderze
  2.  
  3.  
  4. $analytics = initializeAnalytics();
  5. $profile = getFirstProfileId($analytics);
  6. $results = getResults($analytics, $profile);
  7. printResults($results);
  8.  
  9. function initializeAnalytics()
  10. {
  11. // Creates and returns the Analytics Reporting service object.
  12.  
  13. // Use the developers console and download your service account
  14. // credentials in JSON format. Place them in this directory or
  15. // change the key file location if necessary.
  16. $KEY_FILE_LOCATION = __DIR__ . '/[...]/client_secret.json'; // w tym samym miejscu co ten plik
  17.  
  18. // Create and configure a new client object.
  19. $client = new Google_Client();
  20. $client->setApplicationName("Hello Analytics Reporting");
  21. $client->setAuthConfig($KEY_FILE_LOCATION);
  22. $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  23. $analytics = new Google_Service_Analytics($client);
  24.  
  25. return $analytics;
  26. }
  27.  
  28. function getFirstProfileId($analytics) {
  29. // Get the user's first view (profile) ID.
  30.  
  31. // Get the list of accounts for the authorized user.
  32. $accounts = $analytics->management_accounts->listManagementAccounts();
  33.  
  34. if (count($accounts->getItems()) > 0) {
  35. $items = $accounts->getItems();
  36. $firstAccountId = $items[0]->getId();
  37.  
  38. // Get the list of properties for the authorized user.
  39. $properties = $analytics->management_webproperties
  40. ->listManagementWebproperties($firstAccountId);
  41.  
  42. if (count($properties->getItems()) > 0) {
  43. $items = $properties->getItems();
  44. $firstPropertyId = $items[0]->getId();
  45.  
  46. // Get the list of views (profiles) for the authorized user.
  47. $profiles = $analytics->management_profiles
  48. ->listManagementProfiles($firstAccountId, $firstPropertyId);
  49.  
  50. if (count($profiles->getItems()) > 0) {
  51. $items = $profiles->getItems();
  52.  
  53. // Return the first view (profile) ID.
  54. return $items[0]->getId();
  55.  
  56. } else {
  57. throw new Exception('No views (profiles) found for this user.');
  58. }
  59. } else {
  60. throw new Exception('No properties found for this user.');
  61. }
  62. } else {
  63. throw new Exception('No accounts found for this user.');
  64. }
  65. }
  66.  
  67. function getResults($analytics, $profileId) {
  68. // Calls the Core Reporting API and queries for the number of sessions
  69. // for the last seven days.
  70. return $analytics->data_ga->get(
  71. 'ga:' . $profileId,
  72. '7daysAgo',
  73. 'today',
  74. 'ga:sessions');
  75. }
  76.  
  77. function printResults($results) {
  78. // Parses the response from the Core Reporting API and prints
  79. // the profile name and total sessions.
  80. if (count($results->getRows()) > 0) {
  81.  
  82. // Get the profile name.
  83. $profileName = $results->getProfileInfo()->getProfileName();
  84.  
  85. // Get the entry for the first entry in the first row.
  86. $rows = $results->getRows();
  87. $sessions = $rows[0][0];
  88.  
  89. // Print the results.
  90. print "First view (profile) found: $profileName\n";
  91. print "Total sessions: $sessions\n";
  92. } else {
  93. print "No results found.\n";
  94. }
  95. }


i nic... dostaje pustą stronę. Nie ma błędów ale też nie ma wyniku. Co robię nie tak?
viking
Pusta strona oznacza błędy ale ich nie wyświetlasz. Temat: Jak poprawnie zadac pytanie oraz przygotowac srodowisko pracy

Zapewne na dzień dobry __DIR__ . '/[...]/client_secret.json i [...]
chomikiki
po wklejeniu:

error_reporting(E_ALL);
ini_set('display_errors','1');

na początku strony pokazuje:
"Fatal error: Uncaught exception 'Google_Exception' with message 'Invalid client secret JSON file.' in /[...]/google-api-php-client/src/Google/Client.php:171 Stack trace: #0 /[...]/view/admin/HelloAnalytics.php(47): Google_Client->setAuthConfig('/home/admin/web...') #1 /[...]/view/admin/HelloAnalytics.php(30): initializeAnalytics() #2 {main} thrown in /[...]/google-api-php-client/src/Google/Client.php on line 171"

Ponieważ nie mogę ujawnić strony pod [...] kryje się link do głównego folderu.

view\admin\HelloAnalytics.php
[30] $analytics = initializeAnalytics();

[35-52]
  1. function initializeAnalytics()
  2. {
  3. // Creates and returns the Analytics Reporting service object.
  4.  
  5. // Use the developers console and download your service account
  6. // credentials in JSON format. Place them in this directory or
  7. // change the key file location if necessary.
  8. $KEY_FILE_LOCATION = __DIR__ . 'view\admin\client_secret.json';
  9.  
  10. // Create and configure a new client object.
  11. $client = new Google_Client();
  12. $client->setApplicationName("Hello Analytics Reporting");
  13. $client->setAuthConfig($KEY_FILE_LOCATION); // <- [47]
  14. $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  15. $analytics = new Google_Service_Analytics($client);
  16.  
  17. return $analytics;
  18. }


google-api-php-client\src\Google\Client.php
[166-178]
  1. public function setAuthConfig($json)
  2. {
  3. $data = json_decode($json);
  4. $key = isset($data->installed) ? 'installed' : 'web';
  5. if (!isset($data->$key)) {
  6. throw new Google_Exception("Invalid client secret JSON file.");
  7. }
  8. $this->setClientId($data->$key->client_id);
  9. $this->setClientSecret($data->$key->client_secret);
  10. if (isset($data->$key->redirect_uris)) {
  11. $this->setRedirectUri($data->$key->redirect_uris[0]);
  12. }
  13. }


nawet po ponownym pobraniu pliku (niby właściwego dla utworzonego projektu w "console.developers.google.com/apis/credentials") nie działa sad.gif
viking
Ta linia
  1. if (!isset($data->$key)) {
  2. throw new Google_Exception("Invalid client secret JSON file.");
  3. }
zwraca ten wyjątek więc coś jest nie tak z $data. Według tego kodu ma być tam jakiś obiekt z wartością installed albo web.
chomikiki
do tego niestety sama doszłam sad.gif ale nie wiem co dalej i jak to naprawić

EDIT
Dodam, że jak użyję kodu
  1. $keyApi = curl_init("http://[adres strony]/client_secret.json");
  2. curl_setopt($keyApi, CURLOPT_CONNECTTIMEOUT, 20);
  3. curl_setopt($keyApi, CURLOPT_TIMEOUT, 20);
  4. curl_setopt($keyApi, CURLOPT_RETURNTRANSFER, 1);
  5.  
  6. $json = curl_exec($keyApi);
  7.  
  8. $tab=json_decode($json, true);
  9. echo "<pre>";
  10. print_r($tab);
  11. echo "</pre>";


To listuje mi całą zawartość pliku json. Ścieżka podana wyżej została zamieniona na link bezpośredni, więc powinno być ok. i powinno mieć możliwość dostać się do pliku. Niestety nawet To nie pomogło.
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.