Skip to content

Instantly share code, notes, and snippets.

@ivarvong
Created September 21, 2012 19:48
Show Gist options
  • Save ivarvong/3763494 to your computer and use it in GitHub Desktop.
Save ivarvong/3763494 to your computer and use it in GitHub Desktop.
Mixpanel Data Export API hack for Node.JS
// this is for node.js. putting your api_secret in a web browser is not ideal.
var crypto = require('crypto');
var md5sum = crypto.createHash('md5');
var request = require('request');
var api_key = 'your_api_key_here';
var api_secret = 'your_api_secret_here';
var api_endpoint = 'http://mixpanel.com/api/2.0/';
var current_time = parseInt((new Date().getTime())/1000);
var expire_time = current_time + 1000; // 1000 seconds in the future is the expire time.
var buildQuery = function(endpoint, paramDict) {
paramDict['format'] = 'json';
var paramString = "";
var paramKeys = Object.keys(paramDict);
paramKeys.sort();
for(var i=0;i<paramKeys.length;i++) {
paramString += paramKeys[i] + "=" + escape(paramDict[paramKeys[i]]) + "&";
}
paramDict['api_key'] = api_key;
paramDict['expire'] = expire_time;
var paramKeys = Object.keys(paramDict);
paramKeys.sort();
var paramStringToHash = "";
for(var i=0;i<paramKeys.length;i++) {
paramStringToHash += paramKeys[i] + "=" + escape(paramDict[paramKeys[i]]);
}
var signature = md5sum.update(paramStringToHash + api_secret).digest("hex");
var url = api_endpoint + endpoint[0] + '/' + endpoint[1] + '/?';
url += "sig=" + signature;
url += "&" + paramString;
url += "api_key=" + api_key;// no '&' because building paramString leaves one on the end
url += "&expire=" + expire_time;
request(url, function(err, res, body) {
if (!err && res.statusCode == 200) {
console.log(body);
}
});
}
buildQuery(
['events', 'properties'],
{
'event': "pages",
'name': 'page',
'type': 'general',
'unit': 'minute',
'interval': '120',
'limit': '20'
});
@forty
Copy link

forty commented Feb 14, 2013

Do not escape the parameter value. See forty/node-mixpanel-api@600d89e

@templth
Copy link

templth commented Mar 17, 2016

Thanks for the code!

I saw a small issue at the md5 level. You need to create a md5 hash each time not only once:

var md5sum = crypto.createHash('md5');
var signature = md5sum.update(paramStringToHash + api_secret).digest("hex");

instead of

var signature = md5sum.update(paramStringToHash + api_secret).digest("hex");

See these links:

Hope it will be helpful to other people!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment