Kaynağa Gözat

获取微信openid

pengjing 10 ay önce
ebeveyn
işleme
300b2dbf02

+ 2 - 2
h5app/public/appconfig.json

@@ -1,5 +1,5 @@
 {
   "isDev": true,
-  "webSiteUrl": "http://www.bowintek.com:8022/mobile/index.html/#",
-  "webApiServiceUrl": "/api/"
+  "webSiteUrl": "http://www.bowintek.com/hzyz/mobile/index.html/#",
+  "webApiServiceUrl": "http://www.bowintek.com/hzyz/api"
 }

+ 42 - 29
h5app/src/App.vue

@@ -1,4 +1,4 @@
-<template >
+<template>
   <ion-app style="z-index: 1">
     <ion-router-outlet/>
   </ion-app>
@@ -8,19 +8,31 @@
 import {IonApp, IonRouterOutlet} from '@ionic/vue';
 import {getCurrentInstance, ref} from "vue";
 import {useUserStore} from "@/store/modules/user";
-import {wxAuth} from "@/utils/wechat";
+import {useRouter} from "vue-router";
 
 const {appContext: {config: {globalProperties}}} = getCurrentInstance();
 
 const userStore = useUserStore();
 
+const router = useRouter();
+
 const user = ref(userStore.getUserInfo);
 
 if (user.value != null) {
   globalProperties.$routeActive = true;
-}
-else{
-  wxAuth();
+} else {
+  let redirectUrl = "/login";
+
+  const url = location.href;
+
+  if (url.indexOf("#") != -1) {
+    const index = url.indexOf("#");
+    const splits = [url.slice(0, index), url.slice(index + 1)];
+
+    redirectUrl = splits[1];
+  }
+
+  router.push("/index?redirectUrl=" + redirectUrl)
 }
 
 </script>
@@ -54,7 +66,7 @@ ion-content {
   }
 }
 
-.header-theme2::after{
+.header-theme2::after {
   background-image: none !important;
 }
 
@@ -275,102 +287,103 @@ ion-grid {
   width: 70%;
 }
 
-.bw-vue-form{
-  .form-title{
+.bw-vue-form {
+  .form-title {
     padding: 10px;
     font-size: 18px;
     font-weight: bold;
   }
 
-  .form-input{
+  .form-input {
     padding: 10px;
 
-    ion-input{
+    ion-input {
       border-bottom: 1px solid #f1f5f7;
       color: #8c8f93;
       --padding-start: 0px;
     }
   }
 
-  .form-select{
+  .form-select {
     padding: 10px;
 
-    ion-select{
+    ion-select {
       border-bottom: 1px solid #f1f5f7;
       color: #8c8f93;
       --padding-start: 0px;
     }
 
-    ion-select::part(icon){
+    ion-select::part(icon) {
       display: none;
     }
 
-    ion-select::after{
+    ion-select::after {
       content: "选择";
       color: #02a6f1;
     }
 
-    ion-item{
-      ion-select{
+    ion-item {
+      ion-select {
         border-bottom: 1px solid #f1f5f7;
         color: #8c8f93;
         --padding-start: 0px;
       }
 
-      ion-select::part(icon){
+      ion-select::part(icon) {
         display: none;
       }
 
-      ion-select::after{
+      ion-select::after {
         content: "选择";
         color: #02a6f1;
       }
     }
   }
 
-  .form-detail{
+  .form-detail {
     padding: 10px;
     display: flex;
     justify-content: space-between;
     vertical-align: middle;
     color: #8c8f93;
 
-    ion-label{
+    ion-label {
       min-width: 80px;
       padding: 0 5px 0 0;
     }
   }
 }
 
-.bw-vue-list{
-  .list-title{
+.bw-vue-list {
+  .list-title {
     padding: 10px;
     font-size: 18px;
     font-weight: bold;
   }
 
-  .list-content{
+  .list-content {
 
-    ion-item{
+    ion-item {
       --inner-border-width: 0;
-      --inner-padding-end:0px;
+      --inner-padding-end: 0px;
       margin: 0 10px;
       border-bottom: 1px solid #f1f5f7;
       border-radius: 0px;
 
-      ion-label{
-        .multi-title{
+      ion-label {
+        .multi-title {
           display: flex;
           justify-content: space-between;
         }
-        p{
+
+        p {
           font-size: 12px;
           color: #8c8f93;
         }
       }
     }
 
-    ion-item::part(native){
+    ion-item::part(native) {
       padding: 0px;
     }
   }

+ 2 - 2
h5app/src/api/wechat/index.ts

@@ -1,11 +1,11 @@
 import {request} from "@/utils/request";
 
-export function getOAuthUrl() {
+export function getOAuthUrl(redirectUrl:string) {
     return request<object>(
         {
             url: 'wx/getOAuthUrl',
             method: 'get',
-            params: {},
+            params: {redirectUrl:redirectUrl},
         },
         {
             isNew: true,

+ 6 - 1
h5app/src/router/index.ts

@@ -8,11 +8,12 @@ import DemoPage from '../views/pages/demo/edit.vue';
 import JobUserInfoIndex from '../views/pages/jobUserInfo/index.vue';
 import JobUserInfoUserEdit from '../views/pages/jobUserInfo/userEdit.vue';
 import JobUserInfoCompanyEdit from '../views/pages/jobUserInfo/companyEdit.vue';
+import IndexPage from '../views/index.vue';
 
 const routes: Array<RouteRecordRaw> = [
     {
         path: '/',
-        redirect: '/login'
+        redirect: '/index'
     },
     {
         path: '/tabs/',
@@ -176,6 +177,10 @@ const routes: Array<RouteRecordRaw> = [
             }
         ]
     },
+    {
+        path: '/index',
+        component: IndexPage
+    },
     {
         path: '/login',
         component: LoginPage

+ 1 - 1
h5app/src/utils/config.ts

@@ -12,7 +12,7 @@ export interface ConfigParams  {
 export const getConfig = async <ConfigParams>(
 ): Promise<ConfigParams> => {
     try {
-        const res = await service.request({url: '../mobile/appconfig.json'});
+        const res = await service.request({url: '../hzyz/mobile/appconfig.json'});
 
         return res.data as ConfigParams;
     } catch (error: any) {

+ 10 - 9
h5app/src/utils/request.ts

@@ -38,15 +38,6 @@ const UNKNOWN_ERROR = '未知错误,请重试';
 // const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
 /** 真实请求的路径前缀 */
 let baseApiUrl = '/api/';
-try {
-    getConfig().then((data: any) => {
-        baseApiUrl = data.webApiServiceUrl || '/api/';
-    }, () => {
-        baseApiUrl = '/api/';
-    })
-} catch (e: any) {
-    baseApiUrl = '/api/';
-}
 /** mock请求路径前缀 */
 const baseMockUrl = '/';
 
@@ -132,6 +123,16 @@ export const request = async <T = any>(
     options: RequestOptions = {},
 ): Promise<T> => {
     try {
+        try {
+            await getConfig().then((data: any) => {
+                baseApiUrl = (data.webApiServiceUrl || '/api') + '/';
+            }, () => {
+                baseApiUrl = '/api/';
+            })
+        } catch (e: any) {
+            baseApiUrl = '/api/';
+        }
+
         const {successMsg, errorMsg, permCode, isMock, isGetDataDirectly = true, isShowSuccessMsg = true} = options;
         // 如果当前是需要鉴权的接口 并且没有权限的话 则终止请求发起 , isNew
         if (permCode && !useUserStore().perms.includes(permCode)) {

+ 42 - 34
h5app/src/utils/urlUtils.ts

@@ -9,18 +9,18 @@
  *  ==>www.baidu.com?a=3&b=4
  */
 export function setObjToUrlParams(baseUrl: string, obj: any): string {
-  let parameters = '';
-  let url = '';
-  for (const key in obj) {
-    parameters += `${key}=${encodeURIComponent(obj[key])}&`;
-  }
-  parameters = parameters.replace(/&$/, '');
-  if (/\?$/.test(baseUrl)) {
-    url = baseUrl + parameters;
-  } else {
-    url = baseUrl.replace(/\/?$/, '?') + parameters;
-  }
-  return url;
+    let parameters = '';
+    let url = '';
+    for (const key in obj) {
+        parameters += `${key}=${encodeURIComponent(obj[key])}&`;
+    }
+    parameters = parameters.replace(/&$/, '');
+    if (/\?$/.test(baseUrl)) {
+        url = baseUrl + parameters;
+    } else {
+        url = baseUrl.replace(/\/?$/, '?') + parameters;
+    }
+    return url;
 }
 
 /**
@@ -33,27 +33,35 @@ export const uniqueSlash = (path: string) => path.replace(/(https?:\/)|(\/)+/g,
 // export const uniqueSlash = (path: string) => path.replace(/(?<!:)\/{2,}/g, '/');
 
 
-export function getUrlParams(){
-  let url = location.href;
-  const theRequest = new Object();
-  if (url.indexOf("#/login") != -1) {
-    url = url.split("#/login")[0];
-  }
-  if (url.indexOf("?") != -1) {
-    const index = url.indexOf("?");
-    const splits = [url.slice(0,index),url.slice(index+1)];
-    const paramsUrl = splits[1];
-    const strs = paramsUrl.split("&");
-    for (let i = 0; i < strs.length; i++) {
-      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
-      // @ts-ignore
-      const paramsIndex = strs[i].indexOf("=");
-      const paramsSplits = [strs[i].slice(0,paramsIndex),strs[i].slice(paramsIndex+1)];
-
-      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
-      // @ts-ignore
-      theRequest[paramsSplits[0]] = paramsSplits[1];
+export function getUrlParams() {
+    const href = location.href;
+    const theRequest = new Object();
+    let urls = [];
+    if (href.indexOf("#") != -1) {
+        const index = href.indexOf("#");
+        urls = [href.slice(0, index), href.slice(index + 1)];
+    } else {
+        urls = [href];
     }
-  }
-  return theRequest;
+
+    urls.forEach(url => {
+        if (url.indexOf("?") != -1) {
+            const index = url.indexOf("?");
+            const splits = [url.slice(0, index), url.slice(index + 1)];
+            const paramsUrl = splits[1];
+            const strs = paramsUrl.split("&");
+            for (let i = 0; i < strs.length; i++) {
+                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+                // @ts-ignore
+                const paramsIndex = strs[i].indexOf("=");
+                const paramsSplits = [strs[i].slice(0, paramsIndex), strs[i].slice(paramsIndex + 1)];
+
+                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+                // @ts-ignore
+                theRequest[paramsSplits[0]] = paramsSplits[1];
+            }
+        }
+    });
+
+    return theRequest;
 }

+ 28 - 19
h5app/src/utils/wechat.ts

@@ -2,37 +2,46 @@ import {getUrlParams} from "@/utils/urlUtils";
 import {getOAuthUrl, getWxOpenId} from "@/api/wechat";
 import {useUserStore} from "@/store/modules/user";
 import {alertController, loadingController} from '@ionic/vue';
+import {getConfig} from "@/utils/config";
 
 export function isWechat() {
     return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
-    /*return true;*/
 }
 
-export async function wxAuth() {
-    const userStore = useUserStore();
-    if (isWechat() && !userStore.getOpenId) {
-        const urlParams = getUrlParams() as any;
-        const code = urlParams["code"];
-        if (!code) {
+export const wxAuth = async <Object>(redirectUrl: string): Promise<string> => {
+    try {
+        const userStore = useUserStore();
+
+        if (isWechat() && !userStore.getOpenId) {
+            await getConfig().then((data: any) => {
+                redirectUrl = data.webSiteUrl + redirectUrl;
+            })
+            const urlParams = getUrlParams() as any;
+            const code = urlParams["code"];
             const loading = await loadingController.create({
                 cssClass: 'my-custom-class',
                 message: '微信授权中,请稍后...',
                 duration: 2000,
             });
             await loading.present();
-
-            getOAuthUrl().then((res: any) => {
-                if (res) {
-                    window.location.href = res;
-                } else {
-                    presentAlert("微信授权失败!");
-                }
-            });
-        } else {
-            getWxOpenId(code).then((res: any) => {
-                userStore.setOpenId(res);
-            });
+            if (!code) {
+                getOAuthUrl(encodeURIComponent(redirectUrl)).then((res: any) => {
+                    if (res) {
+                        window.location.href = res;
+                    } else {
+                        presentAlert("微信授权失败!");
+                    }
+                });
+            } else {
+                await getWxOpenId(code).then((res: any) => {
+                    userStore.setOpenId(res);
+                });
+            }
         }
+        return "";
+    }
+    catch (e){
+        return Promise.reject(null);
     }
 }
 

+ 41 - 0
h5app/src/views/index.vue

@@ -0,0 +1,41 @@
+<template>
+  <div></div>
+</template>
+<script>
+import {defineComponent, ref} from "vue";
+import {useRouter} from "vue-router";
+import {useUserStore} from "@/store/modules/user";
+import {isWechat, wxAuth} from "@/utils/wechat";
+import {getUrlParams} from "@/utils/urlUtils";
+
+export default defineComponent({
+  name: "sysindex",
+  setup() {
+    const router = useRouter();
+    const userStore = useUserStore();
+    const user = ref(userStore.getUserInfo);
+    const urlParams = getUrlParams();
+    let redirectUrl = urlParams["redirectUrl"] || '/login';
+
+    if (redirectUrl === '/index') {
+      redirectUrl = '/login';
+    }
+
+    const wxLogin = async function () {
+      await wxAuth(redirectUrl);
+    };
+
+    if (isWechat()) {
+      wxLogin().then(res => {
+        router.push(redirectUrl);
+      });
+    } else {
+      router.push(redirectUrl);
+    }
+
+    return {}
+  }
+});
+</script>
+<style lang="less">
+</style>

+ 34 - 8
h5app/src/views/pages/jobUserInfo/index.vue

@@ -27,6 +27,10 @@
           <ion-label>所属驿站</ion-label>
           <ion-text>{{ user.siteName }}</ion-text>
         </div>
+        <div v-if="isDev" class="form-detail">
+          <ion-label>openId</ion-label>
+          <ion-text>{{ openId }}</ion-text>
+        </div>
       </div>
       <div class="page_button">
         <ion-button shape="round" expand="block" @click="onCompany">我是企业</ion-button>
@@ -38,11 +42,11 @@
 <script>
 import {defineComponent, ref} from "vue";
 import {getUrlParams} from "@/utils/urlUtils";
-import {alertController} from "@ionic/vue";
+import {alertController, onIonViewDidEnter} from "@ionic/vue";
 import {getUserByID} from "@/api/siteUserInfo";
 import {useRouter} from "vue-router";
-import {getWxOpenId} from "@/api/wechat";
 import {useUserStore} from "@/store/modules/user";
+import {getConfig} from "@/utils/config";
 
 
 const presentAlert = async (message) => {
@@ -57,14 +61,19 @@ const presentAlert = async (message) => {
   await alert.present();
 }
 
+const openId = ref("");
+
 export default defineComponent({
   name: "jobUserInfoIndex",
   setup() {
+
     const router = useRouter();
     const user = ref({userNo: '', name: '', IDCard: '', siteName: ''});
     const urlParams = getUrlParams();
     const userId = urlParams["userId"];
+    const isDev = ref(false);
     const userStore = useUserStore();
+    openId.value = userStore.getOpenId;
 
     const getUser = async function () {
       const reqData = await getUserByID(userId);
@@ -72,11 +81,11 @@ export default defineComponent({
     };
 
     const onCompany = function () {
-      router.push({path: '/jobUserInfo/companyedit', query: {reload: 1, openId: userStore.getOpenId}});
+      router.push({path: '/jobUserInfo/companyedit', query: {reload: 1, openId: openId.value, siteUserId: userId}});
     };
 
     const onJobUser = function () {
-      router.push({path: '/jobUserInfo/useredit', query: {reload: 1, openId: userStore.getOpenId}});
+      router.push({path: '/jobUserInfo/useredit', query: {reload: 1, openId: openId.value, siteUserId: userId}});
     };
 
 
@@ -86,16 +95,32 @@ export default defineComponent({
       getUser();
     }
 
+    getConfig().then(res => {
+      isDev.value = res.isDev;
+    }, () => {
+      isDev.value = true;
+    })
+
+    onIonViewDidEnter(() => {
+      openId.value = userStore.getOpenId;
+    });
+
     return {
       user,
       onCompany,
-      onJobUser
+      onJobUser,
+      openId,
+      isDev
     }
+  },
+  mounted() {
+    const userStore = useUserStore();
+    openId.value = userStore.getOpenId;
   }
 });
 </script>
 <style lang="less">
-.bw-vue-form{
+.bw-vue-form {
   padding: 20px 10px;
 }
 
@@ -108,8 +133,9 @@ export default defineComponent({
     width: 150px;
   }
 }
-.header-theme3{
-  ion-title{
+
+.header-theme3 {
+  ion-title {
     margin-left: 0px !important;
   }
 }

+ 5 - 2
src/main/java/com/hz/employmentsite/controller/WxController.java

@@ -4,12 +4,15 @@ import com.hz.employmentsite.filter.exception.BaseResponse;
 import com.hz.employmentsite.filter.exception.RespGenerstor;
 import com.hz.employmentsite.services.service.WechatService;
 import me.chanjar.weixin.common.error.WxErrorException;
+import org.apache.tomcat.util.buf.UDecoder;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -35,8 +38,8 @@ public class WxController {
     private WechatService wechatService;
 
     @GetMapping("getOAuthUrl")
-    public BaseResponse<String> getOAuthUrl() {
-        return RespGenerstor.success(wechatService.getOAuthUrl(""));
+    public BaseResponse<String> getOAuthUrl(String redirectUrl) throws UnsupportedEncodingException {
+        return RespGenerstor.success(wechatService.getOAuthUrl(URLDecoder.decode(redirectUrl,"UTF-8")));
     }
 
 

+ 1 - 1
src/main/java/com/hz/employmentsite/filter/exception/GlobalExceptionHandler.java

@@ -25,7 +25,7 @@ public class GlobalExceptionHandler {
     @ExceptionHandler(value = Exception.class)
     public BaseResponse<Object> exceptionHandler(Exception e) {
         logger.error("未知异常!原因是:" + e);
-        return RespGenerstor.fail(BaseErrorEnum.INTERNAL_SERVER_ERROR,null);
+        return RespGenerstor.fail(BaseErrorEnum.INTERNAL_SERVER_ERROR,e.getMessage());
     }
 
 }

+ 2 - 2
src/main/java/com/hz/employmentsite/services/impl/WechatServiceImpl.java

@@ -33,8 +33,8 @@ public class WechatServiceImpl implements WechatService {
         logger = LoggerFactory.getLogger(this.getClass());
     }
 
-    public String getOAuthUrl(String state) {
-        return wxMpService.oauth2buildAuthorizationUrl(appConfig.wxRedirectURI, appConfig.wxAccessScope, state);
+    public String getOAuthUrl(String redirectUrl) {
+        return wxMpService.oauth2buildAuthorizationUrl(redirectUrl, appConfig.wxAccessScope, "");
     }
 
     @Override

+ 1 - 1
src/main/java/com/hz/employmentsite/services/service/WechatService.java

@@ -6,7 +6,7 @@ import java.util.Map;
 
 public interface WechatService {
 
-    String getOAuthUrl(String state);
+    String getOAuthUrl(String redirectUrl);
 
     Integer sentMsg(String toUserId, Map<String,String> sentData);
 

+ 2 - 2
src/main/resources/application.yml

@@ -118,8 +118,8 @@ appconfig:
     client_id: xxx
     client_secret: xxx
   wxconfig:
-    appId: 'wx74648e2f8589cc94'
-    appSecret: 'c177326e256261175288ef529e44a477'
+    appId: 'wx737c2a7879b897c1'
+    appSecret: '0d37c99bf2edd9ef3d839869bfa724ad'
     messageTemplateId: ''
     redirectURI: 'http://www.bowintek.com/hzyz/mobile'
     accessScope: 'snsapi_base'