Browse Source

企业微信接口

pengjing 7 months ago
parent
commit
9470ae5bad

+ 23 - 0
parth5/parth5/src/app/api/account/index.ts

@@ -0,0 +1,23 @@
+import {ConfigService, RequsetData} from "../../service/config.service";
+import {Injectable} from "@angular/core";
+import {Observable} from "rxjs";
+import {DESModel, DesService} from "../../service/des.service";
+
+@Injectable({providedIn: 'root'})
+export class AccountApi {
+  constructor(private configService: ConfigService,private desService: DesService) {
+  }
+
+  login(model: DESModel): Observable<RequsetData> {
+    return this.configService.HttpGetRomote('/appApi/home/login', model);
+  }
+
+  loginByWxUserId(wxUserId: string): Observable<RequsetData> {
+    let id = this.desService.GetToken(wxUserId);
+    return this.configService.HttpGetRomote('/appApi/home/loginByWxUserId', {
+      id
+    });
+  }
+
+}
+

+ 23 - 0
parth5/parth5/src/app/api/wechat/index.ts

@@ -0,0 +1,23 @@
+import {ConfigService, RequsetData} from "../../service/config.service";
+import {Injectable} from "@angular/core";
+import {Observable} from "rxjs";
+
+@Injectable({providedIn: 'root'})
+export class WechatApi {
+  constructor(private configService: ConfigService) {
+  }
+
+  getOAuthUrl(redirectUrl:string):Observable<RequsetData> {
+    return this.configService.HttpGetRomote('/wxapi/cp/getOAuthUrl', {
+      redirectUrl
+    });
+  }
+
+  getWxCpUserId(code:string):Observable<RequsetData> {
+    return this.configService.HttpGetRomote('/wxapi/cp/getWxCpUserId', {
+      code
+    });
+  }
+
+}
+

+ 2 - 1
parth5/parth5/src/app/app-routing.module.ts

@@ -3,7 +3,8 @@ import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
 
 const routes: Routes = [
   { path: 'tapp', loadChildren: () => import('./views/tapp/tabs/tabs.module').then(m => m.TabsPageModule)},
-  { path: '', loadChildren: () => import('./views/login/login.module').then(m => m.LoginPageModule) },
+  { path: 'login', loadChildren: () => import('./views/login/login.module').then(m => m.LoginPageModule) },
+  { path: '', loadChildren: () => import('./views/index/index.module').then(m => m.IndexPageModule) },
   {
     path: '**',
     redirectTo: ''

+ 2 - 11
parth5/parth5/src/app/app.component.ts

@@ -1,13 +1,4 @@
 import {Component} from '@angular/core';
-import {ActivatedRoute, Router} from "@angular/router";
-import {ConfigService} from "./service/config.service";
-import {UserService} from "./service/user.service";
-import {JsBridgeService} from "./service/js-bridge.service";
-import {DesService} from "./service/des.service";
-import {LoadingController} from "@ionic/angular";
-import {UsemodularService} from "./service/usemodular.service";
-import {WxpayService} from "./service/wxpay.service";
-
 
 @Component({
   selector: 'app-root',
@@ -15,10 +6,10 @@ import {WxpayService} from "./service/wxpay.service";
   styleUrls: ['app.component.scss'],
 })
 export class AppComponent {
-  constructor(private router: Router, private route: ActivatedRoute, private userService: UserService, private wxpayService: WxpayService) {
+  constructor() {
   }
 
   ngOnInit() {
-    this.wxpayService.getWechatCode();
+
   }
 }

+ 57 - 0
parth5/parth5/src/app/service/account.service.ts

@@ -0,0 +1,57 @@
+import {Injectable, Inject} from '@angular/core';
+import {DOCUMENT} from '@angular/common';
+import {ConfigService, RequsetData} from "./config.service";
+import {from, Observable} from "rxjs";
+import * as moment from "./work.service";
+import {Router} from "@angular/router";
+import {AlertController} from "@ionic/angular";
+import {AccountApi} from "../api/account";
+import {UsemodularService} from "./usemodular.service";
+import {AlertModal} from "../comm/modal/alert";
+import {UserService} from "./user.service";
+
+
+@Injectable({providedIn: 'root'})
+export class AccountService {
+
+  constructor(private router: Router, private userService: UserService,
+              private configService: ConfigService, private accountApi: AccountApi, private usemodularService: UsemodularService, private alertModal: AlertModal) {
+
+  }
+
+
+  /**
+   * 根据微信用户id登录系统,如果未绑定则跳转到登陆页面
+   * @param wxUserId 企业微信用户id
+   * @param currentUrl 登录成功后跳转路由,可未空,默认首页路由
+   */
+  async loginByWxUserId(wxUserId: string, currentUrl: string) {
+    if (!wxUserId)
+      return false;
+
+    const loading = await this.alertModal.loading('验证微信用户中,请稍等...');
+    await loading.present();
+
+    this.accountApi.loginByWxUserId(wxUserId).subscribe(req => {
+      loading.dismiss();
+      if (req.success) {
+        req.item.curRoleId = req.extdata.userRoles[0].roleid;
+        this.userService.SetUser(req.item);
+        this.userService.SetExt(req.extdata);
+        this.userService.setToken(req.item.logintoken);
+        this.userService.ReadUserDataScope(req.item.curRoleId, this.configService);
+        this.usemodularService.getButtonList();
+        this.router.navigate([currentUrl || '/tapp/tabs/tabMain']);
+      } else {
+        this.alertModal.alert('微信用户未绑定或验证失败,请输入账号密码登录');
+        this.router.navigate(['/login']);
+      }
+    }, () => {
+      loading.dismiss();
+      this.alertModal.alert('微信用户未绑定或验证失败,请输入账号密码登录');
+      this.router.navigate(['/login']);
+    });
+  };
+
+
+}

+ 9 - 0
parth5/parth5/src/app/service/user.service.ts

@@ -16,6 +16,7 @@ export class UserService {
   userDataScope: string = '/appApi/home/UserDataScope';
   tokenName = "logintoken";
   openIDName = "userOpenID";
+  wxUserIdName = "wxUserId";
 
   constructor(@Inject(DOCUMENT) private document: any, private router: Router, private  alertController: AlertController) {
     this.win = this.document.defaultView;
@@ -85,6 +86,14 @@ export class UserService {
     return this.lStorage[this.openIDName];
   }
 
+  setWxUserID(wxUserId: string) {
+    this.lStorage[this.wxUserIdName] = wxUserId;
+  }
+
+  getWxUserID() {
+    return this.lStorage[this.wxUserIdName];
+  }
+
   verifyToken() {
     let token = this.lStorage[this.tokenName];
     let url = location.href.split("#");

+ 75 - 0
parth5/parth5/src/app/service/wxcp.service.ts

@@ -0,0 +1,75 @@
+import {Inject, Injectable} from '@angular/core';
+import {ConfigService, RequsetData} from "./config.service";
+import {UserService} from "./user.service";
+import {from, interval, Observable, of, Subject} from "rxjs";
+import * as moment from 'moment';
+import {DOCUMENT} from "@angular/common";
+import {AlertController, LoadingController} from "@ionic/angular";
+import {ActivatedRoute, Router} from "@angular/router";
+import {AlertModal} from "../comm/modal/alert";
+import {WechatApi} from "../api/wechat";
+import {getUrlParams} from "../utils/urlUtils";
+
+@Injectable({
+  providedIn: 'root'
+})
+
+export class WxcpService {
+  private siteUrl: string = '';
+
+  constructor(@Inject(DOCUMENT) private document: any, private router: Router, private configService: ConfigService, private userService: UserService
+    , private alertModal: AlertModal, private wechatApi: WechatApi, private routeInfo: ActivatedRoute) {
+    this.configService.GetConfig().subscribe((config) => {
+      this.siteUrl = config.siteUrl;
+    });
+  }
+
+  isWechat = () => {
+    return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
+  }
+
+  wxAuth = async <Object>(routePath: string): Promise<string> => {
+    try {
+      const urlParams = getUrlParams() as any;
+      const openId = urlParams["wxUserId"] || this.userService.getWxUserID();
+      const code = urlParams["code"];
+
+      if (this.isWechat()) {
+        if (openId) {
+          this.userService.setWxUserID(openId);
+        } else {
+          if (!code) {
+            const loading = await this.alertModal.loading('微信授权中,请稍等...');
+            await loading.present();
+
+            let oAuthUrl_redirectUrl = this.siteUrl + "?routePath=" + encodeURIComponent(routePath); //www.aa.com/mobile?routePath=xxxxx
+            this.wechatApi.getOAuthUrl(encodeURIComponent(oAuthUrl_redirectUrl)).subscribe((res: any) => {
+              if (res) {
+                window.location.replace(res);
+              } else {
+                this.alertModal.alert("微信授权失败!");
+              }
+            });
+          } else {
+            const loading = await this.alertModal.loading('微信授权成功,请稍等...');
+            await loading.present();
+            await this.wechatApi.getWxCpUserId(code).subscribe((res: any) => {
+              this.userService.setWxUserID(res);
+
+              const currentUrl = routePath + (routePath.indexOf("?") >= 0 ? "&" : "?") + "wxUserId=" + res;
+
+              this.router.navigate([currentUrl], {
+                relativeTo: this.routeInfo,
+                queryParams: {random: Math.random(), op: 0}
+              });
+            });
+          }
+        }
+      }
+
+      return "";
+    } catch (e) {
+      return Promise.reject(null);
+    }
+  }
+}

+ 73 - 0
parth5/parth5/src/app/utils/urlUtils.ts

@@ -0,0 +1,73 @@
+/**
+ * 将对象添加当作参数拼接到URL上面
+ * @param baseUrl 需要拼接的url
+ * @param obj 参数对象
+ * @returns {string} 拼接后的对象
+ * 例子:
+ *  let obj = {a: '3', b: '4'}
+ *  setObjToUrlParams('www.baidu.com', obj)
+ *  ==>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;
+}
+
+/**
+ * 将路径中重复的正斜杆替换成单个斜杆隔开的字符串
+ * @param path 要处理的路径
+ * @returns {string} 将/去重后的结果
+ */
+export const uniqueSlash = (path: string) => path.replace(/(https?:\/)|(\/)+/g, '$1$2');
+// Safari 不支持以下正则(反向否定查找) shit!
+// export const uniqueSlash = (path: string) => path.replace(/(?<!:)\/{2,}/g, '/');
+
+
+export function getUrlParams() {
+  /*let href = decodeURIComponent(location.href);
+  href = decodeURIComponent(href);*/
+  const href = location.href;
+
+  /*alert("href:"+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];
+  }
+
+  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];
+      }
+    }
+  });
+
+  console.log(theRequest);
+
+  return theRequest;
+}

+ 17 - 0
parth5/parth5/src/app/views/index/index-routing.module.ts

@@ -0,0 +1,17 @@
+import { NgModule } from '@angular/core';
+import { Routes, RouterModule } from '@angular/router';
+
+import { IndexPage } from './index.page';
+
+const routes: Routes = [
+  {
+    path: '',
+    component: IndexPage
+  }
+];
+
+@NgModule({
+  imports: [RouterModule.forChild(routes)],
+  exports: [RouterModule],
+})
+export class IndexPageRoutingModule {}

+ 20 - 0
parth5/parth5/src/app/views/index/index.module.ts

@@ -0,0 +1,20 @@
+import { NgModule } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { FormsModule } from '@angular/forms';
+
+import { IonicModule } from '@ionic/angular';
+
+import { IndexPageRoutingModule } from './index-routing.module';
+
+import { IndexPage } from './index.page';
+
+@NgModule({
+  imports: [
+    CommonModule,
+    FormsModule,
+    IonicModule,
+    IndexPageRoutingModule
+  ],
+  declarations: [IndexPage]
+})
+export class IndexPageModule {}

+ 3 - 0
parth5/parth5/src/app/views/index/index.page.html

@@ -0,0 +1,3 @@
+<ion-content>
+  系统加载中,请稍等...
+</ion-content>

+ 0 - 0
parth5/parth5/src/app/views/index/index.page.scss


+ 47 - 0
parth5/parth5/src/app/views/index/index.page.ts

@@ -0,0 +1,47 @@
+import {Component, OnInit} from '@angular/core';
+import {getUrlParams} from "../../utils/urlUtils";
+import {WxcpService} from "../../service/wxcp.service";
+import {ActivatedRoute, Router} from "@angular/router";
+import {UserService} from "../../service/user.service";
+import {ConfigService} from "../../service/config.service";
+import {AccountApi} from "../../api/account";
+import {UsemodularService} from "../../service/usemodular.service";
+import {AlertModal} from "../../comm/modal/alert";
+import {AccountService} from "../../service/account.service";
+
+@Component({
+  selector: 'app-index',
+  templateUrl: './index.page.html',
+  styleUrls: ['./index.page.scss'],
+})
+export class IndexPage implements OnInit {
+  private routePath = '';
+
+
+  constructor(private router: Router, private route: ActivatedRoute, private wxcpService: WxcpService, private userService: UserService,
+              private accountService: AccountService) {
+  }
+
+  ngOnInit() {
+  }
+
+  ionViewWillEnter() {
+    const urlParams = getUrlParams() as any;
+    this.routePath = urlParams["routePath"] || '/login';
+    this.routePath = decodeURIComponent(this.routePath);
+
+    if (this.wxcpService.isWechat() && this.routePath.indexOf("wxMessage") < 0) {
+      const wxUserId = urlParams["wxUserId"] || this.userService.getWxUserID();
+      if (!wxUserId) {
+        //根据微信用户id登录系统
+        this.accountService.loginByWxUserId(wxUserId, null);
+      } else {
+        this.wxcpService.wxAuth(this.routePath);
+      }
+    } else {
+      this.router.navigate([this.routePath], {queryParams: {random: Math.random()}});
+    }
+
+  }
+
+}