2014 年も終わりなので Google Analytics API を使ってアクセス数の多いページを取得してみた - しばやん雑記 ãä»å¹´æå¾ã«ãããã¨æã£ããã§ãããã¢ã¯ã»ã¹æ°ã®å¤ãè¨äºã®æ å ±ã JavaScript 㨠OAuth 2 ã§ãåããã®ã§ã¯ãªããã¨æã£ãã®ã§ãå®éã«ãµã¼ãã¹åãã¦ã¿ã¾ããã
使ãæ¹ã¯åç´ã§ãOAuth 2 ã§ãã°ã¤ã³ãã¦ãããããã¦ã³ããåå¾ããã Web ããããã£ãé¸æããçæãã¿ã³ãã¯ãªãã¯ããã ãã§çµããã§ãã
æ°ç§å¾ã«ã¯å®è¡çµæãã¯ã¦ãªè¨æ³ãHTMLãMarkdown ã§åºåãããã®ã§ãé©å½ã«åå©ç¨ãã¦ãã ããã
å®è£ ã®è©±
Google API ã JavaScript ãã使ãå ´åã«ã¯ã©ã¤ãã©ãªãèªã¿è¾¼ã¿ã¾ããAPI ãã¼ã«ã ã注æã
<script> var apiKey = 'å ¬é API ã¸ã®ã¢ã¯ã»ã¹ãã¼'; function handleClientLoad() { gapi.client.setApiKey(apiKey); } </script> <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
API ãã¼ã¯ OAuth 2 ã®ã¯ã©ã¤ã¢ã³ãã·ã¼ã¯ã¬ããã¨ã¯å¥ç©ã§ããééãã㨠1 æéãããç¡é§ã«ãã¾ãã
OAuth 2 èªè¨¼ã¯ã¯ã©ã¤ã¢ã³ã ID ã¨ã¹ã³ã¼ããæå®ã㦠authorize ã¡ã½ãããå¼ã³åºãã¾ãããããåãããã«ã³ã¼ã«ããã¯å ã§æåããã失æãããå¤å¥ãã¾ãã
var clientId = '********'; var scopes = 'https://www.googleapis.com/auth/analytics.readonly'; gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false }, function(result) { if (result && !result.error) { // ãã°ã¤ã³æå } });
OAuth 2 ã§èªè¨¼ãå®äºããã API ãå¼ã³åºããããã«ãªãã¾ãã
Google Analytics API ã使ãåã« load ã¡ã½ããã§ãã¼ã¸ã§ã³ãæå®ãã¦ãã©ã¤ãã©ãªã追å ã§èªã¿è¾¼ãå¿ è¦ãããã¾ããã³ã¼ã«ããã¯ãå¼ã°ããå¾ã«ä½¿ããããã«ãªãã¾ãã
gapi.client.load('analytics', 'v3', function () { var req = gapi.client.analytics.management.profiles.list({ 'accountId': '~all', 'webPropertyId': '~all' }); req.execute(function (res) { self.webProperties(res.items); }); });
ãã®ä¾ã§ã¯ç¾å¨ã® Google ã¢ã«ã¦ã³ãã«é¢é£ä»ãã¦ãã Web ããããã£ããã¹ã¦åå¾ãã¾ãããã®å®è¡çµæã«ãã¥ã¼ ID ã Web ãµã¤ãã® URL ãå«ã¾ãã¦ããã®ã§ãPV ãåããããã«ãªãã¾ãã
ã¨ããããåºæ¬çãªæµãã¯ãããªæãã§ããä»åº¦ããä»å¹´æå¾ã®è¨äºã«ãªãã¾ããè¯ããå¹´ãã