Last active
September 24, 2017 03:15
-
-
Save shinux/aaadea384c0bb3dc17327aea0ac0baff to your computer and use it in GitHub Desktop.
nowcoder signature generator
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
import crypto from 'crypto'; | |
import request from 'request'; | |
import Promise from 'bluebird'; | |
Promise.promisifyAll(request); | |
/** | |
* format object to key=value&key1=value1 string. | |
* | |
* @param {Object} params - params object. | |
* @return {String} string | |
*/ | |
function stringUtil(params) { | |
const stringArray = []; | |
for (const i in params) { | |
stringArray.push(encodeURI(i) + '=' + encodeURI(params[i])); | |
} | |
return stringArray.join('&'); | |
} | |
/** | |
* niuke signature generator | |
* | |
* @param {String} apiSecret - api secret key | |
* @return {Object} sinature - signature string | |
*/ | |
function niukeSignatureGenerator(params, apiSecret) { | |
const stringArray = []; | |
for (const i in params) { | |
stringArray.push(encodeURI(i) + '=' + encodeURI(params[i])); | |
} | |
let _string = stringArray.join('&'); | |
_string += apiSecret; | |
return crypto.createHash('md5').update(_string).digest('hex'); | |
} | |
const apiKey = ''; | |
const apiSecret = ''; | |
const params = { | |
api_key: apiKey, | |
path: '/users/self', | |
timestamp: Math.floor(Date.now() / 1000), | |
}; | |
const signature = niukeSignatureGenerator(params, apiSecret); | |
params.sign = signature; | |
const paramString = stringUtil(params); | |
request.getAsync({ | |
uri: 'http://d.api.nowcoder.com/v1' + '/users/self' + '?' + paramString, | |
}) | |
.spread((res, body) => { | |
console.log(res.statusCode, body); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment