Created
September 21, 2012 19:48
-
-
Save ivarvong/3763494 to your computer and use it in GitHub Desktop.
Mixpanel Data Export API hack for Node.JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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' | |
}); |
If I pass a event name with space that makes " invalid API signature" the error.
example:
'event': "pages" works 'event': "pages withspace" is not working :(
Do not escape the parameter value. See forty/node-mixpanel-api@600d89e
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
Hi @ivarvong,
I'm getting invalid API signature error. Is anything changed on the Mixpanel side ?
Thanks