नमस्ते Analytics API: वेब ऐप्लिकेशन के लिए PHP क्विकस्टार्ट

यह ट्यूटोरियल Google Analytics खाता ऐक्सेस करने, Analytics एपीआई के बारे में क्वेरी करने, एपीआई से मिले रिस्पॉन्स को मैनेज करने, और नतीजे देने के लिए ज़रूरी चरणों के बारे में बताता है. इस ट्यूटोरियल में, Core Reporting API v3.0, Management API v3.0, और OAuth2.0 का इस्तेमाल किया गया है.

पहला चरण: Analytics API चालू करना

Google Analytics API का इस्तेमाल शुरू करने से पहले, सेटअप टूल इस्तेमाल करना ज़रूरी है. यह आपको Google API Console में प्रोजेक्ट बनाने, एपीआई की सुविधा चालू करने, और क्रेडेंशियल बनाने के बारे में जानकारी देता है.

क्लाइंट आईडी बनाना

क्रेडेंशियल पेज से:

  1. क्रेडेंशियल बनाएं पर क्लिक करें और OAuth क्लाइंट आईडी चुनें.
  2. APPLICATION TYPE के लिए, वेब ऐप्लिकेशन चुनें.
  3. क्रेडेंशियल को नाम दें.
  4. अनुमति वाले JAVAscript ORIGIN को खाली छोड़ें, इस ट्यूटोरियल के लिए इसकी ज़रूरत नहीं है.
  5. अनुमति वाले रीडायरेक्ट यूआरआई को http://localhost:8080/oauth2callback.php पर सेट करें
  6. बनाएं पर क्लिक करें.

आपने अभी जो क्रेडेंशियल बनाया है उसे चुनें और JSON डाउनलोड करें पर क्लिक करें. डाउनलोड की गई फ़ाइल को client_secrets.json के तौर पर सेव करें. आपको बाद में ट्यूटोरियल में इसकी ज़रूरत पड़ेगी.

दूसरा चरण: Google क्लाइंट लाइब्रेरी इंस्टॉल करना

आपके पास PHP के लिए Google API क्लाइंट लाइब्रेरी रिलीज़ डाउनलोड करने या कंपोज़र का इस्तेमाल करने का विकल्प है:

composer require google/apiclient:^2.0

तीसरा चरण: सैंपल सेटअप करना

आपको दो फ़ाइलें बनानी होंगी:

  1. उपयोगकर्ता ने index.php मुख्य पेज देखा होगा.
  2. OAuth 2.0 रिस्पॉन्स को oauth2callback.php हैंडल करेगा.

index.php

इस फ़ाइल में मुख्य तौर पर, Google Analytics API से जुड़ी क्वेरी करने और नतीजे दिखाने का लॉजिक शामिल होता है. पहले सैंपल कोड को कॉपी या डाउनलोड करके index.php में करें.

<?php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_Analytics($client);

  // Get the first view (profile) id for the authorized user.
  $profile = getFirstProfileId($analytics);

  // Get the results from the Core Reporting API and print the results.
  $results = getResults($analytics, $profile);
  printResults($results);
} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


function getFirstProfileId($analytics) {
  // Get the user's first view (profile) ID.

  // Get the list of accounts for the authorized user.
  $accounts = $analytics->management_accounts->listManagementAccounts();

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

    // Get the list of properties for the authorized user.
    $properties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

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

      // Get the list of views (profiles) for the authorized user.
      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstPropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();

        // Return the first view (profile) ID.
        return $items[0]->getId();

      } else {
        throw new Exception('No views (profiles) found for this user.');
      }
    } else {
      throw new Exception('No properties found for this user.');
    }
  } else {
    throw new Exception('No accounts found for this user.');
  }
}

function getResults($analytics, $profileId) {
  // Calls the Core Reporting API and queries for the number of sessions
  // for the last seven days.
  return $analytics->data_ga->get(
      'ga:' . $profileId,
      '7daysAgo',
      'today',
      'ga:sessions');
}

function printResults($results) {
  // Parses the response from the Core Reporting API and prints
  // the profile name and total sessions.
  if (count($results->getRows()) > 0) {

    // Get the profile name.
    $profileName = $results->getProfileInfo()->getProfileName();

    // Get the entry for the first entry in the first row.
    $rows = $results->getRows();
    $sessions = $rows[0][0];

    // Print the results.
    print "<p>First view (profile) found: $profileName</p>";
    print "<p>Total sessions: $sessions</p>";
  } else {
    print "<p>No results found.</p>";
  }
}

?>

oauth2callback.php

यह फ़ाइल OAuth 2.0 रिस्पॉन्स को मैनेज करती है. दूसरे सैंपल कोड को oauth2callback.php पर कॉपी करें या डाउनलोड करें.

<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


चौथा चरण: सैंपल चलाएं

Analytics API चालू करने के बाद, PHP के लिए Google API क्लाइंट लाइब्रेरी इंस्टॉल करें. और सैंपल सोर्स कोड सेट अप करें, ताकि सैंपल चलाने के लिए तैयार हो.

PHP को सेवा देने के लिए कॉन्फ़िगर किए गए वेब सर्वर पर सैंपल चलाएं. अगर PHP 5.4 या इसके बाद के वर्शन का इस्तेमाल किया जा रहा है, तो इस कमांड को लागू करके PHP के बिल्ट-इन टेस्ट वेब सर्वर का इस्तेमाल किया जा सकता है:

php -S localhost:8080 /path/to/sample

इसके बाद, अपने ब्राउज़र में http://localhost:8080 पर जाएं.

इन चरणों को पूरा करने के बाद, सैंपल, अनुमति वाले उपयोगकर्ता के पहले Google Analytics व्यू (प्रोफ़ाइल) का नाम और पिछले सात दिनों के सेशन की संख्या दिखाता है.

अनुमति वाले Analytics सेवा ऑब्जेक्ट की मदद से, अब आप Management API रेफ़रंस दस्तावेज़ में मिलने वाले किसी भी कोड सैंपल को चला सकते हैं. उदाहरण के लिए, आप accountSummaries.list तरीके का इस्तेमाल करने के लिए, कोड को बदलकर देख सकते हैं.