using Microsoft.Extensions.Configuration; using Shentun.Utilities; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Shentun.Sms.Client { public class SmsClientHelper { protected static IConfiguration? _appConfig; private static string? _baseAddress; private static string? _createSmsTaskUrl; private static string? _accesToken; private static string? _user; private static string? _password; private static string? _email; static SmsClientHelper() { _appConfig = new ConfigurationBuilder() .SetBasePath(DirectoryHelper.GetAppDirectory()) // 设置基础路径为当前目录 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); _baseAddress = _appConfig.GetSection("Sms") .GetSection("BaseAddress").Value; _createSmsTaskUrl = _appConfig.GetSection("Sms") .GetSection("CreateSmsTaskUrl").Value; _user = _appConfig.GetSection("Sms") .GetSection("User").Value; _password = _appConfig.GetSection("Sms") .GetSection("Password").Value; } public async static Task CreateSmsTask(CreateSmsTaskDto createSmsTaskDto) { if (createSmsTaskDto == null) { throw new Exception("createSmsTaskDto参数不能为空"); } if (createSmsTaskDto.MobileTelephone.Length != 11) { throw new Exception("手机号长度必须为11位"); } if (string.IsNullOrWhiteSpace(createSmsTaskDto.PersonId)) { throw new Exception("人员ID不能为空"); } if (string.IsNullOrWhiteSpace(createSmsTaskDto.PersonName)) { throw new Exception("姓名不能为空"); } if (string.IsNullOrWhiteSpace(createSmsTaskDto.CountryCode)) { throw new Exception("国家编码不能为空"); } if (string.IsNullOrWhiteSpace(createSmsTaskDto.Content)) { throw new Exception("短信内容不能为空"); } if (createSmsTaskDto.SmsAppId == null || createSmsTaskDto.SmsAppId == Guid.Empty) { var smsAppIdStr = _appConfig.GetSection("Sms") .GetSection("SmsAppId").Value; if (!Guid.TryParse(smsAppIdStr, out var smsAppId)) { throw new Exception("解析短信应用ID错误"); } createSmsTaskDto.SmsAppId = smsAppId; } var reslut = await CallAppServiceAsync(_createSmsTaskUrl, createSmsTaskDto); } public async static Task CreateVerifySmsTask(CreateSmsTaskDto smsDto) { var verifySmsTypeIdStr = _appConfig.GetSection("Sms") .GetSection("VerifySmsTypeId").Value; if (!Guid.TryParse(verifySmsTypeIdStr, out var verifySmsTypeId)) { throw new Exception("解析校验短信类别ID错误"); } smsDto.SmsTypeId = verifySmsTypeId; await CreateSmsTask(smsDto); } public async static Task CreateAppointSmsTask(CreateSmsTaskDto smsDto) { var appointSmsTypeIdStr = _appConfig.GetSection("Sms") .GetSection("AppointSmsTypeId").Value; if (!Guid.TryParse(appointSmsTypeIdStr, out var appointSmsTypeId)) { throw new Exception("解析预约成功短信类别ID错误"); } var smsAppIdStr = _appConfig.GetSection("Sms") .GetSection("SmsAppId").Value; if (!Guid.TryParse(smsAppIdStr, out var smsAppId)) { throw new Exception("解析短信应用ID错误"); } string appointTemplateId = _appConfig.GetSection("Sms") .GetSection("AppointTemplateId").Value; smsDto.SmsAppId = smsAppId; smsDto.SmsTypeId = appointSmsTypeId; smsDto.TemplateId = appointTemplateId; var result = await CallAppServiceAsync(_createSmsTaskUrl, smsDto); } public async static Task CallAppServiceAsync(string url, TInput data, string method = "post") { if (string.IsNullOrWhiteSpace(_baseAddress)) { throw new Exception("_baseAddress不能为空"); } string baseAddress = _baseAddress; await CheckLoginAsync(); using (var httpClientHandler = new HttpClientHandler()) { using (var httpClient = new HttpClient(httpClientHandler)) { httpClient.BaseAddress = new Uri(baseAddress); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型 httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesToken); var jsonOptions = new JsonSerializerOptions { WriteIndented = true, // 设置为true以便于可读性更好的JSON输出 PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 如果你想要对日期进行格式化,可以使用JsonConverter Converters = { new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss") } }; var sendData = System.Text.Json.JsonSerializer.Serialize(data, jsonOptions); using (HttpContent httpContent = new StringContent(sendData)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = null; if (method == "post") { response = await httpClient.PostAsync(url, httpContent); } else { response = await httpClient.GetAsync(url); } string result; if (!response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result); } result = await response.Content.ReadAsStringAsync(); var resultDto = System.Text.Json.JsonSerializer.Deserialize>(result, jsonOptions); if (resultDto.Code == -1) { throw new Exception($"调用WebApi失败,返回-1,消息:" + resultDto.Message); } return resultDto.Data; } } } } public async static Task> LoginAsync() { if (string.IsNullOrWhiteSpace(_user)) { throw new Exception("SelfUser不能为空"); } if (string.IsNullOrWhiteSpace(_password)) { throw new Exception("SelfPassword不能为空"); } var relult = await LoginAsync(_user, _password); return relult; } public async static Task> LoginAsync(string userId, string password) { if (string.IsNullOrWhiteSpace(userId)) { throw new Exception("用户ID不能为空"); } if (string.IsNullOrWhiteSpace(password)) { throw new Exception("密码不能为空"); } using (var httpClientHandler = new HttpClientHandler()) { using (var httpClient = new HttpClient(httpClientHandler)) { httpClient.BaseAddress = new Uri(_baseAddress); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型 var url = "api/app/CustomerUser/UserLogin"; var jsonOptions = new JsonSerializerOptions { WriteIndented = true, // 设置为true以便于可读性更好的JSON输出 PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 如果你想要对日期进行格式化,可以使用JsonConverter Converters = { new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss") } }; var loginUser = new SmsLoginInputDto() { UserName = userId, Password = password }; var sendData = System.Text.Json.JsonSerializer.Serialize(loginUser); using (HttpContent httpContent = new StringContent(sendData)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await httpClient.PostAsync(url, httpContent); string result; if (!response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; throw new Exception("登录短信系统时http通信错误:" + response.StatusCode + ",结果:" + result); } result = await response.Content.ReadAsStringAsync(); var restultDto = System.Text.Json.JsonSerializer.Deserialize>(result, jsonOptions); if (restultDto == null) { throw new Exception("返回结果是空"); } if (restultDto.Code != 1) { throw new Exception($"短信登录失败{restultDto.Message}"); } _accesToken = restultDto.Data.access_token; return restultDto; } } } } private async static Task CheckLoginAsync() { if (string.IsNullOrWhiteSpace(_accesToken)) { await LoginAsync(); } else { var handler = new JwtSecurityTokenHandler(); var payload = handler.ReadJwtToken(_accesToken).Payload; var claims = payload.Claims; var exp = claims.First(claim => claim.Type == "exp").Value; if (exp == null) { await LoginAsync(); } else { if (long.TryParse(exp, out var expires)) { var expireTime = DateTimeOffset.FromUnixTimeSeconds(expires).LocalDateTime; if (expireTime <= DateTime.Now) { await LoginAsync(); } } else { await LoginAsync(); } } } } } }