using ApiTools.Core; using Furion; using Furion.DatabaseAccessor; using Furion.HttpRemote; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ApiTools.CommonServer.Application { /// /// 阿里云短信平台回传通知 /// public class SmsAliyunNotifyCommandHandler( IRepository repSmsSetting, IRepository repSmsLog, ApiTools.Core.SmsUtils smsUtils, IHttpRemoteService httpRemoteService ) : IRequestHandler { private readonly IRepository repSmsSetting = repSmsSetting; private readonly IRepository repSmsLog = repSmsLog; private readonly Core.SmsUtils smsUtils = smsUtils; private readonly IHttpRemoteService httpRemoteService = httpRemoteService; /// /// 阿里云短信平台回传通知 /// /// /// /// public async Task Handle(SmsAliyunNotifyCommand request, CancellationToken cancellationToken) { if (App.GetConfig("Environment") == "Product") { try { await httpRemoteService.PostAsStringAsync("http://118.178.252.28:8780/api/common/sms/smsAliyunNotify", builder => builder.SetJsonContent(request)); } catch { } } var templateCodes = await EnumUtils.GetModel(); var msgIds = request.DistinctSelect(it => it.BizId.ToString()); var entities = await repSmsLog.AsQueryable() .Where(it => it.Access == EnumSmsAccess.AliyunSms && msgIds.Contains(it.RequestId) && it.Status == EnumSmsStatus.InProcess) .ToListAsync(); var channelIds = entities.DistinctSelect(it => it.ChannelId.HasValue, it => it.ChannelId.Value); var settings = await repSmsSetting.AsQueryable().AsNoTracking() .Include(it => it.Accesses) .Where(it => it.ChannelId.HasValue && channelIds.Contains(it.ChannelId.Value)) .ToListAsync(); foreach (var entity in entities) { var report = request.FirstOrDefault(it => it.BizId.ToString() == entity.RequestId); if (report != null) { entity.Status = report.Success ? EnumSmsStatus.Success : EnumSmsStatus.Fail; entity.Code = report.ErrCode; entity.Message = report.ErrMsg; await repSmsLog.UpdateNowAsync(entity); if (entity.Status == EnumSmsStatus.Fail) { var templateCode = templateCodes.Items.FirstOrDefault(it => it.Name == entity.TemplateCode)?.Enum; if (templateCode.HasValue) { var templateParam = entity.TemplateParam.IsNotNull() ? JObject.Parse(entity.TemplateParam) : null; var setting = settings.FirstOrDefault(it => it.ChannelId == entity.ChannelId); await smsUtils.Send(setting, entity, new SendSmsModel { PhoneNumber = entity.PhoneNumber, TemplateCode = templateCode.Value, Expiry = entity.Expiry, }, templateParam, cancellationToken); } } } } return new SmsAliyunNotifyCommandResult { Code = 0, Msg = " 成功" }; } } }