Hello Analytics API: التشغيل السريع لJavaScript لتطبيقات الويب

يشرح هذا الدليل التوجيهي الخطوات المطلوبة للوصول إلى حساب على "إحصاءات Google" وإجراء طلبات بحث في واجهات برمجة تطبيقات "إحصاءات Google" والتعامل مع ردود واجهة برمجة التطبيقات والحصول على النتائج. يتم استخدام الإصدار 3.0 من واجهة برمجة التطبيقات الأساسية لإعداد التقارير والإصدار 3.0 من واجهة برمجة تطبيقات الإدارة وOAuth2.0 في هذا البرنامج التعليمي.

الخطوة 1: تفعيل واجهة برمجة تطبيقات "إحصاءات Google"

لبدء استخدام واجهة برمجة تطبيقات Google Analytics، عليك أولاً استخدام أداة الإعداد، التي ترشدك خلال عملية إنشاء مشروع في وحدة التحكم في واجهة Google API، وتفعيل واجهة برمجة التطبيقات، وإنشاء بيانات الاعتماد.

إنشاء معرِّف عميل

من صفحة "بيانات الاعتماد":

  1. انقر على إنشاء بيانات اعتماد واختَر معرِّف عميل OAuth.
  2. اختَر تطبيق الويب من أجل نوع التطبيق.
  3. أدخِل اسمًا لبيانات الاعتماد.
  4. اضبط مصادر JavaScript المعتمَدة على http://localhost:8080.
  5. اضبط معرِّفات الموارد المنتظمة (URI) المعتمَدة لإعادة التوجيه على http://localhost:8080/oauth2callback
  6. انقر على إنشاء.

الخطوة 2: إعداد النموذج

يجب إنشاء ملف واحد باسم HelloAnalytics.html يحتوي على رمز HTML وJavaScript الخاص بالمثال.

  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: تشغيل العيّنة

بعد تفعيل واجهة برمجة تطبيقات "إحصاءات Google"، وإعداد نموذج رمز المصدر الذي يصبح النموذج جاهزًا للعرض.

  1. انشر HelloAnalytics.html على خادم الويب وحمِّل الصفحة في المتصفّح.
  2. انقر على الزر تفويض، واسمح بالوصول إلى خدمة "إحصاءات Google".

عند الانتهاء من هذه الخطوات، يعرض النموذج اسم الملف الشخصي الأول للمستخدم المفوَّض على "إحصاءات Google" وعدد الجلسات خلال آخر سبعة أيام.

باستخدام عنصر خدمة "إحصاءات Google" المعتمَد، يمكنك الآن تشغيل أيّ من عيّنات التعليمات البرمجية المتوفّرة في المستندات المرجعية لواجهة Management API. على سبيل المثال، يمكنك محاولة تغيير الرمز لاستخدام طريقة accountSummaries.list.