é£è¼ç¬¬2åç®ã¯Google Analyticsã使ã£ã¦PVãåå¾ãã¦ã¿ã¾ãããã
é£è¼ç®æ¬¡
ã¯ããã«
第ï¼åãGoogle Analytics APIã®å©ç¨æºå
第ï¼åãGoogle AnalyticsããPVãåå¾ãã
第ï¼åãTwitter APIã®å©ç¨æºå
第ï¼åãTwitterã«æ稿ãã
第ï¼åãWebã¢ããªã±ã¼ã·ã§ã³ã«ã¾ã¨ãã
æçµåãAzureã¸ã®ãããã¤
Visual Studioã§ããã¸ã§ã¯ããä½æ
ãTweetPVãã¨ããååã§ã¯ã©ã¹ã©ã¤ãã©ãªãä½æãã¾ããã½ãªã¥ã¼ã·ã§ã³åã¯ãTweetPVAppsãã«ãã¦ããã¾ãã
Google.Apis.Analytics.v3 Client Libraryã®ã¤ã³ã¹ãã¼ã«
ããã±ã¼ã¸ããã¼ã¸ã£ã³ã³ã½ã¼ã«ã§Google.Apis.Analytics.v3 Client Libraryãã¤ã³ã¹ãã¼ã«ãã¾ãã
PM> Install-Package Google.Apis.Analytics.v3
app.configã«Analytic APIé¢é£ã®è¨å®ã追å
app.configã«ååè¡ã£ãéã«åå¾ãã以ä¸ã®è¨å®ã追å ãã¾ãã
- ä½æããP12ãã¼ã®ãã¡ã¤ã«åï¼ãã«ãã¹ï¼
- ã¡ã¼ã«ã¢ãã¬ã¹
- ãã¥ã¼ID
<configuration> <appSettings> <add key="analyticsKeyFile" value="xxxxx.p12"/> <add key="analyticsCredentialId" value="[email protected]"/> <add key="analyticsViewId" value="99999999"/> </appSettings>
AnalyticsHelperã¯ã©ã¹ã®ä½æ
ããã¸ã§ã¯ãã«AnalyticsHelperã¯ã©ã¹ã追å ãã¾ãã
ã³ã¼ãã¯ãGoogle Analytics API を使って前日の PV を取得するコードを C# で書いてみた - しばやん雑記ãã®å 容ã¾ããã¯ãªã§ãããã°ãããããã¨ãã
â»P12ãã¼ãã¡ã¤ã«ã®ãã¹ãã³ã³ã¹ãã©ã¯ã¿ã§æå®ããããã«ãã¦ã¾ãã
public class AnalyticsHelper { private AnalyticsService _service; public AnalyticsHelper(string analyticsKeyFile) { // Azure Web ãµã¤ãã§åããå ´åã«ã¯ WEBSITE_LOAD_USER_PROFILE = 1 å¿ é var certificate = new X509Certificate2(analyticsKeyFile, "notasecret", X509KeyStorageFlags.Exportable); // Scopes ã¯æå®ããªãã¨ã¨ã©ã¼ã«ãªã var analyticsCredentialId = ConfigurationManager.AppSettings["analyticsCredentialId"]; var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(analyticsCredentialId) { Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly } }.FromCertificate(certificate)); // HttpClientInitializer ã« credential å ¥ããã®ã¯éåæãããã©æ£ããããã _service = new AnalyticsService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "TweetPVSample", }); } public async Task<int> GetPvAsync() { // Azure 㯠UTC ãªã®ã§ +9 æéã㦠-1 æ¥ var date = DateTime.UtcNow.AddHours(9).AddDays(-1).ToString("yyyy-MM-dd"); // ãã¥ã¼ã®IDãæå®ãã¦ãã¼ã¿ãåå¾ãã var analyticsViewId = ConfigurationManager.AppSettings["analyticsViewId"]; var data = await _service.Data.Ga.Get("ga:" + analyticsViewId, date, date, "ga:pageviews").ExecuteAsync(); return int.Parse(data.Rows[0][0]); } }
åä½ç¢ºèª
åä½ç¢ºèªã§ãããã³ã³ã½ã¼ã«ã¢ããªã±ã¼ã·ã§ã³ãããã¯åä½ãã¹ãããã¸ã§ã¯ããä½æãã¦ã以ä¸ã®æ§ãªã³ã¼ãã§åä½ç¢ºèªã§ãã¾ãã
var file = ConfigurationManager.AppSettings["analyticsKeyFile"]; var sut = new AnalyticsHelper(file); var pv = sut.GetPvAsync().Result;
ç§ã¯ã©ã¡ããã¨ããã¨åä½ãã¹ãããã¸ã§ã¯ãã§ç¢ºèªããæ´¾ã§ããã
ããã
ããã§Google AnalyticsããPVåå¾ã§ããããã«ãªãã¾ããã次ã¯Twitterã«åãçºã®æºåãè¡ãã¾ãã