Skip to content

Instantly share code, notes, and snippets.

@shinux
Last active September 24, 2017 03:15
Show Gist options
  • Save shinux/aaadea384c0bb3dc17327aea0ac0baff to your computer and use it in GitHub Desktop.
Save shinux/aaadea384c0bb3dc17327aea0ac0baff to your computer and use it in GitHub Desktop.
nowcoder signature generator
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