瀏覽代碼

替换无效编码序列(解决 decodeURIComponent 报错 "URI malformed" 的问题)

lifanagju_citu 3 周之前
父節點
當前提交
fd01bb0b68
共有 1 個文件被更改,包括 13 次插入2 次删除
  1. 13 2
      src/utils/openEncryption.js

+ 13 - 2
src/utils/openEncryption.js

@@ -19,6 +19,17 @@ import { sha256 } from 'js-sha256'
  * @param { Object } body
  * @returns 
 */
+
+// 替换无效编码序列(解决 decodeURIComponent 报错 "URI malformed" 的问题)
+export const decodeURIComponentSafe = (str) => {
+  try {
+    return decodeURIComponent(str);
+  } catch (e) {
+    // 替换无效的百分号编码为空字符串
+    return decodeURIComponent(str.replace(/%(?![\da-f]{2})/gi, ''));
+  }
+}
+
 export const encryptionFun = ({raw, body, appId, AppSecret, timestamp}) => {
   const initSign = {
     appId,
@@ -33,10 +44,10 @@ export const encryptionFun = ({raw, body, appId, AppSecret, timestamp}) => {
   const paramsStr = _initSign + AppSecret
   let str = ''
   if (raw) {
-    str += decodeURIComponent(raw)
+    str += decodeURIComponentSafe(raw)
   }
   if (body && Object.keys(body).length) {
-    str += decodeURIComponent(JSON.stringify(body))
+    str += decodeURIComponentSafe(JSON.stringify(body))
   }
   return {
     ...initSign,