Browse Source

绑定微信openid

pengjing 1 year ago
parent
commit
56a680b7bd

+ 1 - 1
OrderSystem.App/H5/angular.json

@@ -14,7 +14,7 @@
         "build": {
           "builder": "@angular-devkit/build-angular:browser",
           "options": {
-            "outputPath": "../../OrderSystem.Web/wwwroot",
+            "outputPath": "../../OrderSystem.Web/wwwroot/h5/v1",
             "index": "src/index.html",
             "main": "src/main.ts",
             "polyfills": "src/polyfills.ts",

+ 4 - 3
OrderSystem.App/H5/src/app/app.component.ts

@@ -3,7 +3,8 @@ import {ActivatedRoute, Router} from "@angular/router";
 import {ConfigService} from "./service/config.service";
 import {UserService} from "./service/user.service";
 import {DesService} from "./service/des.service";
-import {LoadingController} from "@ionic/angular";
+import { LoadingController } from "@ionic/angular";
+import { WxService } from "./service/wx.service";
 
 
 @Component({
@@ -12,10 +13,10 @@ import {LoadingController} from "@ionic/angular";
   styleUrls: ['app.component.scss'],
 })
 export class AppComponent {
-  constructor(private router: Router, private route: ActivatedRoute, private userService: UserService) {
+  constructor(private router: Router, private route: ActivatedRoute, private userService: UserService, private wxService: WxService) {
   }
 
   ngOnInit() {
-    
+    this.wxService.getWechatOpenId();
   }
 }

+ 1 - 1
OrderSystem.App/H5/src/app/home/home.page.html

@@ -3,7 +3,7 @@
     <div class="mine-body">
       <div style="display:flex;margin-left:50px;">
         <div class="info-img">
-          <img class="img-user" src="../../assets/icon/icon-user-3x.png" onerror="this.src='../../assets/icon/icon-user-2x.png'" />
+          <img class="img-user" src="assets/icon/icon-user-3x.png" onerror="this.src='assets/icon/icon-user-2x.png'" />
         </div>
         <div class="info-text">
           <div class="info-text-name">

+ 3 - 0
OrderSystem.App/H5/src/app/login/login.page.html

@@ -15,6 +15,9 @@
       <ion-icon name="bag-handle-outline"></ion-icon>
       <ion-input [(ngModel)]="contractNo" type="text" placeholder="请输入合同号"></ion-input>
     </ion-item>
+    <!--<ion-item class="login-item">
+      openID:{{openID}}
+    </ion-item>-->
     <div class="login-item">
       <ion-buttons>
         <ion-button (click)="Login()">

+ 5 - 39
OrderSystem.App/H5/src/app/login/login.page.ts

@@ -5,6 +5,7 @@ import { UserService } from '../service/user.service';
 import { switchMap } from 'rxjs/operators';
 import { DESModel, DesService } from '../service/des.service';
 import { LoadingController, AlertController } from '@ionic/angular';
+import { AccountService } from '../service/account.service';
 
 @Component({
   selector: 'app-login',
@@ -13,13 +14,13 @@ import { LoadingController, AlertController } from '@ionic/angular';
 })
 export class LoginPage implements OnInit {
 
-  loginUrl = '/api/systemsetting/Account/GetToken';
   mobile: string = '';
   contractNo: string = '';
+  openID: string = '';
 
   constructor(private router: Router, private route: ActivatedRoute,
     private configService: ConfigService, private userService: UserService,
-    private desService: DesService, private loadingController: LoadingController, public alertController: AlertController) {
+    private desService: DesService, private loadingController: LoadingController, public alertController: AlertController, private accountService: AccountService) {
     this.route.queryParams.subscribe(params => {
 
     });
@@ -28,7 +29,7 @@ export class LoginPage implements OnInit {
   }
 
   ionViewWillEnter() {
-
+    this.openID = this.userService.getOpenID();
   }
 
   ngOnInit() {
@@ -46,43 +47,8 @@ export class LoginPage implements OnInit {
       return false;
     }
 
-    let token = this.desService.GetToken(this.mobile + '|' + this.contractNo);
-
-    let loading = this.loadingController.create({
-      message: '正在绑定...',
-      duration: 10000,
-      id: "loading_login1"
-    });
-
-    loading.then(l => {
-      l.present();
-    });
+    this.accountService.login(this.mobile, this.contractNo);
 
-    /*this.configService.HttpGetRomote(this.orderInfoUrl, { mobile: "", orderNo: "" }).subscribe(req => {
-      loading.then(l => l.dismiss());
-      if (req.IsSuccess) {
-        this.router.navigate(['/home']);
-      } else {
-      }
-    }, error => {
-      loading.then(l => l.dismiss());
-      this.presentAlert(error);
-    });*/
-
-    this.configService.HttpPostRomote(this.loginUrl,token).subscribe(req => {
-      loading.then(l => l.dismiss());
-      if (req.IsSuccess) {
-        this.userService.SetToken(req.Data.Token);
-        this.userService.SetUser(req.Data.UserObj);
-        this.router.navigate(['/home']);
-      } else {
-        /*this.presentAlert(req.Message);*/
-        this.presentAlert("绑定失败!请检查手机号或合同号是否正确!");
-      }
-    }, error => {
-      loading.then(l => l.dismiss());
-      this.presentAlert(error);
-    });
   }
 
   async presentAlert(msg: string) {

+ 85 - 0
OrderSystem.App/H5/src/app/service/account.service.ts

@@ -0,0 +1,85 @@
+import { Injectable, Inject } from '@angular/core';
+import { DOCUMENT } from '@angular/common';
+import { ConfigService, RequsetData } from "./config.service";
+import { from, Observable } from "rxjs";
+import { DesService } from './des.service';
+import { AlertController, LoadingController } from '@ionic/angular';
+import { ActivatedRoute, Router } from '@angular/router';
+import { UserService } from './user.service';
+
+
+@Injectable({ providedIn: 'root' })
+export class AccountService {
+  win: any;
+  loginUrl = '/api/systemsetting/Account/GetToken';
+  loginByOpenIDUrl: string = "/api/systemsetting/Account/GetTokenByOpenID";
+
+  constructor(@Inject(DOCUMENT) private document: any, private desService: DesService, private configService: ConfigService, private loadingController: LoadingController, public alertController: AlertController, private router: Router, private route: ActivatedRoute,
+    private userService: UserService) {
+    this.win = this.document.defaultView;
+  }
+
+
+  login(mobile: string, contractNo:string) {
+    let token = this.desService.GetToken(mobile + '|' + contractNo + '|' + this.userService.getOpenID());
+
+    let loading = this.loadingController.create({
+      message: '正在绑定...',
+      duration: 10000,
+      id: "loading_login1"
+    });
+
+    loading.then(l => {
+      l.present();
+    });
+
+    this.configService.HttpPostRomote(this.loginUrl, token).subscribe(req => {
+      loading.then(l => l.dismiss());
+      if (req.IsSuccess) {
+        this.loginSuccess(req.Data);
+      } else {
+        this.presentAlert("绑定失败!请检查手机号或合同号是否正确!");
+      }
+    }, error => {
+      loading.then(l => l.dismiss());
+      this.presentAlert(error);
+    });
+  }
+
+  loginByOpenID() {
+    let token = this.desService.GetToken(this.userService.getOpenID());
+
+    let loading = this.loadingController.create({
+      message: '正在绑定...',
+      duration: 10000,
+      id: "loading_login1"
+    });
+ 
+    this.configService.HttpPostRomote(this.loginByOpenIDUrl, token).subscribe(req => {
+      loading.then(l => l.dismiss());
+      if (req.IsSuccess) {
+        this.loginSuccess(req.Data);
+      }
+    }, error => {
+      loading.then(l => l.dismiss());
+    });
+  }
+
+  loginSuccess(data: any) {
+    this.userService.SetToken(data.Token);
+    this.userService.SetUser(data.UserObj);
+    this.router.navigate(['/home']);
+  }
+
+  async presentAlert(msg: string) {
+    const alert = await this.alertController.create({
+      header: '提示',
+      subHeader: '',
+      message: msg,
+      buttons: ['确定']
+    });
+
+    await alert.present();
+  }
+
+}

+ 1 - 2
OrderSystem.App/H5/src/app/service/config.service.ts

@@ -19,7 +19,7 @@ export interface Config {
   webSite: string;
   webServerHost: string;
   siteUrl: string;
-  isWxPay: boolean;
+  isWxLogin: boolean;
   isDev?: boolean;
 }
 
@@ -33,7 +33,6 @@ export interface RequsetData {
 export class ConfigService {
   configUrl = 'assets/appconfig.json';
   baseConfig: Config;
-  gddwdm: String = "001091209";
 
   constructor(private http: HttpClient, private userService: UserService) {
 

+ 11 - 4
OrderSystem.App/H5/src/app/service/user.service.ts

@@ -10,10 +10,7 @@ export class UserService {
   lStorage: any;
   userInfo: any;
   userExt: any;
-  userDataScope: string = '/appApi/home/UserDataScope';
-  //public wxUserId: string = '';
-  public cmWorkLinkAcountId: string = "";
-  public cmWorkLinkAcountType: number = null;
+  openIDName = "userOpenID";
 
   constructor(@Inject(DOCUMENT) private document: any) {
     this.win = this.document.defaultView;
@@ -78,6 +75,16 @@ export class UserService {
   ClearUser(): void {
     this.lStorage.removeItem('userinfo');
     this.lStorage.removeItem('token');
+    this.lStorage.removeItem(this.openIDName);
     this.ClearRemember();
   }
+
+  setOpenID(openID: string) {
+    this.lStorage[this.openIDName] = openID;
+  }
+
+  getOpenID() {
+    return this.lStorage[this.openIDName] || "";
+  }
+
 }

+ 105 - 0
OrderSystem.App/H5/src/app/service/wx.service.ts

@@ -0,0 +1,105 @@
+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 { Router } from "@angular/router";
+import { AccountService } from './account.service';
+
+@Injectable({
+  providedIn: 'root'
+})
+
+export class WxService {
+  win: any;
+  isWxLogin: boolean = true;
+  private siteUrl: string = '';
+  private getOauthUrl: string = '/api/wx/GetOauthUrlForBase';
+  private getOpenIdUrl: string = '/api/wx/GetOpenID';
+
+  constructor(@Inject(DOCUMENT) private document: any, private router: Router, private configService: ConfigService, private userService: UserService, private alertController: AlertController, public loadingController: LoadingController,
+     private accountService: AccountService  ) {
+    this.configService.GetConfig().subscribe((config) => {
+      this.siteUrl = config.siteUrl;
+      this.isWxLogin = config.isWxLogin;
+    });
+
+    this.win = this.document.defaultView;
+  }
+
+  isWechat = () => {
+    return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
+  }
+
+  async getWechatOpenId() {
+    if (this.isWxLogin && this.isWechat()) {
+      if (this.userService.getOpenID()) {
+        this.accountService.loginByOpenID();
+      }
+      else {
+        let code = this.getUrlCode()["code"];
+
+        const loading = await this.loadingController.create({
+          cssClass: 'my-custom-class',
+          message: '微信授权中,请稍后...',
+          duration: 2000,
+        });
+        await loading.present();
+
+        if (!code) {
+          this.configService.HttpGetRomote(this.getOauthUrl, null).subscribe(result => {
+            loading.dismiss();
+            if (result.IsSuccess)
+              window.location.href = result.Data;
+            else
+              this.presentAlert("获取微信授权地址失败!" + result.Message);
+          }, () => {
+            loading.dismiss();
+            this.presentAlert("微信授权地址请求失败!");
+          });
+        } else {
+          this.configService.HttpGetRomote(this.getOpenIdUrl, { code: code }).subscribe(result => {
+            loading.dismiss();
+            if (result.IsSuccess) {
+              this.userService.setOpenID(result.Data);
+              this.accountService.loginByOpenID();
+            }
+            else
+              this.presentAlert("获取微信openID失败!" + result.Message);
+          }, () => {
+            loading.dismiss();
+            this.presentAlert("微信openID地址请求失败!");
+          });
+        }
+      }
+    }
+  }
+
+  getUrlCode() {
+    // 截取url中的code方法
+    var url = location.href;
+    var theRequest = new Object();
+    if (url.indexOf("?") != -1) {
+      var paramsUrl = url.split('?')[1];
+      var strs = paramsUrl.split("&");
+      for (var i = 0; i < strs.length; i++) {
+        theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
+      }
+    }
+    return theRequest;
+  }
+
+  async presentAlert(msg: string) {
+    const alert = await this.alertController.create({
+      header: '提示',
+      subHeader: '',
+      message: msg,
+      buttons: ['确定']
+    });
+
+    await alert.present();
+  }
+
+}

+ 1 - 1
OrderSystem.App/H5/src/assets/appconfig.json

@@ -2,6 +2,6 @@
   "webSite": "OrderH5App",
   "webServerHost": "http://localhost:5009",
   "siteUrl": "http://localhost:5009/#",
-  "isWxPay": true,
+  "isWxLogin": true,
   "isDev": true
 }

+ 10 - 11
OrderSystem.App/H5/src/index.html

@@ -2,24 +2,23 @@
 <html lang="en">
 
 <head>
-  <meta charset="utf-8"/>
+  <meta charset="utf-8" />
   <title></title>
 
-  <base href="/"/>
+  <base href="/" />
 
-  <meta name="color-scheme" content="light dark"/>
+  <meta http-equiv="Cache-Control" content="no-cache, must-revalidate" />
+  <meta name="color-scheme" content="light dark" />
   <meta name="viewport"
-        content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
-  <meta name="format-detection" content="telephone=no"/>
-  <meta name="msapplication-tap-highlight" content="no"/>
+        content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
+  <meta name="format-detection" content="telephone=no" />
+  <meta name="msapplication-tap-highlight" content="no" />
 
-  <link rel="icon" type="image/png" href="assets/icon/favicon.png"/>
+  <link rel="icon" type="image/png" href="assets/icon/favicon.png" />
 
   <!-- add to homescreen for ios -->
-  <meta name="apple-mobile-web-app-capable" content="yes"/>
-  <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
-  <!--<script src="http://ydgzpt.gzrailway.com.cn:8088/oa/plugins/ioffice/js/h5.js"></script>-->
-  <!--<script src="http://10.160.15.180:8089/uatem/open/js/jem.js"></script>-->
+  <meta name="apple-mobile-web-app-capable" content="yes" />
+  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
   <!--<style type="text/css">
     .appLoading {
       width: 100%;

+ 4 - 0
OrderSystem.IServices/SystemSetting/IUserService.cs

@@ -14,7 +14,11 @@ namespace OrderSystem.Services.SystemSetting
     {
         LoginUser GetLoginUserById(string mobile, string contractNo);
 
+        LoginUser GetLoginUserByVxId(string openID);
+
         LoginUser GetUserById(string userID);
 
+        int UpdateUserOpenID(string userID, string openID);
+
     }
 }

+ 105 - 0
OrderSystem.Services/Common/DbContextExtensions.cs

@@ -0,0 +1,105 @@
+using System.Runtime.InteropServices.ComTypes;
+using System.Data;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using System.Data.Common;
+using System.Reflection;
+using Microsoft.Data.SqlClient;
+using Microsoft.EntityFrameworkCore;
+using System.Collections.Generic;
+using System;
+using Bowin.Common.Data;
+
+namespace OrderSystem.Services.Common
+{
+    public static class DbContextExtensions
+    {
+        private static void CombineParams(ref DbCommand command, params object[] parameters)
+        {
+            if (parameters != null)
+            {
+                foreach (SqlParameter parameter in parameters)
+                {
+                    if (!parameter.ParameterName.Contains("@"))
+                        parameter.ParameterName = $"@{parameter.ParameterName}";
+                    command.Parameters.Add(parameter);
+                }
+            }
+        }
+
+        private static DbCommand CreateCommand(DatabaseFacade facade, string sql, out DbConnection dbConn, params object[] parameters)
+        {
+            DbConnection conn = facade.GetDbConnection();
+            dbConn = conn;
+            conn.Open();
+            DbCommand cmd = conn.CreateCommand();
+            if (facade.IsSqlServer())
+            {
+                cmd.CommandText = sql;
+                CombineParams(ref cmd, parameters);
+            }
+            return cmd;
+        }
+
+        public static DataTable SqlQuery(this DatabaseFacade facade, string sql, params object[] parameters)
+        {
+            DbCommand cmd = CreateCommand(facade, sql, out DbConnection conn, parameters);
+            DbDataReader reader = cmd.ExecuteReader();
+            DataTable dt = new DataTable();
+
+            try
+            {
+                dt.Load(reader);
+                reader.Close();
+                conn.Close();
+
+            }
+            catch (System.Data.DataException e)
+            {
+                System.Data.DataRow[] rowsInError;
+                System.Text.StringBuilder sbError = new System.Text.StringBuilder();
+                // Test if the table has errors. If not, skip it.
+                if (dt.HasErrors)
+                {
+                    // Get an array of all rows with errors.
+                    rowsInError = dt.GetErrors();
+                    // Print the error of each column in each row.
+                    for (int i = 0; i < rowsInError.Length; i++)
+                    {
+                        foreach (System.Data.DataColumn column in dt.Columns)
+                        {
+                            sbError.Append(column.ColumnName + " " + rowsInError[i].GetColumnError(column));
+                        }
+                        // Clear the row errors
+                        rowsInError[i].ClearErrors();
+                    }
+                }
+            }
+            return dt;
+        }
+
+        public static IEnumerable<T> SqlQuery<T>(this DatabaseFacade facade, string sql, params object[] parameters) where T : class, new()
+        {
+            DataTable dt = SqlQuery(facade, sql, parameters);
+            return dt.ToEnumerable<T>();
+        }
+
+        public static IEnumerable<T> ToEnumerable<T>(this DataTable dt) where T : class, new()
+        {
+            PropertyInfo[] propertyInfos = typeof(T).GetProperties();
+            T[] ts = new T[dt.Rows.Count];
+            int i = 0;
+            foreach (DataRow row in dt.Rows)
+            {
+                T t = new T();
+                foreach (PropertyInfo p in propertyInfos)
+                {
+                    if (dt.Columns.IndexOf(p.Name) != -1 && row[p.Name] != DBNull.Value)
+                        p.SetValue(t, row[p.Name], null);
+                }
+                ts[i] = t;
+                i++;
+            }
+            return ts;
+        }
+    }
+}

+ 31 - 0
OrderSystem.Services/SystemSetting/UserService.cs

@@ -15,6 +15,7 @@ using Microsoft.VisualBasic;
 using Z.EntityFramework.Plus;
 using OrderSystem.Entity.Extensions;
 using Bowin.Common.Utility;
+using OrderSystem.Services.Common;
 
 namespace OrderSystem.Services.SystemSetting
 {
@@ -44,6 +45,20 @@ namespace OrderSystem.Services.SystemSetting
             return sql.FirstOrDefault();
         }
 
+        public LoginUser GetLoginUserByVxId(string openID)
+        {
+            var sql = from u in DbContext.CVxIdClientPhoneMerge
+                      where u.VxId == openID
+                      select new LoginUser
+                      {
+                          UserID = u.ClientPhoneNo,
+                          UserName = u.ClientName,
+                          Mobile = u.ClientPhoneNo
+                      };
+
+            return sql.FirstOrDefault();
+        }
+
 
         public LoginUser GetUserById(string userID)
         {
@@ -58,5 +73,21 @@ namespace OrderSystem.Services.SystemSetting
 
             return sql.FirstOrDefault();
         }
+
+
+        public int UpdateUserOpenID(string userID, string openID) {
+
+            /*var list = DbContext.CVxIdClientPhoneMerge.Where(e => e.ClientPhoneNo == userID).ToList();
+            list.ForEach(item => 
+            {
+                item.VxId = openID;
+                this.DbContext.CVxIdClientPhoneMerge.Update(item);
+            });*/
+
+            this.DbContext.Database.SqlQuery<CVxIdClientPhoneMerge>($"update C_VxIdClientPhoneMerge set VxId='{openID}' where ClientPhoneNo = '{userID}'", null);
+
+            return this.DbContext.SaveChanges();
+        }
+
     }
 }

+ 16 - 2
OrderSystem.Web/Configuration.cs

@@ -29,6 +29,8 @@ namespace OrderSystem.Web
                    .Split(",", StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => x.Trim()).ToList();
 
+                result.WxConfig = configuration.GetSection("WxConfig").Get<WxConfig>();
+
                 return result;
             }
         }
@@ -37,12 +39,14 @@ namespace OrderSystem.Web
 
         public List<string> CROSDomainList { get; set; }
 
+        public WxConfig WxConfig { get; set; }
+
     }
 
 
     public class AppSettings
     {
-        public string TemplatePath { get; set; }
+        /*public string TemplatePath { get; set; }
         public string PicturePath { get; set; }
         public string FilePath { get; set; }
 
@@ -52,6 +56,16 @@ namespace OrderSystem.Web
             {
                 return HttpHelper.MapPath(TemplatePath);
             }
-        }
+        }*/
+
+        public string H5Version { get; set; }
+    }
+
+    public class WxConfig 
+    {
+        public string AppId { get; set; }
+
+        public string AppSecret { get; set; }
+        public string RedirectURI { get; set; }
     }
 }

+ 27 - 0
OrderSystem.Web/Controllers/AppController.cs

@@ -0,0 +1,27 @@
+using Bowin.Common.Cache;
+using Bowin.Common.DES;
+using Bowin.Common.ServiceToken;
+using Bowin.Common.Utility;
+using Bowin.Common.WebModels;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Newtonsoft.Json;
+using OrderSystem.Entity.ViewModel;
+using OrderSystem.Services.SystemSetting;
+using System.Net.Http;
+
+
+namespace OrderSystem.Web.Controllers
+{
+    [Route("")]
+    [ApiController]
+    public class AppController : ControllerBase
+    {
+
+        [HttpGet("h5/{v}")]
+        public RedirectResult h5()
+        {
+            return Redirect("/h5/" + Configuration.Current.AppSettings.H5Version + "/index.html");
+        }
+    }
+}

+ 22 - 1
OrderSystem.Web/Controllers/SystemSetting/AccountController.cs

@@ -31,6 +31,7 @@ namespace OrderSystem.Web.Controllers.SystemSetting
             var datas = data.Split('|');
             string loginID = datas[0];
             string pdmd = datas[1];
+            string openID = datas.Length == 3 ? datas[2] : "";
             /*string verfiyKey = datas[2];
             string verfiyCode = datas[3];
 
@@ -46,12 +47,32 @@ namespace OrderSystem.Web.Controllers.SystemSetting
 
             ResultMessage result = new ResultMessage();
 
-            var token = JwtHelper.GetToken(() => UserService.GetLoginUserById(loginID, pdmd), (x => x.UserID));
+            var user = UserService.GetLoginUserById(loginID, pdmd);
+
+            var token = JwtHelper.GetToken(() => user, (x => x.UserID));
+
+            if (user != null && !string.IsNullOrEmpty(openID))
+                UserService.UpdateUserOpenID(user.UserID, openID);
 
             return ResultMessage.Success(token);
         }
 
 
+        [AllowAnonymous]
+        [HttpPost]
+        public ResultMessage GetTokenByOpenID([FromBody] DesModel inputObject)
+        {
+            var openID = this.DesAccessor.DeDesToken(inputObject);
+
+            ResultMessage result = new ResultMessage();
+
+            var user = UserService.GetLoginUserByVxId(openID);
+
+            var token = JwtHelper.GetToken(() => user, (x => x.UserID));
+
+            return ResultMessage.Success(token);
+        }
+
         [HttpPost]
         public ResultMessage RefreshToken()
         {

+ 82 - 0
OrderSystem.Web/Controllers/WxController.cs

@@ -0,0 +1,82 @@
+using Bowin.Common.Cache;
+using Bowin.Common.DES;
+using Bowin.Common.ServiceToken;
+using Bowin.Common.Utility;
+using Bowin.Common.WebModels;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Newtonsoft.Json;
+using OrderSystem.Entity.ViewModel;
+using OrderSystem.Services.SystemSetting;
+using System.Net.Http;
+
+namespace OrderSystem.Web.Controllers
+{
+    [Route("api/[controller]/[action]")]
+    [Authorize]
+    public class WxController : ControllerBase
+    {
+        private readonly IHttpClientFactory _clientFactory;
+        public WxController(IHttpClientFactory clientFactory)
+        {
+            _clientFactory = clientFactory;
+        }
+
+        [AllowAnonymous]
+        [HttpGet]
+        public ResultMessage GetOauthUrlForBase()
+        {
+            string url = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={ Configuration.Current.WxConfig.AppId}&redirect_uri={Configuration.Current.WxConfig.RedirectURI}/{Configuration.Current.AppSettings.H5Version}/index.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
+
+            return ResultMessage.Success(url);
+        }
+
+
+        [AllowAnonymous]
+        [HttpGet]
+        public ResultMessage GetOpenID(string code) 
+        {
+            string url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={ Configuration.Current.WxConfig.AppId}&secret={Configuration.Current.WxConfig.AppSecret}&code={code}&grant_type=authorization_code";
+
+            var client = _clientFactory.CreateClient();
+
+            var httpResponse = client.PostAsync(url, null).Result;
+
+            if (httpResponse.IsSuccessStatusCode)
+            {
+                var jsonData = httpResponse.Content.ReadAsStringAsync().Result;
+
+                var error = JsonConvert.DeserializeObject<WxMpError>(jsonData);
+
+                if (error != null && !string.IsNullOrEmpty(error.errcode))
+                    return ResultMessage.GetError($"获取openID接口返回错误!错误代码:{error.errcode},错误信息:{error.errmsg}");
+
+                var data = JsonConvert.DeserializeObject<WxMpOAuth2AccessToken>(jsonData);
+
+                return ResultMessage.Success(data.openid);
+
+            }
+            else 
+            {
+                return ResultMessage.GetError("获取openID接口请求错误!错误代码:" + httpResponse.StatusCode);
+            }
+           
+        }
+
+        public class WxMpOAuth2AccessToken 
+        {
+            public string access_token { get; set; }
+            public int expires_in { get; set; }
+            public string refresh_token { get; set; }
+            public string openid { get; set; }
+            public string scope { get; set; }
+            public string unionid { get; set; }
+        }
+
+        public class WxMpError 
+        {
+            public string errcode { get; set; }
+            public string errmsg { get; set; }
+        }
+    }
+}

+ 1 - 2
OrderSystem.Web/Startup.cs

@@ -92,7 +92,6 @@ namespace OrderSystem.Web
 
 
             services.AddHttpClient();
-
         }
 
         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -111,7 +110,7 @@ namespace OrderSystem.Web
             {
                 DefaultFileNames = new List<string>
                 {
-                    "index.html"
+                   "h5/"+ OrderSystem.Web.Configuration.Current.AppSettings.H5Version+"/index.html"
                 }
             });
             var provider = new FileExtensionContentTypeProvider();

+ 8 - 0
OrderSystem.Web/appsettings.json

@@ -18,5 +18,13 @@
     "Cros": {
       "Domain": "http://localhost:8100, http://localhost:8101"
     }
+  },
+  "WxConfig": {
+    "AppId": "wx737c2a7879b897c1",
+    "AppSecret": "0d37c99bf2edd9ef3d839869bfa724ad",
+    "RedirectURI": "http://www.bowintek.com/order/h5"
+  },
+  "AppSettings": {
+    "H5Version": "v1"
   }
 }