目次

Google Analytics API v3 を用いて日別ページビュー数を取得する - C#

Google Analytics API v3 を利用して日別ページビュー数を取得するコードを紹介します。
サービス終了に関する注意
Google Universal Analytics はサービスを終了したため、現在はこの記事で紹介しているコードは動作しません。 新しい Google Analytics 4 (GA4) プロパティを利用する必要があります。 GA4プロパティからのデータ取得はこちらの記事を参照してください。

概要

こちらの記事では、Google Analytics API v3 を利用してGoogle Analyticsから情報を取得するシンプルなプログラムのコードを紹介しました。この記事では、日別のページビュー数を取得するコードを紹介します。

プログラム

UI

下図のUIを作成します。ButtonとTextBoxを1つずつ配置します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;

namespace GoogleAnalyticsTotalPVGet
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      X509Certificate2 certificate = new X509Certificate2(@"apikey.p12", "notasecret", X509KeyStorageFlags.Exportable);

      string serviceAccountEmail = "012345678901-abcdefghijklmnopqrstuvwxyz012345@developer.gserviceaccount.com";

      ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
      {
        Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly }
      }
      .FromCertificate(certificate));

      AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer
      {
        HttpClientInitializer = credential,
        ApplicationName = "sample app",
      });

      string enddate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
      string startdate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd");

      DataResource.GaResource.GetRequest request = service.Data.Ga.Get("ga:00000000", startdate, enddate, "ga:pageviews");
      request.Dimensions = "ga:date";
      GaData data = request.Execute();// Fetch();

      for (int i = 0; i < data.Rows.Count; i++) {
        DateTime dt = System.DateTime.ParseExact(data.Rows[i][0], "yyyyMMdd",
          System.Globalization.DateTimeFormatInfo.InvariantInfo,
          System.Globalization.DateTimeStyles.NoCurrentDateDefault);

        textBox1.Text += string.Format("{0}\t{1:d}\r\n", dt.ToString("yyyy-MM-dd"), Convert.ToInt32(data.Rows[i][1]));
      }
    }
  }
}

解説

  X509Certificate2 certificate = new X509Certificate2(@"apikey.p12", "notasecret", X509KeyStorageFlags.Exportable);

  string serviceAccountEmail = "012345678901-abcdefghijklmnopqrstuvwxyz012345@developer.gserviceaccount.com";

  ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
  {
    Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly }
  }
  .FromCertificate(certificate));

  AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer
  {
    HttpClientInitializer = credential,
    ApplicationName = "sample app",
  });
上記のコード(認証部分、サービスオブジェクトの生成)に関しては、こちらのページを参照して下さい。

  string enddate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
  string startdate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd");

  DataResource.GaResource.GetRequest request = service.Data.Ga.Get("ga:00000000", startdate, enddate, "ga:pageviews");
  request.Dimensions = "ga:date";
  GaData data = request.Execute();// Fetch();

  for (int i = 0; i < data.Rows.Count; i++) {
    DateTime dt = System.DateTime.ParseExact(data.Rows[i][0], "yyyyMMdd",
      System.Globalization.DateTimeFormatInfo.InvariantInfo,
      System.Globalization.DateTimeStyles.NoCurrentDateDefault);

    textBox1.Text += string.Format("{0}\t{1:d}\r\n", dt.ToString("yyyy-MM-dd"), Convert.ToInt32(data.Rows[i][1]));
  }
上記コードがAnalyticsから情報を取得するコードです。今回は、開始日が30日前、終了日を前日としています。AnalyticsServiceのData.Ga.Get()メソッドのメトリクスには"ga:pageviews"を指定し、ページビュー数を取得する設定とします。また、DataResource.GaResource.GetRequestオブジェクトのDimensionsプロパティに、"ga:date"を指定し、日別の情報として取得します。情報の取得はDataResource.GaResource.GetRequestオブジェクトのExecute()メソッドの呼び出しにより実行されます。

Data.Ga.Get()メソッドの第一に引数に値を取得するビューのIDを与えます、ビューのIDはAnalyticsの設定画面で取得した8桁の数値の前に"ga:"を付加した文字列になります。(ビューIDが"01234567"であれば、"ga:01234567"となります。)

取得した情報は、DataResource.GaResource.GetRequestオブジェクトのExecute()メソッドの戻り値として、GeDataオブジェクトが返されます。PVなどの情報はGaDataオブジェクト内に格納されています。GaDataオブジェクトのRowsプロパティは配列になっており、今回の例では、GaData.Rows[i][0]に日付が"yyyyMMdd"形式で入っており、GaData.Rows[i][1]にGaData.Rows[i][0]に設定されている日付のPV数が入っています。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[button1]をクリックします。Google Analyticsから取得したPVが下部のテキストボックスに表示されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-03-24
作成日: 2015-10-02
iPentec all rights reserverd.