नमस्ते Analytics Reporting API v4; वेब ऐप्लिकेशन के लिए PHP से क्विकस्टार्ट सुविधा

इस ट्यूटोरियल में, Analytics Reporting API v4 को ऐक्सेस करने के ज़रूरी चरणों के बारे में बताया गया है.

1. एपीआई चालू करें

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

ध्यान दें: वेब क्लाइंट आईडी या इंस्टॉल किया गया ऐप्लिकेशन क्लाइंट बनाने के लिए, आपको सहमति वाली स्क्रीन में प्रॉडक्ट का नाम सेट करना होगा. अगर आपने अब तक ऐसा नहीं किया है, तो आपको सहमति वाली स्क्रीन कॉन्फ़िगर करें के लिए कहा जाएगा.

क्रेडेंशियल बनाएं

  • क्रेडेंशियल पेज खोलें.
  • क्रेडेंशियल बनाएं पर क्लिक करें और OAuth क्लाइंट आईडी चुनें
  • ऐप्लिकेशन के टाइप के लिए वेब ऐप्लिकेशन चुनें.
  • क्लाइंट आईडी को quickstart नाम दें और quickstart पर क्लिक करें.
  • अनुमति वाले JavaScript ऑरिजिन को खाली छोड़ें. इस ट्यूटोरियल के लिए, इसकी ज़रूरत नहीं है.
  • अनुमति वाले रीडायरेक्ट यूआरआई को http://localhost:8080/oauth2callback.php पर सेट करें
  • बनाएं पर क्लिक करें.

क्रेडेंशियल पेज पर जाकर, नए क्लाइंट आईडी पर क्लिक करें. इसके बाद, JSON डाउनलोड करें पर क्लिक करके, उसे client_secrets.json के तौर पर सेव करें. आपको बाद में ट्यूटोरियल में इसकी ज़रूरत पड़ेगी.

2. क्लाइंट लाइब्रेरी इंस्टॉल करना

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

composer require google/apiclient:^2.0

3. सैंपल सेटअप करें

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

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

index.php

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

  • index.php पर पहला सैंपल कोड कॉपी या डाउनलोड करें.
  • VIEW_ID की वैल्यू बदलें. व्यू आईडी ढूंढने के लिए, खाता एक्सप्लोरर का इस्तेमाल किया जा सकता है.
<?php

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

session_start();

$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_AnalyticsReporting($client);

  // Call the Analytics Reporting API V4.
  $response = getReport($analytics);

  // Print the response.
  printResults($response);

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


/**
 * Queries the Analytics Reporting API V4.
 *
 * @param service An authorized Analytics Reporting API V4 service object.
 * @return The Analytics Reporting API V4 response.
 */
function getReport($analytics) {

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "<REPLACE_WITH_VIEW_ID>";

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("7daysAgo");
  $dateRange->setEndDate("today");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setMetrics(array($sessions));

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );
}


/**
 * Parses and prints the Analytics Reporting API V4 response.
 *
 * @param An Analytics Reporting API V4 response.
 */
function printResults($reports) {
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();

    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
      $metrics = $row->getMetrics();
      for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
        print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
      }

      for ($j = 0; $j < count($metrics); $j++) {
        $values = $metrics[$j]->getValues();
        for ($k = 0; $k < count($values); $k++) {
          $entry = $metricHeaders[$k];
          print($entry->getName() . ": " . $values[$k] . "\n");
        }
      }
    }
  }
}


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));
}


4. सैंपल चलाएं

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

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

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

जब इन चरणों को पूरा किया जाता है, तो सैंपल, दिए गए व्यू के लिए पिछले सात दिनों के सेशन की संख्या दिखाता है.