back-helper.js 1.05 KB
/**
 * Created by TaoHuang on 2016/6/27.
 */

'use strict';

/**
 * 签名算法参考微信支付加密算法
 * 参考链接:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
 *
 */

const _ = require('lodash');
const SALT = '_+@#$%^';

/**
 * 加密手机的数据,生成加密token
 * @param data json
 * @returns string
 */

const _packageObject = (data) => {
    return _.keys(data).sort().map(key => `${key}=${data[key]}`).join('&').toUpperCase();
};

const _encodeMD5 = (str) => {
    const md5 = require('md5');

    return md5(str).toUpperCase();
};

/**
 * 返回一个 md5加密后的字符串
 * @param data json
 */
const makeToken = (data) => {
    let saltData = Object.assign({}, data, {key: SALT});
    let str = _packageObject(saltData);

    return _encodeMD5(str);
};

/**
 * 验证 token 是否一致
 */
const validateToken = (data, token) => {
    let saltData = Object.assign({}, data, {key: SALT});
    let str = _packageObject(saltData);

    return _encodeMD5(str) === token;
};

module.exports = {
    makeToken,
    validateToken
};