util.ts 1.35 KB
/*
 * @Description: 
 * @Author: huyue
 * @Date: 2022-10-10 10:54:14
 * @LastEditors: huyue
 * @LastEditTime: 2022-10-20 10:12:09
 */
import sha1 from 'sha1'
import qs from 'qs'
export const Util = {
  createSign: function(params: object, secret: string, noSignAttr = [], way = 'hexSha2') {
    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(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