Google Apps Script で Mixpanel の解析データを取得する

Mixpanel の API を利用して、Google Apps Script 上でデータを取得する方法です。JSON 形式で返ってくるので、こちらを解析して SpreadSheet にグラフ表示することもできます。

API_KEY      = "*******************************";
API_SECRET   = "*****************************";


function getEvent() {

  try {
    var data = {
      'unit'     : "day",
      'interval' : 15,
      'type'     : "general",
      'event'    : '["SignUp"]'
    }
    data['sig']   = getSig(data);
    data['event'] = encodeURIComponent(data['event']);

    var url = "http://mixpanel.com/api/2.0/events/?" + createParameter(data);
    var response = UrlFetchApp.fetch(url);
    if (!response) {
      Logger.log("no response");
      return;
    }
    Logger.log(response.getContentText());
    return response.getContentText();
  } catch(e) {
    Logger.log(e);
    return null;
  }
}

function getSig(hash) {
  var keys = [];
  var kv   = "";

  var currentDate = new Date;
  var expire = Math.floor(currentDate.getTime() / 1000) + 600;

  delete hash['sig'];
  hash['api_key'] = API_KEY;
  hash['expire'] = expire;
  hash['format'] = "json";

  for (var k in hash) keys.push(k);
  keys.sort();
  var length = keys.length;
  for(var i = 0; i < length; i++){
    kv += keys[i] + "=" + hash[keys[i]];
  }
  return getMD5Hash(kv + API_SECRET);
}

function getMD5Hash(input) {
  var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
  var txtHash = '';
  for (j = 0; j < rawHash.length; j++) {
    var hashVal = rawHash[j];
    if (hashVal < 0)
      hashVal += 256;
    if (hashVal.toString(16).length == 1)
      txtHash += "0";
    txtHash += hashVal.toString(16);
  }
  return txtHash;
}

function createParameter(hash) {
  var param = "";
  for(var key in hash) {
    param += key + "=" + hash[key] + "&";
  }
  param = param.substring(0, param.length-1);
  return param;
}