张涛 1 yıl önce
ebeveyn
işleme
821ab8f493
18 değiştirilmiş dosya ile 76294 ekleme ve 13091 silme
  1. 0
    2
      babel.config.js
  2. 2
    2
      config/dev.js
  3. 61
    49
      config/index.js
  4. 4
    4
      jsconfig.json
  5. 59473
    0
      package-lock.json
  6. 8
    7
      package.json
  7. 2
    2
      project.config.json
  8. 31
    19
      src/app.js
  9. 11
    3
      src/app.less
  10. 1
    0
      src/index.html
  11. 10
    10
      src/layouts/index.jsx
  12. 7
    0
      src/services/wxma.js
  13. 5
    1
      src/store/user.js
  14. 6
    2
      src/utils/log.js
  15. 73
    56
      src/utils/request.js
  16. 11
    5
      src/utils/token.js
  17. 121
    0
      src/utils/wx.js
  18. 16468
    12929
      yarn.lock

+ 0
- 2
babel.config.js Dosyayı Görüntüle

@@ -5,8 +5,6 @@ module.exports = {
5 5
     ['taro', {
6 6
       framework: 'react',
7 7
       ts: false,
8
-      // hot:false,
9
-      // 'dynamic-import-node': true,
10 8
     }]
11 9
   ],
12 10
   plugins: [

+ 2
- 2
config/dev.js Dosyayı Görüntüle

@@ -3,8 +3,8 @@ module.exports = {
3 3
     NODE_ENV: '"development"',
4 4
   },
5 5
   defineConstants: {
6
-    // HOST: '"http://127.0.0.1:9087"',
7
-    HOST: '"http://192.168.89.13:9087"',
6
+    HOST: '"http://127.0.0.1:9087"',
7
+    // HOST: '"http://192.168.89.13:9087"',
8 8
     // HOST: '"https://wmcj.huoshannews.com"',
9 9
     AD_IMAGE: '"https://h5.njyunzhi.com/images/citizen_banner.png"',
10 10
     DEFAULT_POS: '"116.3476917447715,31.409912844296578"', // 霍山县人民政府 gcj02

+ 61
- 49
config/index.js Dosyayı Görüntüle

@@ -4,6 +4,7 @@ const path = require("path");
4 4
 
5 5
 import devConfig from "./dev";
6 6
 import prodConfig from "./prod";
7
+const url = "http://127.0.0.1:9087";
7 8
 
8 9
 export default defineConfig(async (merge, { command, mode }) => {
9 10
   const config = {
@@ -14,6 +15,7 @@ export default defineConfig(async (merge, { command, mode }) => {
14 15
       640: 2.34 / 2,
15 16
       750: 1,
16 17
       828: 1.81 / 2,
18
+      375: 2 / 1,
17 19
     },
18 20
 
19 21
     sourceRoot: "src",
@@ -29,73 +31,83 @@ export default defineConfig(async (merge, { command, mode }) => {
29 31
     alias: {
30 32
       "@": path.resolve(__dirname, "..", "src"),
31 33
     },
32
-  
33
-    mini: {
34
-      postcss: {
35
-        pxtransform: {
36
-          enable: true,
37
-          config: {},
38
-        },
39
-        url: {
40
-          enable: true,
41
-          config: {
42
-            limit: 1024, // 设定转换尺寸上限
43
-          },
44
-        },
45
-        cssModules: {
46
-          enable: true, // 默认为 false,如需使用 css modules 功能,则设为 true
47
-          config: {
48
-            namingPattern: "module", // 转换模式,取值为 global/module
49
-            generateScopedName: "[name]__[local]___[hash:base64:5]",
50
-          },
51
-        },
52
-      },
53
-    },
34
+
35
+    // mini: {
36
+    //   postcss: {
37
+    //     pxtransform: {
38
+    //       enable: true,
39
+    //       config: {},
40
+    //     },
41
+    //     url: {
42
+    //       enable: true,
43
+    //       config: {
44
+    //         limit: 1024, // 设定转换尺寸上限
45
+    //       },
46
+    //     },
47
+    //     cssModules: {
48
+    //       enable: true, // 默认为 false,如需使用 css modules 功能,则设为 true
49
+    //       config: {
50
+    //         namingPattern: "module", // 转换模式,取值为 global/module
51
+    //         generateScopedName: "[name]__[local]___[hash:base64:5]",
52
+    //       },
53
+    //     },
54
+    //   },
55
+    // },
54 56
     h5: {
55 57
       publicPath: "/",
56 58
       staticDirectory: "static",
57
-      outputDir: 'dist',
58
-      router : {
59
-        mode : "hash",
60
-        // base : "./"
59
+      outputDir: "dist",
60
+      router: {
61
+        mode: "hash",
61 62
       },
62
-      // output: {
63
-      //   filename: "js/[name].[hash:8].js",
64
-      //   chunkFilename: "js/[name].[chunkhash:8].js",
65
-      // },
63
+      esnextModules: ["@antmjs/vantui"],
66 64
       miniCssExtractPluginOption: {
67 65
         ignoreOrder: true,
68 66
         filename: "css/[name].[hash].css",
69
-        chunkFilename: "css/[name].[chunkhash].css",
67
+        chunkFilename: "css/[id].css",
70 68
       },
69
+
71 70
       postcss: {
72
-        autoprefixer: {
71
+      
72
+     
73
+        pxtransform: {
73 74
           enable: true,
74
-          config: {},
75
+          config: {
76
+            // 设置rpx转换为目标单位为rem
77
+            unitToRem: true,
78
+            // 设计稿宽度与 rem 基准值,默认设计稿宽度为 750,即 1rem = 75px
79
+            designWidth: 750,
80
+            // 可选,选择器黑名单
81
+            selectorBlackList: [],
82
+            // // 可选,替换rpx为其他单位后缀,例如 'px' 或 'rem'
83
+            propList: ["*"],
84
+            // 可选,媒体查询中是否禁用转换
85
+            mediaQuery: false,
86
+            // 可选,是否转换页面根节点字体大小,如body: font-size: 16px
87
+            minPixelValue: 0,
88
+
89
+          },
75 90
         },
76 91
         cssModules: {
77
-          enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
92
+          enable: true, // 默认为 false,如需使用 css modules 功能,则设为 true
78 93
           config: {
79
-            namingPattern: "module", // 转换模式,取值为 global/module
94
+            namingPattern: "module", // 转换模式,取值为 global/module,下文详细说明
80 95
             generateScopedName: "[name]__[local]___[hash:base64:5]",
81 96
           },
82 97
         },
83 98
       },
84
-      // devServer: {
85
-      //   host: "0.0.0.0",
86
-      //   // port: ,
87
-      //   proxy: {
88
-      //     "/api": {
89
-      //       target: "http://127.0.0.1:9087", // 服务端地址
90
-      //       pathRewrite: {
91
-      //         '/api': ''
92
-      //       },
93
-      //       changeOrigin: true,
94
-      //     },
95
-      //   },
96
-      // },
99
+      devServer: {
100
+        proxy: {
101
+          "/api": {
102
+            target: url, // 服务端地址
103
+            pathRewrite: {
104
+              "^/api": "",
105
+            },
106
+            changeOrigin: true,
107
+          },
108
+        },
109
+      },
97 110
     },
98
- 
99 111
   };
100 112
   if (process.env.NODE_ENV === "development") {
101 113
     return merge({}, config, devConfig);

+ 4
- 4
jsconfig.json Dosyayı Görüntüle

@@ -4,10 +4,10 @@
4 4
     "paths": {
5 5
       "@/*": ["./src/*"]
6 6
     },
7
-    // 解决prettier对于装饰器语法的警告
8
-    "experimentalDecorators": true,
9
-    // 解决.jsx文件无法快速跳转的问题
10
-    "jsx": "preserve"
7
+    // // 解决prettier对于装饰器语法的警告
8
+    // "experimentalDecorators": true,
9
+    // // 解决.jsx文件无法快速跳转的问题
10
+    // "jsx": "preserve"
11 11
   },
12 12
   //提高  性能
13 13
   "exclude": ["node_modules", "dist", "build"]

+ 59473
- 0
package-lock.json
Dosya farkı çok büyük olduğundan ihmal edildi
Dosyayı Görüntüle


+ 8
- 7
package.json Dosyayı Görüntüle

@@ -41,12 +41,12 @@
41 41
     "@tarojs/helper": "3.6.25",
42 42
     "@tarojs/plugin-framework-react": "3.6.25",
43 43
     "@tarojs/plugin-platform-h5": "3.6.25",
44
-    "@tarojs/plugin-platform-weapp": "3.6.25",
45 44
     "@tarojs/plugin-platform-harmony-hybrid": "3.6.25",
46
-    "@tarojs/shared": "3.6.25",
45
+    "@tarojs/plugin-platform-weapp": "3.6.25",
47 46
     "@tarojs/react": "3.6.25",
48 47
     "@tarojs/router": "3.5.7",
49 48
     "@tarojs/runtime": "3.6.25",
49
+    "@tarojs/shared": "3.6.25",
50 50
     "@tarojs/taro": "3.6.25",
51 51
     "@zjxpcyc/js_event": "^1.0.0",
52 52
     "@zjxpcyc/react-tiny-store": "^2.0.1",
@@ -62,11 +62,12 @@
62 62
   "devDependencies": {
63 63
     "@babel/core": "^7.8.0",
64 64
     "@pmmmwh/react-refresh-webpack-plugin": "^0.5.5",
65
-    "react-refresh": "^0.11.0",
66 65
     "@tarojs/cli": "3.6.25",
67
-    "@tarojs/test-utils-react": "^0.1.1",
68 66
     "@tarojs/mini-runner": "3.6.25",
67
+    "@tarojs/test-utils-react": "^0.1.1",
69 68
     "@tarojs/webpack-runner": "3.6.25",
69
+    "@types/jest": "^29.3.1",
70
+    "@types/node": "^18.15.11",
70 71
     "@types/react": "^18.0.0",
71 72
     "@types/webpack-env": "^1.13.6",
72 73
     "babel-plugin-import": "^1.13.5",
@@ -76,12 +77,12 @@
76 77
     "eslint-plugin-import": "^2.12.0",
77 78
     "eslint-plugin-react": "^7.8.2",
78 79
     "eslint-plugin-react-hooks": "^4.2.0",
79
-    "@types/node": "^18.15.11",
80
-    "@types/jest": "^29.3.1",
81 80
     "jest": "^29.3.1",
82 81
     "jest-environment-jsdom": "^29.5.0",
83
-    "stylelint": "^14.4.0",
84 82
     "postcss": "^8.4.18",
83
+    "postcss-pxtorem": "^6.1.0",
84
+    "react-refresh": "^0.11.0",
85
+    "stylelint": "^14.4.0",
85 86
     "webpack": "4.46.0"
86 87
   }
87 88
 }

+ 2
- 2
project.config.json Dosyayı Görüntüle

@@ -1,8 +1,8 @@
1 1
 {
2 2
     "miniprogramRoot": "dist/",
3 3
     "projectname": "civilized-miniapp",
4
-    "description": "文明城市小程序",
5
-    "appid": "wx39d721c54a0a11c4",
4
+    "description": "云致公众号",
5
+    "appid": "wxd3bab568bc42d1de",
6 6
     "setting": {
7 7
         "urlCheck": true,
8 8
         "es6": false,

+ 31
- 19
src/app.js Dosyayı Görüntüle

@@ -1,25 +1,37 @@
1
-import Taro from '@tarojs/taro';
2
-import store, { Provider } from '@/store';
3
-import './app.less'
1
+import Taro from "@tarojs/taro";
2
+import store, { Provider, getState } from "@/store";
3
+import "./app.less";
4
+import { useEffect, useMemo } from "react";
5
+// import wxsdk from "./utils/wx";
4 6
 
5 7
 const App = (props) => {
8
+  // useEffect(async() => {
9
+  //   const userState = store.getState("user");
6 10
 
7
-  Taro.useLaunch(() => {
8
-    Taro.login({
9
-      success: (res) => {
10
-        console.log(res)
11
-        store.getState('user').login(res.code);
12
-      }
13
-    });
11
+  //   // 等待组件挂载完成
12
+  //   await Promise.resolve();
14 13
 
15
-    store.getState('user').current();
16
-  });
14
+  //   // 然后执行异步操作
15
+  //   await userState.login(123);
16
+  //   userState.current();
17
+  // }, []);
18
+  const init = async () => {
19
+    console.log(11111111111)
20
+    const userState = store.getState("user");
21
+    // 等待组件挂载完成
22
+    await Promise.resolve();
17 23
 
18
-  return (
19
-    <Provider>
20
-      {props.children}
21
-    </Provider>
22
-  );
23
-}
24
+    // 然后执行异步操作
25
+    await userState.login(123);
26
+    await userState.current();
27
+  };
28
+ 
24 29
 
25
-export default App
30
+  useEffect(() => {
31
+    init()
32
+  }, []);
33
+
34
+  return <Provider>{props.children}</Provider>;
35
+};
36
+
37
+export default App;

+ 11
- 3
src/app.less Dosyayı Görüntüle

@@ -1,11 +1,11 @@
1 1
 /* stylelint-disable CssSyntaxError */
2
-
3
-page {
2
+:root {
4 3
   height: 100%;
5 4
   box-sizing: border-box;
6 5
   background: #f8f8f8;
7 6
   --main-bg-color: #1A7565;
8 7
   --main-space: 4vw;
8
+  // --main-space: 20px; /* 基准字体大小,您可以根据实际情况调整 */
9 9
 
10 10
   // antm-js 样式修改
11 11
   // 按钮
@@ -35,4 +35,12 @@ page {
35 35
 
36 36
 view {
37 37
   box-sizing: border-box;
38
-}
38
+}
39
+
40
+
41
+
42
+// @media (min-width: 750px) {
43
+//   page {
44
+//     font-size: calc(100vw / 7.5); /* 基于设计稿宽度750px计算的自适应字体大小 */
45
+//   }
46
+// }

+ 1
- 0
src/index.html Dosyayı Görüntüle

@@ -8,6 +8,7 @@
8 8
   <meta name="format-detection" content="telephone=no,address=no">
9 9
   <meta name="apple-mobile-web-app-status-bar-style" content="white">
10 10
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" >
11
+  <script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
11 12
   <title>civilized-miniapp</title>
12 13
   <script><%= htmlWebpackPlugin.options.script %></script>
13 14
 </head>

+ 10
- 10
src/layouts/index.jsx Dosyayı Görüntüle

@@ -14,16 +14,16 @@ export default (props) => {
14 14
   const { person, user, duty } = useModel('user');
15 15
   const containerClass = `${laySty['page-conatiner']} ${tabBar ? laySty['with-tabbar'] : ''} ${className}`;
16 16
 
17
-  React.useEffect(() => {
18
-    if (person && !user) {
19
-      const currentPage = Taro.getCurrentPages().slice().pop();
20
-      if ('pages/login/index' !== currentPage.route) {
21
-        Taro.navigateTo({
22
-          url: '/pages/login/index',
23
-        })
24
-      }
25
-    }
26
-  }, [person, user]);
17
+  // React.useEffect(() => {
18
+  //   if (person && !user) {
19
+  //     const currentPage = Taro.getCurrentPages().slice().pop();
20
+  //     if ('pages/login/index' !== currentPage.route) {
21
+  //       Taro.navigateTo({
22
+  //         url: '/pages/login/index',
23
+  //       })
24
+  //     }
25
+  //   }
26
+  // }, [person, user]);
27 27
 
28 28
   Taro.useShareAppMessage(() => {
29 29
     return {

+ 7
- 0
src/services/wxma.js Dosyayı Görüntüle

@@ -15,6 +15,13 @@ export const authUser = (data) => request(`/api/ma/auth-user`, { data, method: '
15 15
  */
16 16
 export const login = (code) => request(`/api/ma/login?code=${code}`, { method: 'post', silent: true });
17 17
 
18
+/**
19
+ * 
20
+ * @param {*} data 
21
+ * @returns 
22
+ */
23
+login
24
+
18 25
 /*
19 26
  * 小程序登录
20 27
  */

+ 5
- 1
src/store/user.js Dosyayı Görüntüle

@@ -17,11 +17,13 @@ export default function useUser() {
17 17
   const [duty, setDuty] = React.useState();
18 18
 
19 19
   const maLogin = (code) => {
20
-    console.log(code);
20
+    console.log(code)
21 21
     login(code).then((res) => {
22 22
       setPerson(res.person);
23 23
       Taro.setStorage({ key: "personId", data: res.person.personId });
24 24
       Taro.setStorage({ key: "sessionKey", data: res.sessionKey });
25
+    }).catch(e => {
26
+      console.log(e)
25 27
     });
26 28
   };
27 29
 
@@ -62,6 +64,8 @@ export default function useUser() {
62 64
     currentUser().then((res) => {
63 65
       setUser(res.user);
64 66
       initDuty(res.user);
67
+    }).catch(e => {
68
+      console.log(e)
65 69
     });
66 70
   };
67 71
 

+ 6
- 2
src/utils/log.js Dosyayı Görüntüle

@@ -1,5 +1,9 @@
1
-import Taro from '@tarojs/taro';
1
+import Taro from "@tarojs/taro";
2
+import { H5 } from "./token";
2 3
 
3
-const logger = Taro.getRealtimeLogManager()
4
+let logger;
5
+if (!H5) {
6
+  logger = Taro.getRealtimeLogManager();
7
+}
4 8
 
5 9
 export default logger;

+ 73
- 56
src/utils/request.js Dosyayı Görüntüle

@@ -1,36 +1,50 @@
1
-import Taro from '@tarojs/taro';
2
-import { getToken, setToken } from './token';
3
-import logger from './log';
1
+import Taro from "@tarojs/taro";
2
+import { H5, TARO_ENV, getToken, setToken } from "./token";
4 3
 
5
-const getQueryStrByParams = params => {
4
+import logger from "./log";
5
+
6
+const getQueryStrByParams = (params) => {
6 7
   if (!params) return undefined;
7 8
 
8
-  return Object.keys(params).map(key => {
9
-    const value = params[key];
10
-    return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
11
-  }).join('&')
12
-}
9
+  return Object.keys(params)
10
+    .map((key) => {
11
+      const value = params[key];
12
+      return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
13
+    })
14
+    .join("&");
15
+};
13 16
 
14 17
 export default function request(api, options = {}) {
15 18
   return new Promise((resolve, reject) => {
16
-    const { method = 'GET', params, data = {}, header = {}, silent = false, noSuccesTip, ...cfgs } = options;
19
+    const {
20
+      method = "GET",
21
+      params,
22
+      data = {},
23
+      header = {},
24
+      silent = false,
25
+      noSuccesTip,
26
+      ...cfgs
27
+    } = options;
17 28
     const queryStr = params ? getQueryStrByParams(params) : undefined;
18 29
     // eslint-disable-next-line no-undef
19 30
     const url = queryStr ? `${HOST}${api}?${queryStr}` : `${HOST}${api}`;
20
-    const personId = Taro.getStorageSync('personId');
21
-    const duty = Taro.getStorageSync('duty');
22
-    
31
+    const personId = Taro.getStorageSync("personId");
32
+    const duty = Taro.getStorageSync("duty");
33
+
23 34
     const onError = (err) => {
24 35
       console.error(err);
25
-      logger.error(`接口 [${method}]: ${url}`);
26
-      logger.error('参数: ', data);
27
-      logger.error(err);
36
+      if (!H5) {
37
+        console.log(1)
38
+        logger.error(`接口 [${method}]: ${url}`);
39
+        logger.error("参数: ", data);
40
+        logger.error(err);
41
+      }
28 42
 
29
-      if (!silent && 'GET' !== method.toUpperCase()) {
43
+      if (!silent && "GET" !== method.toUpperCase()) {
30 44
         Taro.showModal({
31 45
           title: err.message || err,
32 46
           showCancel: false,
33
-        })
47
+        });
34 48
       }
35 49
 
36 50
       reject(err);
@@ -40,47 +54,50 @@ export default function request(api, options = {}) {
40 54
       url,
41 55
       data,
42 56
       method,
57
+      // mode: "no-cors",
43 58
       header: {
44
-        'x-client': 'miniapp',
45
-        'x-personId': personId,
46
-        'x-duty': duty,
47
-        'content-type': 'application/json',
48
-        'authorization': getToken(),
59
+        "x-client": "miniapp",
60
+        "x-personId": personId,
61
+        "x-duty": duty,
62
+        "content-type": "application/json",
63
+        authorization: getToken(),
49 64
         ...header,
50 65
       },
51 66
       ...cfgs,
52
-    }).then(({ statusCode, header, data = result }) => {
53
-      if (statusCode >= 300) {
54
-        logger.error(header);
55
-        return onError(`网络错误 ${statusCode}`);
56
-      }
57
-
58
-      if (data.code === 1000) {
59
-        if (data.data?.token) {
60
-          setToken(data.data.token);
67
+    })
68
+      .then(({ statusCode, header, data = result }) => {
69
+        if (statusCode >= 300) {
70
+          if (!H5) {
71
+            logger.error(header);
72
+          }
73
+          return onError(`网络错误 ${statusCode}`);
61 74
         }
62 75
 
63
-        if (!silent && 'GET' !== method.toUpperCase()) {
64
-          if (!noSuccesTip) {
65
-            Taro.showToast({
66
-              title: '操作成功',
67
-              icon: 'none',
68
-            })
76
+        if (data?.code === 1000) {
77
+          if (data.data?.token) {
78
+            setToken(data?.data?.token);
69 79
           }
70
-        }
71 80
 
72
-        resolve(data.data);
73
-      } else {
74
-        onError(data);
75
-      }
76
-    }).catch(onError);
81
+          if (!silent && "GET" !== method.toUpperCase()) {
82
+            if (!noSuccesTip) {
83
+              Taro.showToast({
84
+                title: "操作成功",
85
+                icon: "none",
86
+              });
87
+            }
88
+          }
77 89
 
90
+          resolve(data.data);
91
+        } else {
92
+          onError(data);
93
+        }
94
+      })
95
+      .catch(onError);
78 96
   });
79 97
 }
80 98
 
81
-
82 99
 export const uploadFiles = async (files, url) => {
83
-  const uploads = []
100
+  const uploads = [];
84 101
   const token = getToken();
85 102
   for (var i = 0; i < files.length; i++) {
86 103
     uploads[i] = new Promise((resolve, reject) => {
@@ -89,27 +106,27 @@ export const uploadFiles = async (files, url) => {
89 106
         url: url || `${HOST}/api/ma/file`,
90 107
         filePath: files[i].tempFilePath,
91 108
         header: {
92
-          'authorization': token,
109
+          authorization: token,
93 110
         },
94
-        name: 'file',
111
+        name: "file",
95 112
         formData: {
96 113
           fileType: files[i].fileType,
97 114
         },
98 115
         success: function (res) {
99 116
           // debugger
100
-          const _data = JSON.parse(res.data)
117
+          const _data = JSON.parse(res.data);
101 118
           // if (_data.code !== CODE_SUCCESS) {
102 119
           //   reject(new Error(_data.message))
103 120
           // }
104 121
 
105
-          resolve(_data.data)
122
+          resolve(_data.data);
106 123
         },
107 124
         fail(err) {
108
-          reject(err)
109
-        }
110
-      })
111
-    })
125
+          reject(err);
126
+        },
127
+      });
128
+    });
112 129
   }
113 130
 
114
-  return Promise.all(uploads)
115
-}
131
+  return Promise.all(uploads);
132
+};

+ 11
- 5
src/utils/token.js Dosyayı Görüntüle

@@ -1,9 +1,15 @@
1
-import Taro from '@tarojs/taro';
1
+import Taro from "@tarojs/taro";
2 2
 
3 3
 export const getToken = function () {
4
-  return Taro.getStorageSync('token');
5
-}
4
+  return Taro.getStorageSync("token");
5
+};
6 6
 
7 7
 export const setToken = function (data) {
8
-  return Taro.setStorage({ key: 'token', data })
9
-}
8
+  return Taro.setStorage({ key: "token", data });
9
+};
10
+
11
+export const TARO_ENV = process.env.TARO_ENV; //那个端的
12
+
13
+export const H5 = TARO_ENV == "h5";
14
+
15
+export const Weapp = TARO_ENV == "weapp";

+ 121
- 0
src/utils/wx.js Dosyayı Görüntüle

@@ -0,0 +1,121 @@
1
+let APPID = '';
2
+const isDev = false
3
+
4
+const API_BASE="http://127.0.0.1:9087"
5
+
6
+
7
+/**
8
+ * 获取 code
9
+ * @returns 
10
+ */
11
+export function getCode () {
12
+    if (isDev) return '123';
13
+  
14
+    const matched = /[?&]*code=([^&]+)/.exec(location.search)
15
+    if (matched) {
16
+      return decodeURIComponent(matched[1])
17
+    }
18
+  }
19
+  
20
+  /**
21
+   * 跳转授权页面
22
+   */
23
+  export function redirect () {
24
+    if (isDev) return;
25
+  
26
+    const appid = APPID || 'wxd3bab568bc42d1de';
27
+    const local = encodeURIComponent(location.origin + location.pathname)
28
+    const scope = 'snsapi_userinfo'; // snsapi_base
29
+    const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=${scope}&state=123#wechat_redirect`
30
+    window.location.href = url;
31
+  }
32
+  function wxsdk() {
33
+    // API_BASE 来源 public/config.js
34
+    const apiBase = API_BASE // import.meta.env.VITE_APP_API_BASE
35
+  
36
+    // 分享接口
37
+    const shareAPIs = [
38
+      // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容(1.4.0)
39
+      'updateAppMessageShareData',
40
+      // 自定义“分享到朋友圈”及“分享到 QQ 空间”按钮的分享内容(1.4.0)
41
+      'updateTimelineShareData',
42
+      // 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口(即将废弃)
43
+      'onMenuShareTimeline',
44
+      // 获取“分享给朋友”按钮点击状态及自定义分享内容接口(即将废弃)
45
+      'onMenuShareAppMessage',
46
+      // 获取“分享到QQ”按钮点击状态及自定义分享内容接口(即将废弃)
47
+      'onMenuShareQQ',
48
+      // 获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
49
+      'onMenuShareWeibo',
50
+      // 获取“分享到 QQ 空间”按钮点击状态及自定义分享内容接口(即将废弃)
51
+      'onMenuShareQZone',
52
+    ]
53
+  
54
+    let inited = false;
55
+  
56
+    function init() {
57
+      if (isDev) return;
58
+      const url = window.location.href;
59
+  
60
+      // 请求后台接口
61
+      fetch(`${apiBase}/api/wx/jsapi?url=${encodeURIComponent(url)}`).then(res => res.json()).then((res) => {
62
+        if (res.code === 1000) {
63
+          const data = res.data;
64
+  
65
+          APPID = data.appId;
66
+  
67
+          wx.config({
68
+            debug: isDev, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来,若要查看传入的参数,可以在 pc 端打开,参数信息会通过 log 打出,仅在 pc 端时才会打印。
69
+            appId: data.appId, // 必填,公众号的唯一标识
70
+            timestamp: data.timestamp, // 必填,生成签名的时间戳
71
+            nonceStr: data.nonceStr, // 必填,生成签名的随机串
72
+            signature: data.signature,// 必填,签名
73
+            jsApiList: [
74
+              ...shareAPIs,
75
+              'openLocation',
76
+            ] // 必填,需要使用的 JS 接口列表
77
+          });
78
+        }
79
+      })
80
+    }
81
+  
82
+    function share(params = {}) {
83
+      if (isDev) return;
84
+  
85
+      if (!inited) {
86
+        init();
87
+      }
88
+  
89
+      wx.ready(() => {
90
+  
91
+        const shareData = {
92
+          ...shareOptTpl,
93
+          ...params
94
+        }
95
+  
96
+        console.log('---分享参数-->', shareData);
97
+  
98
+        for (let api of shareAPIs) {
99
+          wx[api]({
100
+            ...shareData,
101
+            success: () => {
102
+              console.log('分享成功: ', api)
103
+            },
104
+          });
105
+        }
106
+      });
107
+  
108
+      wx.error(function(res){
109
+        console.error('wx js-sdk error');
110
+        console.error(res);
111
+        console.error('<==============');
112
+      });
113
+    }
114
+  
115
+    return {
116
+      share,
117
+      getCode,
118
+      redirect,
119
+    }
120
+  }
121
+  export default wxsdk;

+ 16468
- 12929
yarn.lock
Dosya farkı çok büyük olduğundan ihmal edildi
Dosyayı Görüntüle