Mixpanel の Funnel を解析する Google Apps Script

API_KEY      = "";
API_SECRET   = "";


function getFunnel(funnel_id, from_date, to_date) {

  try {
    var data = {
      'unit' : "day",
      'from_date' : from_date,
      'to_date' : to_date,
      'funnel_id' : funnel_id
    }
    data['sig']   = getSig(data);

    var url = "https://mixpanel.com/api/2.0/funnels/?" + createParameter(data);
    var response = UrlFetchApp.fetch(url);
    if (!response) {
      return null;
    }
    return Utilities.jsonParse(response.getContentText());
  } catch(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;
}