You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

222 lines
8.8 KiB

1 year ago
  1. using Azure.Core;
  2. using Microsoft.Extensions.Configuration;
  3. using Microsoft.Extensions.Logging;
  4. using Microsoft.Identity.Client;
  5. using Newtonsoft.Json;
  6. using Newtonsoft.Json.Converters;
  7. using Shentun.Utilities;
  8. using Shentun.WebPeis.PatientRegisters;
  9. using Shentun.WebPeis.PlugIns;
  10. using Shentun.WebPeis.QueueRegisters;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IdentityModel.Tokens.Jwt;
  14. using System.Linq;
  15. using System.Net.Http.Headers;
  16. using System.Text;
  17. using System.Threading.Tasks;
  18. namespace Shentun.WebPeis.Plugins
  19. {
  20. public class AppQueueRegisterPlugIns
  21. {
  22. protected IConfiguration? AppConfig;
  23. private string? _appBaseAddress;
  24. private static string? _accesToken;
  25. private string? _appUser;
  26. private string? _appPassword;
  27. private string? _appQueueRegisterUrl;
  28. public AppQueueRegisterPlugIns()
  29. {
  30. Init();
  31. }
  32. public void Init()
  33. {
  34. AppConfig = new ConfigurationBuilder()
  35. .SetBasePath(DirectoryHelper.GetAppDirectory()) // 设置基础路径为当前目录
  36. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  37. .Build();
  38. _appBaseAddress = AppConfig.GetSection("Peis")
  39. .GetSection("PeisBaseUrl").Value;
  40. _appUser = AppConfig.GetSection("Peis")
  41. .GetSection("AppUser").Value;
  42. _appPassword = AppConfig.GetSection("Peis")
  43. .GetSection("AppPassWord").Value;
  44. _appQueueRegisterUrl = AppConfig.GetSection("Peis")
  45. .GetSection("AppQueueRegisterUrl").Value;
  46. }
  47. /// <summary>
  48. /// 小程序获取当前排队信息
  49. /// </summary>
  50. /// <param name="input"></param>
  51. /// <returns></returns>
  52. public async Task<GetAppQueueRegisterByPersonIdDto> GetAppQueueRegisterByIdNoAsync(IdNoInputDto input)
  53. {
  54. var appQueueRegisterByPersonIdDtos = await CallAppServiceAsync<IdNoInputDto, GetAppQueueRegisterByPersonIdDto>(_appQueueRegisterUrl,
  55. input);
  56. return appQueueRegisterByPersonIdDtos;
  57. }
  58. public async Task<TOut> CallAppServiceAsync<TInput, TOut>(string url, TInput data, string method = "post")
  59. {
  60. string baseAddress = _appBaseAddress;
  61. await CheckLoginAsync();
  62. using (var httpClientHandler = new HttpClientHandler())
  63. {
  64. using (var httpClient = new HttpClient(httpClientHandler))
  65. {
  66. httpClient.BaseAddress = new Uri(baseAddress);
  67. httpClient.DefaultRequestHeaders.Accept.Add(
  68. new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
  69. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesToken);
  70. IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
  71. timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
  72. var sendData = JsonConvert.SerializeObject(data, Formatting.Indented, timeFormat);
  73. using (HttpContent httpContent = new StringContent(sendData))
  74. {
  75. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  76. HttpResponseMessage response = null;
  77. if (method == "post")
  78. {
  79. response = await httpClient.PostAsync(url, httpContent);
  80. }
  81. else
  82. {
  83. response = await httpClient.GetAsync(url);
  84. }
  85. string result;
  86. if (!response.IsSuccessStatusCode)
  87. {
  88. result = response.Content.ReadAsStringAsync().Result;
  89. throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
  90. }
  91. result = await response.Content.ReadAsStringAsync();
  92. var resultDto = JsonConvert.DeserializeObject<WebApiOutDto<TOut>>(result);
  93. if (resultDto != null)
  94. {
  95. if (resultDto.Code == -1)
  96. {
  97. throw new Exception($"调用WebApi失败,返回-1,消息:" + resultDto.Message);
  98. }
  99. return resultDto.Data;
  100. }
  101. return resultDto.Data;
  102. }
  103. }
  104. }
  105. }
  106. private async Task CheckLoginAsync()
  107. {
  108. if (string.IsNullOrWhiteSpace(_accesToken))
  109. {
  110. await LoginAsync();
  111. }
  112. else
  113. {
  114. var handler = new JwtSecurityTokenHandler();
  115. var payload = handler.ReadJwtToken(_accesToken).Payload;
  116. var claims = payload.Claims;
  117. var exp = claims.First(claim => claim.Type == "exp").Value;
  118. if (exp == null)
  119. {
  120. await LoginAsync();
  121. }
  122. else
  123. {
  124. if (long.TryParse(exp, out var expires))
  125. {
  126. var expireTime = DateTimeOffset.FromUnixTimeSeconds(expires).LocalDateTime;
  127. if (expireTime <= DateTime.Now)
  128. {
  129. await LoginAsync();
  130. }
  131. }
  132. else
  133. {
  134. await LoginAsync();
  135. }
  136. }
  137. }
  138. }
  139. public async Task<WebApiOutDto<LoginOutDataDto>> LoginAsync()
  140. {
  141. if (string.IsNullOrWhiteSpace(_appUser))
  142. {
  143. throw new Exception("SelfUser不能为空");
  144. }
  145. if (string.IsNullOrWhiteSpace(_appPassword))
  146. {
  147. throw new Exception("SelfPassword不能为空");
  148. }
  149. var relult = await LoginAsync(_appUser, _appPassword);
  150. return relult;
  151. }
  152. public async Task<WebApiOutDto<LoginOutDataDto>> LoginAsync(string userId, string password)
  153. {
  154. if (string.IsNullOrWhiteSpace(userId))
  155. {
  156. throw new Exception("用户ID不能为空");
  157. }
  158. if (string.IsNullOrWhiteSpace(password))
  159. {
  160. throw new Exception("密码不能为空");
  161. }
  162. using (var httpClientHandler = new HttpClientHandler())
  163. {
  164. using (var httpClient = new HttpClient(httpClientHandler))
  165. {
  166. httpClient.BaseAddress = new Uri(_appBaseAddress);
  167. httpClient.DefaultRequestHeaders.Accept.Add(
  168. new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
  169. var url = "api/identity/users/login";
  170. var loginUser = new LoginInputDto()
  171. {
  172. UserName = userId,
  173. Password = password
  174. };
  175. var sendData = JsonConvert.SerializeObject(loginUser);
  176. using (HttpContent httpContent = new StringContent(sendData))
  177. {
  178. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  179. HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
  180. string result;
  181. if (!response.IsSuccessStatusCode)
  182. {
  183. result = response.Content.ReadAsStringAsync().Result;
  184. throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
  185. }
  186. result = await response.Content.ReadAsStringAsync();
  187. var restultDto = JsonConvert.DeserializeObject<WebApiOutDto<LoginOutDataDto>>(result);
  188. if (restultDto == null)
  189. {
  190. throw new Exception("返回结果是空");
  191. }
  192. if (restultDto.Code != 1)
  193. {
  194. throw new Exception($"登录失败{restultDto.Message}");
  195. }
  196. _accesToken = restultDto.Data.access_token;
  197. return restultDto;
  198. }
  199. }
  200. }
  201. }
  202. }
  203. }