sign.js 1.3 KB
/*
 * @Author: limin
 * @Date: 2019-08-26 18:02:49
 * @Last Modified by: chenwq
 * @Last Modified time: 2021-06-18 10:04:32
 */
import sha1 from "sha1"
import md5 from "md5"
import qs from "qs"
import { deepClone } from "@/common/util"

const sign = (params, noSignAttr = [], secret, way = "sha1") => {
  // console.log(way, "way")
  delete params.sign
  var objStr = qs.stringify(deepClone(params), {
    arrayFormat: "indices",
    allowDots: true,
    encodeValuesOnly: true
  })
  var objVal = objStr.split("&")
  var realObj = {}
  objVal.forEach((item) => {
    const idx = item.indexOf("=")
    realObj[item.split("=")[0]] = decodeURIComponent(item.slice(idx + 1))
  })
  // console.log(realObj)
  const keys = Object.keys(realObj).sort()
  var str = []
  var obj = null
  for (const key in realObj) {
    obj = realObj[key]
    if (obj === null) {
      obj = ""
    } else if (typeof obj === "object") {
      obj = JSON.stringify(obj)
    }
    realObj[key] = obj
  }
  keys.forEach((e) => {
    !noSignAttr.includes(e) && str.push(e + realObj[e])
  })
  // realObj.sign = sha1(secret + str.join("") + secret).toUpperCase()
  const signObj = { sha1, md5 }
  realObj.sign = signObj[way](secret + str.join("") + secret).toUpperCase()
  return realObj
}
export default sign