Pārlūkot izejas kodu

开启参数加密

lifanagju_citu 6 mēneši atpakaļ
vecāks
revīzija
4d822490cf
3 mainītis faili ar 54 papildinājumiem un 44 dzēšanām
  1. 7 1
      utils/index.js
  2. 36 40
      utils/openEncryption.js
  3. 11 3
      utils/request.js

+ 7 - 1
utils/index.js

@@ -126,7 +126,13 @@ export const checkIsImage = (url) => {
   return null
 }
 
-export const generateUUID = (len = 32, firstU = true, radix = null) => {
+/**
+ * getUuid 生成唯一id
+ * @param {Number} len uuid的长度
+ * @param {Boolean} firstU 将返回的首字母置为"u"
+ * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
+ */
+export const generateUUID = (len = 32, firstU = true, radix = null) => { // 商城复制
   const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
   const uuid = [];
   radix = radix || chars.length;

+ 36 - 40
utils/openEncryption.js

@@ -1,46 +1,42 @@
+/**
+ * encryptionFun()
+  示例1 http://xxx.com?id=123
+  encryptionFun('id=123')
+
+  示例2 http://xxx.com   {"id":123}
+  encryptionFun('{"id":123}')
+
+  示例3 http://xxx.com?id=123&name=张三   {"id":123}
+  encryptionFun('id=123&name=张三{"id":123}')
+*/
+
 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)
+/**
+ * 
+ * @param { str } raw 参数用&隔开
+ * @param { Object } body
+ * @returns 
+*/
+export const encryptionFun = ({raw, body, appId, AppSecret}) => {
   const initSign = {
-    appId: 'web_client', // 与后端协商一致使用
-    nonce: generateUUID(), // 前端生成唯一参数
-    timestamp: new Date().getTime() + 3000, // 多加两秒时间
+    appId,
+    nonce: generateUUID(),
+    timestamp: new Date().getTime() + 3000,
+  }
+  const _initSign = Object.keys(initSign).reduce((str, key) => str += `&${key}=${initSign[key]}`, '')
+  const paramsStr = _initSign.slice(1, _initSign.length) + AppSecret
+  let str = ''
+  if (raw) {
+    str += decodeURIComponent(raw)
+  }
+  if (body && Object.keys(body).length) {
+    str += decodeURIComponent(JSON.stringify(body))
+  }
+  // console.log('str:', str, 'paramsStr:', paramsStr)
+  return {
+    ...initSign,
+    sign: sha256(str + paramsStr)
   }
-  // 固定的参数初始化成字符串
-  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;
-  //   }, {});
 }

+ 11 - 3
utils/request.js

@@ -115,9 +115,6 @@ http.interceptors.request.use(
 				});
 		}
 
-    // 开启参数加密
-    if (config.custom?.openEncryption) encryptionFun(config)
-
     // 增加 token 令牌、terminal 终端、tenant 租户的请求头
 		const token = getAccessToken();
 		if (token) {
@@ -138,6 +135,17 @@ http.interceptors.request.use(
         config.url = config.url + '?' + paramsStr
       }
     }
+		
+		// 开启参数加密
+		if (config.custom?.openEncryption) {
+			const raw = config.url.split('?')[1]
+			const body = {
+				...config.data,
+				...config.params
+			}
+			const header = encryptionFun({raw, body, appId: 'web_client', AppSecret: 'fa0fc0b5098b974b'})
+			Object.assign(config.header, header)
+		}
 
 		if (uni.getStorageSync('token')) {
       // 截取request url