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

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

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

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

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

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

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

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

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

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

composer require google/apiclient:^2.0

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

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

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

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&#in3बिल्ट बिल्ट वेब सर्वर का इस्तेमाल कर सकते हैं:

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

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

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

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