Bladeren bron

公众号调用js-sdk修改

plg 10 maanden geleden
bovenliggende
commit
33e1f6534f

+ 13 - 1
package-lock.json

@@ -24,10 +24,12 @@
         "@dcloudio/uni-quickapp-webview": "3.0.0-alpha-4010720240511003",
         "@dcloudio/uni-ui": "^1.5.5",
         "crypto-js": "^4.2.0",
+        "jweixin-module": "^1.6.0",
         "pinia": "2.0.27",
         "pinia-plugin-persistedstate": "^3.2.0",
         "vue": "^3.4.27",
-        "vue-i18n": "^9.2.2"
+        "vue-i18n": "^9.2.2",
+        "weixin-js-sdk": "^1.6.5"
       },
       "devDependencies": {
         "@dcloudio/types": "^3.4.8",
@@ -11308,6 +11310,11 @@
         "graceful-fs": "^4.1.6"
       }
     },
+    "node_modules/jweixin-module": {
+      "version": "1.6.0",
+      "resolved": "https://registry.npmmirror.com/jweixin-module/-/jweixin-module-1.6.0.tgz",
+      "integrity": "sha512-dGk9cf+ipipHmtzYmKZs5B2toX+p4hLyllGLF6xuC8t+B05oYxd8fYoaRz0T30U2n3RUv8a4iwvjhA+OcYz52w=="
+    },
     "node_modules/keyv": {
       "version": "4.5.4",
       "resolved": "https://registry.npmmirror.com/keyv/-/keyv-4.5.4.tgz",
@@ -15187,6 +15194,11 @@
       "resolved": "https://registry.npmmirror.com/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz",
       "integrity": "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="
     },
+    "node_modules/weixin-js-sdk": {
+      "version": "1.6.5",
+      "resolved": "https://registry.npmmirror.com/weixin-js-sdk/-/weixin-js-sdk-1.6.5.tgz",
+      "integrity": "sha512-Gph1WAWB2YN/lMOFB/ymb+hbU/wYazzJgu6PMMktCy9cSCeW5wA6Zwt0dpahJbJ+RJEwtTv2x9iIu0U4enuVSQ=="
+    },
     "node_modules/whatwg-encoding": {
       "version": "1.0.5",
       "resolved": "https://registry.npmmirror.com/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz",

+ 3 - 1
package.json

@@ -65,10 +65,12 @@
     "@dcloudio/uni-quickapp-webview": "3.0.0-alpha-4010720240511003",
     "@dcloudio/uni-ui": "^1.5.5",
     "crypto-js": "^4.2.0",
+    "jweixin-module": "^1.6.0",
     "pinia": "2.0.27",
     "pinia-plugin-persistedstate": "^3.2.0",
     "vue": "^3.4.27",
-    "vue-i18n": "^9.2.2"
+    "vue-i18n": "^9.2.2",
+    "weixin-js-sdk": "^1.6.5"
   },
   "devDependencies": {
     "@dcloudio/types": "^3.4.8",

+ 93 - 52
src/App.vue

@@ -1,10 +1,49 @@
 <script setup lang="ts">
 import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
-
+import { useMemberStore } from "@/stores";
+import { appId } from "@/utils/http";
 // onLaunch((options) => {
 //   console.log(decodeURIComponent(options?.query.scene));
 //   console.log("App Launch");
 // });
+const userInfo = useMemberStore();
+// userInfo.userInfo.openId;
+onLaunch(() => {
+  userInfo.userInfo.openId;
+  //进入到页面的时候查看解析页面路径查看页面路径中是含有code
+  //如果含有code 则根据code 获取openid
+  //如果没有 则访问微信路径,然后重定向到我们的页面
+  //然后根据返回的信息有没有手机号,如果没有则调用手机号登录界面
+  //接下来调试---调用扫描接口看看sdk可以用吗
+});
+//判断是否有opend的接口
+const judgeOpenId = (openId: string) => {
+  if (!openId) {
+    //假如不存在的话
+    //则跳转到获取code的接口
+  }
+};
+//判断code是否存在
+const judgeCode = () => {
+  let localUrl = encodeURIComponent(window.location.href);
+  let code = getCode();
+};
+
+//获取code
+const getCode = () => {
+  let code = "";
+  let url = window.location.search;
+  if (url.indexOf("?") !== -1) {
+    var strings = url.substring(1).split("&");
+    for (var i in strings) {
+      if (strings[i].indexOf("code") === 0) {
+        code = strings[i].split("=")[1];
+      }
+    }
+  }
+  return code;
+};
+
 onShow(() => {
   console.log("App Show");
   //调用  版本更新
@@ -12,56 +51,56 @@ onShow(() => {
 onHide(() => {
   console.log("App Hide");
 });
-const autoUpdate = () => {
-  if (uni.canIUse("getUpdateManager")) {
-    const updateManager = uni.getUpdateManager();
-    updateManager.onCheckForUpdate(function (res) {
-      if (res.hasUpdate) {
-        updateManager.onUpdateReady(function () {
-          uni.showModal({
-            title: "更新提示",
-            content: "新版本已经准备好,是否重启应用?",
-            showCancel: false,
-            success: function (res) {
-              if (res.confirm) {
-                updateManager.applyUpdate();
-              } else if (res.cancel) {
-                uni.showModal({
-                  title: "温馨提示~",
-                  content: "本次版本更新涉及到新的功能添加,旧版本无法正常访问的哦~",
-                  success: function (res) {
-                    // autoUpdate();
-                    // return;
-                    //第二次提示后,强制更新
-                    if (res.confirm) {
-                      // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
-                      updateManager.applyUpdate();
-                    } else if (res.cancel) {
-                      //重新回到版本更新提示
-                      autoUpdate();
-                    }
-                  },
-                });
-              }
-            },
-          });
-          updateManager.onUpdateFailed(function () {
-            // 新的版本下载失败
-            uni.showModal({
-              title: "已经有新版本了哟~",
-              content: "新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~",
-            });
-          });
-        });
-      }
-    });
-  } else {
-    uni.showModal({
-      title: "提示",
-      content: "当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。",
-    });
-  }
-};
+// const autoUpdate = () => {
+//   if (uni.canIUse("getUpdateManager")) {
+//     const updateManager = uni.getUpdateManager();
+//     updateManager.onCheckForUpdate(function (res) {
+//       if (res.hasUpdate) {
+//         updateManager.onUpdateReady(function () {
+//           uni.showModal({
+//             title: "更新提示",
+//             content: "新版本已经准备好,是否重启应用?",
+//             showCancel: false,
+//             success: function (res) {
+//               if (res.confirm) {
+//                 updateManager.applyUpdate();
+//               } else if (res.cancel) {
+//                 uni.showModal({
+//                   title: "温馨提示~",
+//                   content: "本次版本更新涉及到新的功能添加,旧版本无法正常访问的哦~",
+//                   success: function (res) {
+//                     // autoUpdate();
+//                     // return;
+//                     //第二次提示后,强制更新
+//                     if (res.confirm) {
+//                       // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
+//                       updateManager.applyUpdate();
+//                     } else if (res.cancel) {
+//                       //重新回到版本更新提示
+//                       autoUpdate();
+//                     }
+//                   },
+//                 });
+//               }
+//             },
+//           });
+//           updateManager.onUpdateFailed(function () {
+//             // 新的版本下载失败
+//             uni.showModal({
+//               title: "已经有新版本了哟~",
+//               content: "新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~",
+//             });
+//           });
+//         });
+//       }
+//     });
+//   } else {
+//     uni.showModal({
+//       title: "提示",
+//       content: "当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。",
+//     });
+//   }
+// };
 </script>
 
 <style lang="scss">
@@ -74,7 +113,9 @@ input,
 scroll-view {
   box-sizing: border-box;
 }
-
+uni-page-head {
+  display: none;
+}
 button::after {
   border: none;
 }

+ 1 - 1
src/hooks/useIsLogin.ts

@@ -22,7 +22,7 @@ export const login = () => {
         resolve(re)
       },
       fail: (error) => {
-        reject(error)
+        // reject(error)
       },
     })
   })

+ 6 - 2
src/pages.json

@@ -14,8 +14,11 @@
 
       "path": "pages/index/index",
       "style": {
-        "navigationBarTitleText": "首页",
-        "navigationStyle": "custom"
+        "navigationBarTitleText": "税务风险检测",
+        "navigationStyle": "custom",
+        "app-plus":{
+          "titleNView": false
+        }
       }
 
     },
@@ -81,6 +84,7 @@
     }
   ],
   "globalStyle": {
+    "navigationStyle": "custom",
     "navigationBarTextStyle": "black",
     "navigationBarTitleText": "",
     "navigationBarBackgroundColor": "#F8F8F8",

+ 1 - 1
src/pages/index/components/HomeTabs.vue

@@ -14,7 +14,7 @@ const inviteUserFun = () => {
 };
 </script>
 <template>
-  <view class="home_top"> 税务风险检测 </view>
+  <!-- <view class="home_top"> 税务风险检测 </view> -->
   <view class="home_tabs">
     <view class="user_use" @click="inviteUserFun">邀请用户使用</view>
     <view class="risk_detection">税务风险检测</view>

+ 17 - 1
src/pages/index/index.vue

@@ -3,11 +3,19 @@ import HomeTabs from "./components/HomeTabs.vue";
 import HomeList from "./components/HomeList.vue";
 import { ref, reactive, onMounted } from "vue";
 import { login } from "@/hooks/useIsLogin";
-import { onShow } from "@dcloudio/uni-app";
+import { onLaunch, onShow } from "@dcloudio/uni-app";
+import { chooseImageApi } from "@/utils/js_sdk_utils";
 const companyName = ref<string>("");
 
 const phoneGet = ref<any>();
 
+onLaunch(() => {
+  //进入到页面的时候查看解析页面路径查看页面路径中是含有code
+  //如果含有code 则根据code 获取openid
+  //如果没有 则访问微信路径,然后重定向到我们的页面
+  //然后根据返回的信息有没有手机号,如果没有则调用手机号登录界面
+  //接下来调试---调用扫描接口看看sdk可以用吗
+});
 onMounted(() => {
   //我来了
 });
@@ -15,6 +23,13 @@ onShow(() => {
   console.log("onshow");
   login();
 });
+//点击进行扫码
+const scanFun = async () => {
+  const res = await chooseImageApi();
+  console.log("-------------1------------");
+  console.log(res);
+  //点击进行扫码
+};
 //调用子组件
 const phoneGetFun = () => {
   phoneGet.value.open();
@@ -29,6 +44,7 @@ const validFun = () => {
 <template>
   <!-- 引入头部安全区域组件 -->
   <view class="home_padding">
+    <button @click="scanFun">获取图片</button>
     <ShuiWuTop />
     <HomeTabs @jumpInvite="validFun" />
     <view class="list_search">

+ 20 - 0
src/services/gzh_home.ts

@@ -0,0 +1,20 @@
+import type { SignatureTP } from '@/types/gzh_home'
+import { http } from '@/utils/http'
+
+// const getSignatureUrl = '/api/wx'
+const getSignatureUrl = '/mp/api/signature2'
+// export const getSignatureApi = (val: SignatureTP) => {
+//   return http<any>({
+//     method: 'GET',
+//     url: `${getSignatureUrl}?url=${val.url}`,
+//     // data: { ...val },
+//   })
+// }
+export const getSignatureApi = (val: SignatureTP) => {
+  return http<any>({
+    method: 'GET',
+    url: `${getSignatureUrl}?url=${val.url}`,
+    // url: `${getSignatureUrl}`,
+    // data: { ...val },
+  })
+}

+ 3 - 0
src/types/gzh_home.d.ts

@@ -0,0 +1,3 @@
+export type SignatureTP = {
+  url: string
+}

+ 15 - 3
src/utils/http.ts

@@ -6,10 +6,16 @@ import { userLoginApi } from '@/services/home'
 
 // const baseUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
 // const baseUrl = 'https://test.jue-ming.com:8084'
-const baseUrl = 'http://10.113.248.3:8086'
+// const baseUrl = 'http://10.113.248.3:8086'
+
+// const baseUrl = 'http://g9yv4d.natappfree.cc'
+//服务器
+// const baseUrl = 'http://i9p32r.natappfree.cc'
+const baseUrl = 'http://n823va.natappfree.cc'
 export const imgUrl = 'http://10.113.248.3:8086/file/show?filePath='
+export const appId = 'wx658b72887c56f6b4'
 // export const imgUrl = 'https://test.jue-ming.com:8084/file/show?filePath='
-export const mediaUrl = 'https://test.jue-ming.com:8084/file/show/media?filePath='
+// export const mediaUrl = 'https://test.jue-ming.com:8084/file/show/media?filePath='
 // const baseUrl = 'http://10.113.248.3:8080'
 // export const imgUrl = 'http://10.113.248.3:8080/file/show?filePath='
 
@@ -31,7 +37,8 @@ const httpInterceptor = {
     //判断如果请求体里有data//且data不为空
     if ('data' in options) {
       //如果包含data属性
-      options.data = { data: Encrypt(JSON.stringify(options.data)) }
+      // options.data = { data: Encrypt(JSON.stringify(options.data)) }
+      options.data = { data: options.data }
     }
     console.log(options)
     //添加 token 请求头标识
@@ -73,6 +80,11 @@ export const http = <T>(option: UniApp.RequestOptions) => {
           // eslint-disable-next-line no-debugger
 
           resolve(JSON.parse(Decrypt(res.data)))
+          // const a: any = res.data
+          // resolve(a)
+
+          // debugger
+          // resolve(a)
 
           // resolve(res.data as Data<T>)
         } else if (res.statusCode === 401) {

+ 98 - 0
src/utils/js_sdk_utils.ts

@@ -0,0 +1,98 @@
+// const wxjssdk = require('jweixin-module')
+import { getSignatureApi } from '@/services/gzh_home'
+import wxjssdk from 'weixin-js-sdk'
+import { appId } from '@/utils/http'
+//调用 返回的接口
+
+//获取签名--添加微信配置
+export const wxconfig = async () => {
+  // const currenturl = encodeURIComponent(location.href.split('#')[0])
+  const currenturl = location.href.split('#')[0]
+  alert(currenturl)
+  const response = await getSignatureApi({ url: currenturl })
+  //将值装进微信的配置
+  wxjssdk.config({
+    debug: true,
+    appId: appId,
+    timestamp: response.data.timestamp,
+    nonceStr: response.data.nonceStr,
+    signature: response.data.signature,
+    jsApiList: [
+      // 'checkJsApi', //判断当前客户端版本是否支持指定JS接口
+      'chooseImage',
+      // 'updateAppMessageShareData', //分享接口
+      // // 'chooseImageApi', //扫一扫接口
+      // 'chooseWXPay', //微信支付
+    ],
+  })
+}
+
+// 选择图片方法
+export const chooseImageApi = () => {
+  return new Promise((resolve, reject) => {
+    wxconfig()
+    wxjssdk.ready(() => {
+      console.log('微信验证')
+      wxjssdk.chooseImage({
+        count: 1, // 默认9
+        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
+        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
+        success: function (res) {
+          console.log(res)
+          resolve(res)
+          // var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
+        },
+        cancel: function (): void {
+          console.log('用户取消了')
+          // throw new Error('Function not implemented.')
+          // throw new Error('Function not implemented.')
+        },
+      })
+    }),
+      wxjssdk.error((res) => {
+        console.log('config fail:', res)
+        //config fail,抛出失败原因
+        console.log('-------------失败------------')
+        reject(res)
+      })
+  })
+}
+//分享方法
+const shareAppApi = () => {
+  return new Promise((resolve, reject) => {
+    //注意----需在用户可能点击分享按钮前就先调用
+    wxjssdk.ready(() => {
+      //需在用户可能点击分享按钮前就先调用
+      wxjssdk.updateAppMessageShareData({
+        title: '', // 分享标题
+        desc: '', // 分享描述
+        link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
+        imgUrl: '', // 分享图标
+        success: function () {
+          resolve('分享成功')
+          // 设置成功
+        },
+      })
+    })
+  })
+}
+// wxjssdk.checkJsApi({
+//   jsApiList: ['chooseImage'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
+//   success: function (res) {
+//     // 以键值对的形式返回,可用的api值true,不可用为false
+//     // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
+//   },
+// })
+
+//
+
+// wxjssdk.ready(function () {
+//   //微信config正确性验证通过了
+//   console.log('微信验证通过了')
+//   // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
+// })
+
+wxjssdk.error(function (res) {
+  console.log('微信验证没有通过了')
+  // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
+})

+ 39 - 2
vite.config.ts

@@ -7,7 +7,10 @@ export default defineConfig({
     // 开发阶段启用源码映射:https://uniapp.dcloud.net.cn/tutorial/migration-to-vue3.html#需主动开启-sourcemap
     sourcemap: process.env.NODE_ENV === 'development',
   },
-  plugins: [uni(), { // 自定义插件禁用vite:vue插件的devToolsEnabled,强制编译 vue 模板时 inline 为 true
+  plugins: [
+    uni(),
+    {
+      // 自定义插件禁用vite:vue插件的devToolsEnabled,强制编译 vue 模板时 inline 为 true
       name: 'fix-vite-plugin-vue',
       configResolved(config) {
         const plugin = config.plugins.find((p) => p.name === 'vite:vue')
@@ -15,5 +18,39 @@ export default defineConfig({
           plugin.api.options.devToolsEnabled = false
         }
       },
-    }],
+    },
+  ],
+  server: {
+    // host: 'c3j6u3.natappfree.cc',
+    host: '0.0.0.0',
+    port: 80,
+    // https: false,
+
+    //设置法反向代理跨域
+    // proxy: {
+    //   '/api': {
+    //     //后台地址
+    //     target: '',
+    //     changeOrigin: true,
+    //     rewrite: (path) => path.replace(/^\/api1/, ''),
+    //   },
+    // },
+    proxy: {
+      '/api': {
+        // target: 'http://i9p32r.natappfree.cc',
+        target: 'http://n823va.natappfree.cc',
+        changeOrigin: true,
+        rewrite: (path) => path.replace(/^\/api/, ''),
+      },
+    },
+    // proxy: {
+    //   '/api': {
+    //     target: 'http://localhost:90',
+    //     changeOrigin: true,
+    //     pathRewrite: {
+    //       '^/api': '',
+    //     },
+    //   },
+    // },
+  },
 })