Hello Analytics API: شروع سریع جاوا اسکریپت برای برنامه های کاربردی وب

این آموزش مراحل مورد نیاز برای دسترسی به حساب Google Analytics، پرس و جو از API های Analytics، رسیدگی به پاسخ های API و خروجی نتایج را طی می کند. Core Reporting API v3.0 ، Management API v3.0 و OAuth2.0 در این آموزش استفاده شده است.

مرحله 1: API Analytics را فعال کنید

برای شروع استفاده از Google Analytics API، ابتدا باید از ابزار راه اندازی استفاده کنید که شما را از طریق ایجاد پروژه در کنسول API Google، فعال کردن API و ایجاد اعتبارنامه راهنمایی می کند.

یک شناسه مشتری ایجاد کنید

از صفحه اعتبارنامه:

  1. روی ایجاد اعتبارنامه کلیک کنید و شناسه مشتری OAuth را انتخاب کنید.
  2. برنامه وب را برای APPLICATION TYPE انتخاب کنید.
  3. اعتبارنامه را نام ببرید.
  4. AUTHORIZED JAVASCRIPT ORIGINS را روی http://localhost:8080 تنظیم کنید
  5. AUTHORIZED REDIRECT URIS را روی http://localhost:8080/oauth2callback تنظیم کنید
  6. روی ایجاد کلیک کنید.

مرحله 2: نمونه را تنظیم کنید

شما باید یک فایل به نام HelloAnalytics.html ایجاد کنید که حاوی کد HTML و جاوا اسکریپت برای مثال ما باشد.

  1. کد منبع زیر را در HelloAnalytics.html کپی یا دانلود کنید .
  2. '<YOUR_CLIENT_ID>' با شناسه مشتری خود جایگزین کنید. در بالا ایجاد شده است.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello Analytics - A quickstart guide for JavaScript</title>
</head>
<body>

<button id="auth-button" hidden>Authorize</button>

<h1>Hello Analytics</h1>

<textarea cols="80" rows="20" id="query-output"></textarea>

<script>

  // Replace with your client ID from the developer console.
  var CLIENT_ID = '<YOUR_CLIENT_ID>';

  // Set authorized scope.
  var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];


  function authorize(event) {
    // Handles the authorization flow.
    // `immediate` should be false when invoked from the button click.
    var useImmdiate = event ? false : true;
    var authData = {
      client_id: CLIENT_ID,
      scope: SCOPES,
      immediate: useImmdiate
    };

    gapi.auth.authorize(authData, function(response) {
      var authButton = document.getElementById('auth-button');
      if (response.error) {
        authButton.hidden = false;
      }
      else {
        authButton.hidden = true;
        queryAccounts();
      }
    });
  }


function queryAccounts() {
  // Load the Google Analytics client library.
  gapi.client.load('analytics', 'v3').then(function() {

    // Get a list of all Google Analytics accounts for this user
    gapi.client.analytics.management.accounts.list().then(handleAccounts);
  });
}


function handleAccounts(response) {
  // Handles the response from the accounts list method.
  if (response.result.items && response.result.items.length) {
    // Get the first Google Analytics account.
    var firstAccountId = response.result.items[0].id;

    // Query for properties.
    queryProperties(firstAccountId);
  } else {
    console.log('No accounts found for this user.');
  }
}


function queryProperties(accountId) {
  // Get a list of all the properties for the account.
  gapi.client.analytics.management.webproperties.list(
      {'accountId': accountId})
    .then(handleProperties)
    .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}


function handleProperties(response) {
  // Handles the response from the webproperties list method.
  if (response.result.items && response.result.items.length) {

    // Get the first Google Analytics account
    var firstAccountId = response.result.items[0].accountId;

    // Get the first property ID
    var firstPropertyId = response.result.items[0].id;

    // Query for Views (Profiles).
    queryProfiles(firstAccountId, firstPropertyId);
  } else {
    console.log('No properties found for this user.');
  }
}


function queryProfiles(accountId, propertyId) {
  // Get a list of all Views (Profiles) for the first property
  // of the first Account.
  gapi.client.analytics.management.profiles.list({
      'accountId': accountId,
      'webPropertyId': propertyId
  })
  .then(handleProfiles)
  .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}


function handleProfiles(response) {
  // Handles the response from the profiles list method.
  if (response.result.items && response.result.items.length) {
    // Get the first View (Profile) ID.
    var firstProfileId = response.result.items[0].id;

    // Query the Core Reporting API.
    queryCoreReportingApi(firstProfileId);
  } else {
    console.log('No views (profiles) found for this user.');
  }
}


function queryCoreReportingApi(profileId) {
  // Query the Core Reporting API for the number sessions for
  // the past seven days.
  gapi.client.analytics.data.ga.get({
    'ids': 'ga:' + profileId,
    'start-date': '7daysAgo',
    'end-date': 'today',
    'metrics': 'ga:sessions'
  })
  .then(function(response) {
    var formattedJson = JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value = formattedJson;
  })
  .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}

  // Add an event listener to the 'auth-button'.
  document.getElementById('auth-button').addEventListener('click', authorize);
</script>

<script src="https://apis.google.com/js/client.js?onload=authorize"></script>

</body>
</html>

مرحله 3: نمونه را اجرا کنید

پس از اینکه API Analytics را فعال کردید و کد منبع نمونه را تنظیم کردید، نمونه آماده اجرا است.

  1. HelloAnalytics.html در سرور وب خود منتشر کنید و صفحه را در مرورگر خود بارگذاری کنید.
  2. کلیک کنید بر روی دکمه مجوز، و اجازه دسترسی به Google Analytics.

پس از اتمام این مراحل، نمونه نام اولین نمای Google Analytics کاربر مجاز (نمایه) و تعداد جلسات هفت روز گذشته را نمایش می دهد.

با شیء مجاز سرویس Analytics، اکنون می توانید هر یک از نمونه کدهای موجود در اسناد مرجع مدیریت API را اجرا کنید. برای مثال، می‌توانید کد را برای استفاده از روش accountSummaries.list تغییر دهید.