Search code examples
javascriptgoogle-analytics-apigoogle-analytics-data-api

Question Concerning Google Analytics Data API


I got those code while watching this video https://www.youtube.com/watch?v=teL_9dJDvRw which provide me with this code, but my login button is not showing initially and I supect that is because of the problem of Google Sign-In is not in used anymore therefore I follow their instruction and try to add"plugin_name" in my easyData-google-analtyics.js as shown in the belowe script I added

  1. const GA_PLUGIN_NAME = "quickstart"

  2. Change gapi.auth2.init({ client_id: CLIENT_ID}).then(() => document.dispatchEvent(new Event('gapi-loaded')));

    intogapi.auth2.init({ client_id: CLIENT_ID,plugin_name: GA_PLUGIN_NAME}).then(() => document.dispatchEvent(new Event('gapi-loaded')));

  3. Change

    function signIn(scope = GA_SCOPE,plugin_name= GA_PLUGIN_NAME) { return gapi.auth2.getAuthInstance().signIn({ scope,plugin_name }).then(() => { setCookie('guser-loggedin', 'true', 1); location.reload(); }, (e) => console.error(e)); }

into

function signIn(scope = GA_SCOPE,plugin_name= GA_PLUGIN_NAME) {
  return gapi.auth2.getAuthInstance().signIn({ scope,plugin_name }).then(() => {
    setCookie('guser-loggedin', 'true', 1);
    location.reload();
  }, (e) => console.error(e));
}
  • After all these changes the login button load, but the script didn't load data as it suppose to do(in the last screenshot no data is showing and a few weird error form console)

index.html

    <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>Top Shelf Distillers Staff</title>
    <!-- Icon -->
    <link
      rel="icon"
      href="https://cdn.shopify.com/s/files/1/2256/4539/files/top-shelf-distillers-store-2.svg?v=1634904798"
      type="image/x-icon"
    />
    <!-- Font Awesome -->
    <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.11.2/css/all.css"
    />
    <!-- Google Fonts Roboto -->
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
    />
    <!-- MDB UI KIT -->
    <link rel="stylesheet" href="css/mdb.min.css" />
    <!-- Custom styles -->
    <style></style>
  </head>

  <body style="background-color: hsl(0, 0%, 96%)">
    <!--Main Navigation-->
    <header class="mb-10">
      <!-- Navbar-->
      <nav
        class="navbar navbar-expand-lg navbar-light bg-white shadow-2 fixed-top"
      >
        <div
          class="
            container-fluid
            justify-content-center justify-content-md-between
          "
        >
          <!-- Left elements -->
          <ul class="navbar-nav flex-row align-items-center">
            <li class="nav-item me-3 me-lg-1">
              <a
                class="nav-link d-flex"
                href="https://topshelfdistillers.com/"
                target="_blank"
              >
                <img
                  src="https://cdn.shopify.com/s/files/1/2256/4539/files/top-shelf-distillers-store-2.svg?v=1634904798"
                  height="31"
                  alt=""
                  loading="lazy"
                  class="me-2"
                />
                <span
                  style="
                    font-size: 19px;
                    font-weight: 500;
                    color: hsl(0, 0%, 30%);
                  "
                  >Top Shelf Distillers <span class="text-theme">Staff</span></span
                >
              </a>
            </li>
            <li class="nav-item me-3 me-lg-1">
              <a
                class="nav-link"
                href="https://twitter.com/TSDistillers"
                rel="nofollow"
                target="_blank"
              >
                <span><i class="fab fa-twitter"></i></span>
              </a>
            </li>
            <li class="nav-item me-3 me-lg-1">
              <a
                class="nav-link"
                href="https://github.com/mdbootstrap/mdb-easydata"
                rel="nofollow"
                target="_blank"
              >
                <span><i class="fab fa-github"></i></span>
              </a>
            </li>
          </ul>
          <!-- Left elements -->



          <!-- Right elements -->
          <ul class="navbar-nav flex-row d-none d-md-flex">
            <li class="nav-item me-3 me-lg-1">

              <button
                id="sign-in-btn"
                type="button"
                class="btn btn-primary btn-rounded"
                style="display: none"
                onclick="signIn()"
              >
                Login
              </button>
            </li>

            <li class="nav-item me-3 me-lg-1">
              <button
                id="sign-out-btn"
                type="button"
                class="btn btn-primary btn-rounded"
                style="display: none"
                onclick="signOut()"
              >
                Logout
              </button>
            </li>

            <li class="nav-item me-3 me-lg-1">
              <button
                type="button"
                class="btn btn-primary btn-rounded"
                style="display: none"
                onclick="loadData()"
              >
                Load Data
              </button>
            </li>

            <li class="nav-item me-3 me-lg-1">
              <a
                href="https://mdbootstrap.com/"
                target="_blank"
                class="btn btn-danger btn-rounded mx-2 d-none d-lg-inline-block"
                ><i class="fas fa-cubes me-2"></i>MDB UI KIT</a
              >
            </li>
          </ul>
          <!-- Right elements -->
        </div>
      </nav>
      <!-- Navbar -->
    </header>
    <!--Main Navigation-->

    <!--Main layout-->
    <main>
      <div class="container">
        <!--Section: Design Block-->
        <section class="mb-8">
          <h3 class="mb-7 text-center fw-bold">Last 7 days</h3>
          <div class="row">
            <div class="col-md-4 mb-4 mb-md-0">
              <!-- Card -->
              <div class="card">
                <div
                  class="
                    card-body
                    d-flex
                    justify-content-start
                    align-items-center
                  "
                >
                  <div
                    class="
                      bg-primary
                      text-white
                      rounded-4
                      d-flex
                      justify-content-center
                      align-items-center
                    "
                    style="width: 50px; height: 50px"
                  >
                    <i class="fas fa-users fa-lg"></i>
                  </div>
                  <div class="ms-3">
                    <p class="text-muted mb-1">Users</p>
                    <p class="mb-0">
                      <span id="displayUsers" class="h4 me-2"></span>
                    </p>
                  </div>
                </div>
              </div>
              <!-- Card -->
            </div>
            <div class="col-md-4 mb-4 mb-md-0">
              <!-- Card -->
              <div class="card">
                <div
                  class="
                    card-body
                    d-flex
                    justify-content-start
                    align-items-center
                  "
                >
                  <div
                    class="
                      bg-primary
                      text-white
                      rounded-4
                      d-flex
                      justify-content-center
                      align-items-center
                    "
                    style="width: 50px; height: 50px"
                  >
                    <i class="fas fa-file fa-lg"></i>
                  </div>
                  <div class="ms-3">
                    <p class="text-muted mb-1">Page views</p>
                    <p class="mb-0">
                      <span id="displayPageViews" class="h4 me-2"></span>
                    </p>
                  </div>
                </div>
              </div>
              <!-- Card -->
            </div>
            <div class="col-md-4">
              <!-- Card -->
              <div class="card">
                <div
                  class="
                    card-body
                    d-flex
                    justify-content-start
                    align-items-center
                  "
                >
                  <div
                    class="
                      bg-primary
                      text-white
                      rounded-4
                      d-flex
                      justify-content-center
                      align-items-center
                    "
                    style="width: 50px; height: 50px"
                  >
                    <i class="fas fa-chart-line fa-lg"></i>
                  </div>
                  <div class="ms-3">
                    <p class="text-muted mb-1">Sessions</p>
                    <p class="mb-0">
                      <span id="displaySessions" class="h4 me-2"></span>
                    </p>
                  </div>
                </div>
              </div>
              <!-- Card -->
            </div>
          </div>
        </section>
        <!--Section: Design Block-->
      </div>
    </main>
    <!--Main layout-->

    <!--Footer-->
    <footer></footer>
    <!--Footer-->
  </body>

  <!-- MDB ESSENTIAL -->
  <script type="text/javascript" src="js/mdb.min.js"></script>
  <!-- Google API -->
  <script src="https://apis.google.com/js/api.js"></script>
  <!-- easyData - Google Analtyics -->
  <script type="text/javascript" src="js/easyData-google-analtyics.js"></script>

  <!-- easyData - Fetching data-->
  <script>
    // Your Client ID
    const CLIENT_ID = "1086039826600-2r3481ge270o57vau3kshic6l4vrg4gg.apps.googleusercontent.com";
    

    function loadData() {
      // Your GA property ID
      const propertyId = "323434397";

      const startDate = "7daysAgo";
      const endDate = "today";
      const metrics = [
        { name: "activeUsers" },
        { name: "screenPageViews" },
        { name: "sessions" },
      ];

      const query = {
        dateRanges: [{ startDate, endDate }],
        metrics: metrics,
      };

      runReport(propertyId, query, displayResult);
    }

    function displayResult(response) {
      document.getElementById("displayUsers").innerHTML =
        response.result.rows[0].metricValues[0].value;
      document.getElementById("displayPageViews").innerHTML =
        response.result.rows[0].metricValues[1].value;
      document.getElementById("displaySessions").innerHTML =
        response.result.rows[0].metricValues[2].value;
    }

    // Login buttons

    document.addEventListener("gapi-loaded", (e) => {
      
      if (isSignedIn()) {
        document.getElementById("sign-out-btn").style.display = "block";
        document.getElementById("sign-in-btn").style.display = "none";
        loadData();
        console.log("happen");
      } else {
        console.log("happen");
        document.getElementById("sign-in-btn").style.display = "block";
        document.getElementById("sign-out-btn").style.display = "none";
      }
    });
  </script>
</html>

easyData-google-analtyics.js

// Google Analytics

const GA_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
const GA_API_URL = "https://analyticsdata.googleapis.com/$discovery/rest?version=v1beta";
const GA_PLUGIN_NAME = "quickstart";

gapi.load("client:auth2", function () {
  gapi.auth2.init({ client_id: CLIENT_ID,plugin_name: GA_PLUGIN_NAME}).then(() => document.dispatchEvent(new Event('gapi-loaded')));
});

function signIn(scope = GA_SCOPE,plugin_name= GA_PLUGIN_NAME) {
  return gapi.auth2.getAuthInstance().signIn({ scope,plugin_name }).then(() => {
    setCookie('guser-loggedin', 'true', 1);
    location.reload();
  }, (e) => console.error(e));
}

function signOut() {
  return gapi.auth2.getAuthInstance().signOut().then(() => {
    setCookie('guser-loggedin', 'true', -1);
    location.reload();}, (e) => console.error(e));
}

function loadClient(apiPath = GA_API_URL) {
  return gapi.client.load(apiPath);
}

function runReport(propertyId, query, cb = function (res) { console.log(res); }, err = function (err) { console.error(err); }) {

  return loadClient().then(() => gapi.client.analyticsdata.properties
    .runReport({
      property: "properties/" + propertyId,
      resource: query
    })
    .then(cb, err));
}

function isSignedIn() {
  if (getCookie('guser-loggedin') === 'true') return true;
  return false;
}

function setCookie(cname = 'guser-loggedin', cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  let expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  let name = cname + "=";
  let ca = document.cookie.split(';');
  for(let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

enter image description here

enter image description here enter image description here enter image description here


Solution

  • So finally after a few trying, I found my way of solving this is actually correct!The error in the console is actually caused by my setup in credential is not complete. If any one want to use the sample code that I provided below to fetch data form Google Analytics4, simply follow the instruction in the video attched below to setup the OAUTH@ credential etcetera https://www.youtube.com/watch?v=teL_9dJDvRw

    1. Replace <REPLACE_WITH_CLIENT_ID> with your client ID created above.
    2. Replace <REPLACE_WITH_PROPERTY_ID> with a property ID, which can be retrieved from the GA4 admin (only GA4, GAU will not applied in this situation, I had tried all the approach to fetch data form GAU in another thread which ended up in failure, so if you are using GAU currently, I will suggest you to migrate to GA4).

    index.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        <meta http-equiv="x-ua-compatible" content="ie=edge" />
        <title>easyData - open source & free solutions</title>
        <!-- Icon -->
        <link
          rel="icon"
          href="https://easy-data.mdbgo.io/img/favicon/favicon-32x32.png"
          type="image/x-icon"
        />
        <!-- Font Awesome -->
        <link
          rel="stylesheet"
          href="https://use.fontawesome.com/releases/v5.11.2/css/all.css"
        />
        <!-- Google Fonts Roboto -->
        <link
          rel="stylesheet"
          href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
        />
        <!-- MDB UI KIT -->
        <link rel="stylesheet" href="css/mdb.min.css" />
        <!-- Custom styles -->
        <style></style>
      </head>
    
      <body style="background-color: hsl(0, 0%, 96%)">
        <!--Main Navigation-->
        <header class="mb-10">
          <!-- Navbar-->
          <nav
            class="navbar navbar-expand-lg navbar-light bg-white shadow-2 fixed-top"
          >
            <div
              class="
                container-fluid
                justify-content-center justify-content-md-between
              "
            >
              <!-- Left elements -->
              <ul class="navbar-nav flex-row align-items-center">
                <li class="nav-item me-3 me-lg-1">
                  <a
                    class="nav-link d-flex"
                    href="https://easy-data.mdbgo.io/"
                    target="_blank"
                  >
                    <img
                      src="https://easy-data.mdbgo.io/img/logo.png"
                      height="31"
                      alt=""
                      loading="lazy"
                      class="me-2"
                    />
                    <span
                      style="
                        font-size: 19px;
                        font-weight: 500;
                        color: hsl(0, 0%, 30%);
                      "
                      >easy<span class="text-theme">Data</span></span
                    >
                  </a>
                </li>
                <li class="nav-item me-3 me-lg-1">
                  <a
                    class="nav-link"
                    href="https://twitter.com/ascensus_mdb"
                    rel="nofollow"
                    target="_blank"
                  >
                    <span><i class="fab fa-twitter"></i></span>
                  </a>
                </li>
                <li class="nav-item me-3 me-lg-1">
                  <a
                    class="nav-link"
                    href="https://github.com/mdbootstrap/mdb-easydata"
                    rel="nofollow"
                    target="_blank"
                  >
                    <span><i class="fab fa-github"></i></span>
                  </a>
                </li>
              </ul>
              <!-- Left elements -->
    
              <!-- Center elements -->
              <ul class="navbar-nav flex-row d-none d-md-flex">
                <li class="nav-item me-3 me-lg-1">
                  <a
                    class="nav-link d-flex"
                    href="https://easy-data.mdbgo.io/#section-google-analytics"
                    target="_blank"
                  >
                    <img
                      src="https://easy-data.mdbgo.io/img/logo-ga.png"
                      height="22"
                      class="me-2"
                      alt=""
                    />
                    <span>Google Analytics example</span>
                  </a>
                </li>
              </ul>
              <!-- Center elements -->
    
              <!-- Right elements -->
              <ul class="navbar-nav flex-row d-none d-md-flex">
                <li class="nav-item me-3 me-lg-1">
                  <button
                    id="sign-in-btn"
                    type="button"
                    class="btn btn-primary btn-rounded"
                    style="display: none"
                    onclick="signIn()"
                  >
                    Login
                  </button>
                </li>
    
                <li class="nav-item me-3 me-lg-1">
                  <button
                    id="sign-out-btn"
                    type="button"
                    class="btn btn-primary btn-rounded"
                    style="display: none"
                    onclick="signOut()"
                  >
                    Logout
                  </button>
                </li>
    
                <li class="nav-item me-3 me-lg-1">
                  <button
                    type="button"
                    class="btn btn-primary btn-rounded"
                    style="display: none"
                    onclick="loadData()"
                  >
                    Load Data
                  </button>
                </li>
    
                <li class="nav-item me-3 me-lg-1">
                  <a
                    href="https://mdbootstrap.com/"
                    target="_blank"
                    class="btn btn-danger btn-rounded mx-2 d-none d-lg-inline-block"
                    ><i class="fas fa-cubes me-2"></i>MDB UI KIT</a
                  >
                </li>
              </ul>
              <!-- Right elements -->
            </div>
          </nav>
          <!-- Navbar -->
        </header>
        <!--Main Navigation-->
    
        <!--Main layout-->
        <main>
          <div class="container">
            <!--Section: Design Block-->
            <section class="mb-8">
              <h3 class="mb-7 text-center fw-bold">Last 7 days</h3>
              <div class="row">
                <div class="col-md-4 mb-4 mb-md-0">
                  <!-- Card -->
                  <div class="card">
                    <div
                      class="
                        card-body
                        d-flex
                        justify-content-start
                        align-items-center
                      "
                    >
                      <div
                        class="
                          bg-primary
                          text-white
                          rounded-4
                          d-flex
                          justify-content-center
                          align-items-center
                        "
                        style="width: 50px; height: 50px"
                      >
                        <i class="fas fa-users fa-lg"></i>
                      </div>
                      <div class="ms-3">
                        <p class="text-muted mb-1">Users</p>
                        <p class="mb-0">
                          <span id="displayUsers" class="h4 me-2"></span>
                        </p>
                      </div>
                    </div>
                  </div>
                  <!-- Card -->
                </div>
                <div class="col-md-4 mb-4 mb-md-0">
                  <!-- Card -->
                  <div class="card">
                    <div
                      class="
                        card-body
                        d-flex
                        justify-content-start
                        align-items-center
                      "
                    >
                      <div
                        class="
                          bg-primary
                          text-white
                          rounded-4
                          d-flex
                          justify-content-center
                          align-items-center
                        "
                        style="width: 50px; height: 50px"
                      >
                        <i class="fas fa-file fa-lg"></i>
                      </div>
                      <div class="ms-3">
                        <p class="text-muted mb-1">Page views</p>
                        <p class="mb-0">
                          <span id="displayPageViews" class="h4 me-2"></span>
                        </p>
                      </div>
                    </div>
                  </div>
                  <!-- Card -->
                </div>
                <div class="col-md-4">
                  <!-- Card -->
                  <div class="card">
                    <div
                      class="
                        card-body
                        d-flex
                        justify-content-start
                        align-items-center
                      "
                    >
                      <div
                        class="
                          bg-primary
                          text-white
                          rounded-4
                          d-flex
                          justify-content-center
                          align-items-center
                        "
                        style="width: 50px; height: 50px"
                      >
                        <i class="fas fa-chart-line fa-lg"></i>
                      </div>
                      <div class="ms-3">
                        <p class="text-muted mb-1">Sessions</p>
                        <p class="mb-0">
                          <span id="displaySessions" class="h4 me-2"></span>
                        </p>
                      </div>
                    </div>
                  </div>
                  <!-- Card -->
                </div>
              </div>
            </section>
            <!--Section: Design Block-->
          </div>
        </main>
        <!--Main layout-->
    
        <!--Footer-->
        <footer></footer>
        <!--Footer-->
      </body>
    
      <!-- MDB ESSENTIAL -->
      <script type="text/javascript" src="js/mdb.min.js"></script>
      <!-- Google API -->
      <script src="https://apis.google.com/js/api.js"></script>
      <!-- easyData - Google Analtyics -->
      <script type="text/javascript" src="js/easyData-google-analtyics.js"></script>
    
      <!-- easyData - Fetching data-->
      <script>
        // Your Client ID
        const CLIENT_ID = "<REPLACE_WITH_CLIENT_ID>";
    
        function loadData() {
          // Your GA property ID
          const propertyId = "<REPLACE_WITH_PROPERTY_ID>";
    
          const startDate = "7daysAgo";
          const endDate = "today";
          const metrics = [
            { name: "activeUsers" },
            { name: "screenPageViews" },
            { name: "sessions" },
          ];
    
          const query = {
            dateRanges: [{ startDate, endDate }],
            metrics: metrics,
          };
    
          runReport(propertyId, query, displayResult);
        }
    
        function displayResult(response) {
          document.getElementById("displayUsers").innerHTML =
            response.result.rows[0].metricValues[0].value;
          document.getElementById("displayPageViews").innerHTML =
            response.result.rows[0].metricValues[1].value;
          document.getElementById("displaySessions").innerHTML =
            response.result.rows[0].metricValues[2].value;
        }
    
        // Login buttons
        document.addEventListener("gapi-loaded", (e) => {
          if (isSignedIn()) {
            document.getElementById("sign-out-btn").style.display = "block";
            document.getElementById("sign-in-btn").style.display = "none";
            loadData();
          } else {
            document.getElementById("sign-in-btn").style.display = "block";
            document.getElementById("sign-out-btn").style.display = "none";
          }
        });
      </script>
    </html>
    

    easyData-google-analtyics.js

    // Google Analytics
    
    const GA_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
    const GA_API_URL = "https://analyticsdata.googleapis.com/$discovery/rest?version=v1beta";
    const GA_PLUGIN_NAME = "quickstart";
    
    gapi.load("client:auth2", function () {
      gapi.auth2.init({ client_id: CLIENT_ID,plugin_name: GA_PLUGIN_NAME}).then(() => document.dispatchEvent(new Event('gapi-loaded')));
    });
    
    function signIn(scope = GA_SCOPE,plugin_name= GA_PLUGIN_NAME) {
      return gapi.auth2.getAuthInstance().signIn({ scope,plugin_name }).then(() => {
        setCookie('guser-loggedin', 'true', 1);
        location.reload();
      }, (e) => console.error(e));
    }
    
    function signOut() {
      return gapi.auth2.getAuthInstance().signOut().then(() => {
        setCookie('guser-loggedin', 'true', -1);
        location.reload();}, (e) => console.error(e));
    }
    
    function loadClient(apiPath = GA_API_URL) {
      return gapi.client.load(apiPath);
    }
    
    function runReport(propertyId, query, cb = function (res) { console.log(res); }, err = function (err) { console.error(err); }) {
    
      return loadClient().then(() => gapi.client.analyticsdata.properties
        .runReport({
          property: "properties/" + propertyId,
          resource: query
        })
        .then(cb, err));
    }
    
    function isSignedIn() {
      if (getCookie('guser-loggedin') === 'true') return true;
      return false;
    }
    
    function setCookie(cname = 'guser-loggedin', cvalue, exdays) {
      const d = new Date();
      d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
      let expires = "expires="+d.toUTCString();
      document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    }
    
    function getCookie(cname) {
      let name = cname + "=";
      let ca = document.cookie.split(';');
      for(let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
          c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
          return c.substring(name.length, c.length);
        }
      }
      return "";
    }
    

    Sample Website Data Loaded