util.ts
1.02 KB
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
}
}
export const createSign = Util.createSign
export default Util