12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import { generateUUID } from "@/utils/index"
- import { sha256 } from 'js-sha256'
- import qs from 'qs'
- // 加密方式:请求头加参数: appId + nonce + timestamp + sign
- // (sign为: queryJsonData+paramsToStrSort+appSecret拼接后sha256加密字符串)
- // 开启参数加密
- export const encryptionFun = (config) => {
- // console.log('加密内容用完请注释->config', config)
- const initSign = {
- appId: 'web_client', // 与后端协商一致使用
- nonce: generateUUID(), // 前端生成唯一参数
- timestamp: new Date().getTime() + 1000,
- }
- // 固定的参数初始化成字符串
- const paramsToStrSort = ['appId', 'nonce', 'timestamp'] // 顺序不能变
- let paramsStr = paramsToStrSort.reduce((str, key) => {
- if (initSign[key]) str = str ? str + `&${key}=${initSign[key]}` : `${key}=${initSign[key]}`
- return str
- }, '')
- const appSecret = 'fa0fc0b5098b974b' // 与后端协商一致使用(拼接在paramsStr后面,且拼接时不加key)
- paramsStr = paramsStr + appSecret
- // console.log('加密内容用完请注释->paramsStr', paramsStr)
- // 请求的参数json // 携带的参数json一下,url拼接参数的直接用,没有参数不拼接
- const queryJsonData = config.data && Object.keys(config.data).length ?
- decodeURIComponent(JSON.stringify(sortObjectByKey(config.data))) : config.params && Object.keys(config.params).length ?
- decodeURIComponent(qs.stringify(sortObjectByKey(config.params), { allowDots: true }) ): config.url.split('?')?.length>1 ?
- config.url.split('?')[1] : ''
- // sha256加密字符串
- if (paramsStr) initSign.sign = sha256(queryJsonData + paramsStr)
- // console.log('加密内容用完请注释->queryJsonData', queryJsonData)
- // 请求头加参数initSign,请求头加参数: appId + nonce + timestamp + sign
- if (initSign && Object.keys(initSign).length) Object.keys(initSign).forEach(key => { (config).header[key] = initSign[key] })
- }
- function sortObjectByKey(obj) {
- return obj
- // return Object.keys(obj)
- // .sort()
- // .reduce((sortedObj, key) => {
- // sortedObj[key] = obj[key];
- // return sortedObj;
- // }, {});
- }
|