Эх сурвалжийг харах

feat: 微信公众号h5授权

John-Hong 2 жил өмнө
parent
commit
237f128f89

+ 2 - 1
public/index.html

@@ -44,7 +44,8 @@
 
 </html>
 <script>
-  const debug = window.localStorage.getItem('H5_DEBUG');
+  // const debug = window.localStorage.getItem('H5_DEBUG');
+  const debug = true;
   if (debug) {
     const script = document.createElement('script');
     script.src = 'https://unpkg.com/vconsole@latest/dist/vconsole.min.js';

+ 27 - 24
src/App.vue

@@ -17,7 +17,7 @@ import CacheTool from '@/utils/cache-tool';
 import uni from '@/utils/uniHooks';
 import { mapState } from 'vuex';
 import { initWxJsSdkConfig } from '@/utils/login.js';
-import { getUrlParams } from '@/utils/index.js';
+import { getUrlParams, getPlatform } from '@/utils/index.js';
 // import qs from 'qs';
 export default {
   data() {
@@ -52,17 +52,26 @@ export default {
   },
   methods: {
     async init() {
-      console.log(55555555);
+      // 初始化环境变量
+      CacheTool.init()
       if (this.isInit) return
       this.isInit = false;
-      initWxJsSdkConfig(['chooseWXPay']);
-      // initWxJsSdkConfig(['chooseImage', 'uploadImage']);
-      // return
-      // 当前页面是否是
-      // const token = uni.getStorageSync('kipAccessToken')
-      // const query = getUrlParams()
-      // console.log(!isMini() && !token, 35)
-      /* if (!isMini() && !token) {
+      // 当前页面是否是在微信公众号运行:start
+      const kipAccessToken = uni.getStorageSync('kipAccessToken')
+      const query = getUrlParams()
+      const platform = getPlatform()
+      if (platform === 'micromessenger' && !kipAccessToken) {
+        // 如果用户没有登录的话,我们需要让用户完成授权拿到 openid
+        const openid = uni.getStorageSync('openid')
+        if (!openid) {
+          // 前往授权页面
+          this.$router.replace({
+            path: '/openWx',
+            query: query
+          })
+          return
+        }
+        initWxJsSdkConfig(['chooseWXPay']);
         this.$store.commit('SET_GROUP_ID', query.groupId);
         this.$store.commit('SET_MALL_ID', query.mallid);
         // 如果用户不选择登录,则不走登录逻辑
@@ -75,29 +84,22 @@ export default {
         }
         this.isInit = true
         return
-      } */
+      }
       // 如果用已经登录
-      /* if(token) {
-        console.log(878787);
+      if(platform === 'micromessenger' && kipAccessToken) {
         this.$router.replace({
           path: '',
           query: query
         })  
         this.isInit = true
         return
-      } */
-      // 初始化环境变量
-      CacheTool.init()
-      if (window.location.href.search(/pageId=|token=/g) < 0) {
+      }
+      // 当前页面是否是在微信公众号运行:end
+      if (!query?.pageId?.length || !query?.token?.length) {
         return;
       }
-      console.log(77777777777, this.$route.query);
-      // window.token = window.location.href.replace(
-      //   /.*token=([0-9A-Za-z]*).*/g,
-      //   '$1'
-      // );
-      window.token = this.$route.query.token
-      console.log(55);
+    
+      window.token = query?.token
       // this.getTicket()
       this.wss(() => {
         this.$store.dispatch('baseInit', {
@@ -142,6 +144,7 @@ export default {
           callback && callback();
           window.subscribe('projectId', (options) => {
             self.$store.commit('SET_PROJECT_ID', options.projectId);
+            self.$store.commit('SET_ACCESS_TOKEN', options.accessToken);
           });
         });
       } catch (err) {

+ 58 - 0
src/pages/login/openWx.vue

@@ -0,0 +1,58 @@
+<template>
+  <div>
+    <!-- 微信页面授权回调:用户首次进入时判断当前用户所在环境:微信公众号和微信小程序 -->
+    微信页面授权回调:用户首次进入时判断当前用户所在环境:微信公众号和微信小程序
+  </div>
+</template>
+<script>
+import { getUrlParams } from '@/utils/index';
+import { WxJsOpenId } from '@/utils/login';
+
+export default {
+  created() {
+    console.log(12121212);
+    this.getCode();
+  },
+  mounted(){
+    console.log(17171717171717);
+  },
+  methods: {
+    getCode() {
+      const code = getUrlParams()?.code; // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
+      console.log(17);
+      const local = window.location.href;
+      if (code == null || code === '') {
+        console.log(120);
+        window.location.href =
+          'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
+          //   window.APPID +
+          `wx907c27f16841a919` +
+          '&redirect_uri=' +
+          encodeURIComponent(local) +
+          '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
+      } else {
+        this.getOpenId(code); //把code传给后台获取用户信息
+      }
+    },
+    async getOpenId(code) {
+      // 通过code获取 openId等用户信息,/api/user/wechat/login 为后台接口
+      let _this = this;
+      const res = await WxJsOpenId({
+        code,
+      });
+      console.log(res);
+      //   this.$http
+      //     .post('/api/user/wechat/login', { code: code })
+      //     .then((res) => {
+      //       let datas = res.data;
+      //       if (datas.code === 0) {
+      //         console.log('成功');
+      //       }
+      //     })
+      //     .catch((error) => {
+      //       console.log(error);
+      //     });
+    },
+  },
+};
+</script>

+ 29 - 40
src/pages/parkingFee/vehicleManagement.vue

@@ -49,7 +49,7 @@
         <div class="desc">·用户可以更改或删除已经绑定车牌</div>
       </div>
     </div>
-    <uni-popup ref="deleteDialog" type="center">
+    <van-popup v-model="deleteDialogSwitch"  position="center">
       <div class="popup-dialog">
         <div class="dialog-title">
           <span class="dialog-title-text">删除已绑定车牌</span>
@@ -67,8 +67,8 @@
           </div>
         </div>
       </div>
-    </uni-popup>
-    <uni-popup ref="deleteSuccessDialog" type="center">
+    </van-popup>
+    <van-popup v-model="deleteSuccessDialogSwitch"  position="center" >
       <div class="popup-dialog">
         <div class="dialog-content">
           <uni-icons type="checkbox-filled" size="60" color="#7DB124"></uni-icons>
@@ -80,7 +80,7 @@
           </div>
         </div>
       </div>
-    </uni-popup>
+    </van-popup>
   </scroll-view>
 </template>
 
@@ -111,6 +111,9 @@ export default {
       custTypeId: (state) => state.custTypeId,
       member: (state) => state.member,
       groupId: (state) => state.groupId,
+      openid: (state) => state.openid,
+      mallid: (state) => state.mallId,
+      mobile: (state) => state.mobile,
     }),
   },
   data() {
@@ -122,26 +125,11 @@ export default {
       isBeijing: false,
       options: null,
       preUrl: '',
+      deleteDialogSwitch: false,
+      deleteSuccessDialogSwitch: false,
     }
   },
-  // 分享好友
-  onShareAppMessage: function (res) {
-    return {
-      title: '车牌管理', // 分享标题
-      // desc: this.params.shareDescribe, // 分享描述
-      imageUrl: '', // 分享图标
-      path: `/pages/parkingFee/vehicleManagement?mallid=${this.mallid}`,
-    }
-  },
-  // 分享朋友圈
-  onShareTimeline: function (res) {
-    return {
-      title: '车牌管理', // 分享标题
-      // desc: this.params.shareDescribe, // 分享描述
-      imageUrl: '', // 分享图标
-      path: `/pages/parkingFee/vehicleManagement?mallid=${app.globalData.mallid}`,
-    }
-  },
+
   async created() {
     const option = this.$route.query;
     this.options = option
@@ -217,13 +205,13 @@ export default {
       uni.showLoading({
         title: '加载中',
       })
-      const openId = MemberCacheTool.getOpenId(app)
+      // const openId = MemberCacheTool.getOpenId(app)
       const params = {
         carno,
         mallid: this.mallid,
-        openid: openId,
+        openid: this.openid,
         vipcode: this.member?.vipcode,
-        mobile: this.member?.mobile,
+        mobile: this.mobile,
         groupId: this.groupId,
         createuser: 'sys_miniprogram',
       }
@@ -236,6 +224,7 @@ export default {
         timeout: 10000,
       })
         .then((res) => {
+          console.log(227, res);
           uni.hideLoading()
           if (res.data.code === 0) {
             this.$router.push({
@@ -291,7 +280,7 @@ export default {
     toDelete(item) {
       this.activeId = item.id
       this.activeCarno = item.vehicleNo
-      this.$refs.deleteDialog.open()
+      this.deleteDialogSwitch = true
     },
     doDelete() {
       uni.showLoading({
@@ -299,18 +288,19 @@ export default {
       })
       const _this = this
       kipDeleteMemberVehicles(this.activeId)
-        .then((resp) => {
+        .then((result) => {
           uni.hideLoading()
-          console.log(resp)
-          const result = resp.data
+          // console.log(resp)
+          // const result = resp.data
           if (result && result.code == '000000') {
             this.sensorsClick('$ClickDeleteLicensePlate', {
               carno_old: this.activeCarno,
               redirect_url: '',
             })
             if (result.data) {
-              _this.$refs.deleteDialog.close()
-              _this.$refs.deleteSuccessDialog.open()
+              this.deleteDialogSwitch = false
+              this.deleteSuccessDialogSwitch = true;
+              // _this.$refs.deleteSuccessDialog.open()
               return
             }
           }
@@ -355,10 +345,12 @@ export default {
       this.$sensors.track(eventName, finalParams)
     },
     cancelDelete() {
-      this.$refs.deleteDialog.close()
+      this.deleteDialogSwitch = true
     },
     confirmDialog() {
-      this.$refs.deleteSuccessDialog.close()
+      // this.$refs.deleteSuccessDialog.close()
+      this.deleteSuccessDialogSwitch = false;
+
       this.getKipMemberVehicles()
     },
     // 获取会员绑定的车牌列表
@@ -367,10 +359,10 @@ export default {
         title: '加载中',
       })
       kipGetMemberVehicles()
-        .then((resp) => {
+        .then((result) => {
           uni.hideLoading()
-          console.log(resp)
-          const result = resp.data
+          console.log(result)
+          // const result = resp.data
           if (result && result.code == '000000') {
             const data = result.data || []
             if (data && data.length > 0) {
@@ -646,15 +638,12 @@ export default {
 }
 
 .popup-dialog {
-  width: 300px;
+  // width: 300px;
   border-radius: 10px;
   background-color: #fff;
 }
 
 .dialog-title {
-  /* #ifndef APP-NVUE */
-  display: flex;
-  /* #endif */
   flex-direction: row;
   justify-content: center;
   padding-top: 10px;

+ 5 - 0
src/routes/index.js

@@ -85,6 +85,11 @@ const routes = [
     path: '/login',
     component: () => import('@/pages/login/login'),
   },
+  // 微信授权回调
+  {
+    path: '/openWx',
+    component: () => import('@/pages/login/openWx'),
+  },
   // { path: '/bar', component: 'Bar' }
 ];
 

+ 10 - 2
src/store/index.js

@@ -27,7 +27,8 @@ const store = new Vuex.Store({
     parkFee: {},
     marketList: [],
     projectId: '',
-    passLogin: false
+    passLogin: false,
+    accessToken: '' // 用户的token
   },
   mutations: {
     SET_GROUP_ID(state, payload) {
@@ -75,6 +76,11 @@ const store = new Vuex.Store({
       state.passLogin = payload;
       uni.setStorageSync('passLogin', payload);
     },
+    SET_ACCESS_TOKEN(state, payload) {
+      state.accessToken = payload;
+      // uni.setStorageSync('accessToken', payload);
+      uni.setStorageSync('kipAccessToken', payload);
+    }
   },
   actions: {
     async baseInit({ commit, dispatch }, { pageId, callback }) {
@@ -89,7 +95,9 @@ const store = new Vuex.Store({
         if (!pageId) return;
         let [groupId, kipUserId, mallId, openid, mobile] =
           Decrypt(pageId).split('#');
-          console.log(8181, groupId, kipUserId, mallId, openid, mobile);
+          console.log(8181, {
+            groupId, kipUserId, mallId, openid, mobile
+          });
 
         // groupId = '8a84853b7c91ac5b017c962dab55030e'
         // kipUserId = '8a84810483bc013e0183d44773bf002a'

+ 15 - 0
src/utils/index.js

@@ -42,6 +42,7 @@ export function getQueryParam() {
   return query;
 }
 
+// 
 export function isInWeixinH5() {
   // TODO: 发布前取消注释
   return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
@@ -49,6 +50,20 @@ export function isInWeixinH5() {
 }
 
 
+// 判断当前运行平台
+export function getPlatform() {
+  const userAgent = navigator.userAgent.toLowerCase()
+  // 微信小程序
+  if (/miniprogram/g.test(userAgent)) {
+    return "miniprogram"
+  }
+  // 微信公众号
+  if (/micromessenger/g.test(userAgent)) {
+    return "micromessenger"
+  }
+  // TODO: 发布前取消注释
+  return 'browser'
+}
 
 export function getUrlParams(url = window.location.href) {
 const str = `${url}`.split('?')[1]

+ 9 - 11
src/utils/uniHooks.js

@@ -43,7 +43,7 @@ function showToast({ title, duration, icon }) {
   // console.log('showToast');
   const params = {};
   if (title) {
-    params.title = title;
+    params.message = title;
   }
   if (duration) {
     params.duration = duration;
@@ -51,16 +51,14 @@ function showToast({ title, duration, icon }) {
   if (icon) {
     params.icon = icon;
   }
-  Toast({
-    message: params.title
-  })
-  if (window?.toWXSendMsg) {
-    window?.toWXSendMsg({
-      type: 'uni_func',
-      funcName: 'showToast',
-      options: params,
-    });
-  }
+  Toast(params)
+  // if (window?.toWXSendMsg) {
+  //   window?.toWXSendMsg({
+  //     type: 'uni_func',
+  //     funcName: 'showToast',
+  //     options: params,
+  //   });
+  // }
 }
 
 function setNavigationBarTitle({ title }) {