sign.js 1.94 KB
var _ = require('lodash'),
    md5 = require('md5');

var privateKey = {
    android: 'fd4ad5fcfa0de589ef238c0e7331b585',
    iphone: 'a85bb0674e08986c6b115d5e3a4884fa',
    ipad: 'ad9fcda2e679cf9229e37feae2cdcf80',
    web: '0ed29744ed318fd28d2c07985d3ba633',
    yoho: 'fd4ad5fcsa0de589af23234ks1923ks',
    h5: 'fd4ad5fcfa0de589ef238c0e7331b585'
};

/**
 * 排序参数
 * @param  {Object} argument 需要排序的参数对象
 * @return {Object}          排序之后的参数对象
 */
function packageSort(argument) {
    var keys = Object.keys(argument),
        len = keys.length,
        i,
        k,
        newObj = {};

    keys.sort();

    for (i = 0; i < len; i++) {
        k = keys[i];
        newObj[k] = argument[k];
    }

    return newObj;
}

/**
 * 生成签名
 * @param  {Object} argument 需要签名的数据
 * @return {string}          生成的签名字符串
 */
function makeSign(argument) {
    var qs = [];

    _.forEach(argument, function(value, key) {
        qs.push(key + '=' + _.trim(value));
    });

    return md5(qs.join('&')).toLowerCase();
}

// 生成API签名,调用后端接口的时候有私钥校验
exports.apiSign = function(params) {
    var sign = packageSort(Object.assign({
        'client_type': 'web',
        'private_key': privateKey.web,
        'app_version': '3.8.2',
        'os_version': 'yohobuy:h5',
        'screen_size': '720x1280',
        'v': '7'
    }, params));

    return Object.assign(sign, {
        client_secret: makeSign(sign)
    });
};

// 检查签名,APP 访问 H5 页面的时候需要检查
exports.checkSign = function(params) {
    var clientSecret = params.client_secret,
        sortedParams;

    // 忽略部分参数
    delete params.client_secret;
    delete params.q;
    delete params.debug_data;
    delete params['/api'];

    params.private_key = privateKey[params.client_type];
    sortedParams = packageSort(params);

    return clientSecret === makeSign(sortedParams);
};