util.ts 1.54 KB
/*
 * @Description:
 * @Author: huyue
 * @Date: 2022-10-10 10:54:14
 * @LastEditors: huyue
 * @LastEditTime: 2024-07-29 10:07:19
 */
import sha1 from "sha1";
import qs from "qs";
import md5 from "js-md5";
export const Util = {
  createSign: function (
    params: object,
    secret: string,
    noSignAttr = [],
    way = "sha1"
  ) {
    delete params.sign;
    params.timestamp = new Date().getTime();
    var strQs = qs.stringify(params, {
      arrayFormat: "indices",
      allowDots: true,
      encodeValuesOnly: true,
    });
    const objQs = strQs.split("&");
    const collect = objQs.reduce((collect: any, item) => {
      let [key, value] = item.split("=");
      if (value === null) {
        value = "";
      } else if (typeof value === "object") {
        value = JSON.stringify(value);
      }
      collect[key] = decodeURIComponent(value);
      return collect;
    }, {});
    const keys = Object.keys(collect).sort();
    const str = keys.reduce((col, key) => {
      if (!noSignAttr.includes(key)) {
        col.push(key, collect[key]);
      }
      return col;
    }, []);
    collect.sign = { sha1, md5 }
      [way](secret + str.join("") + secret)
      .toUpperCase();
    return collect;
  },
  rgb: function () {
    //rgb颜色随机
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r},${g},${b})`;
  },
};

export const createSign = Util.createSign;
export default Util;