You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
3.1 KiB
C#
78 lines
3.1 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
using NPin.Framework.SettingManagement.Domain;
|
|
using NPin.Framework.Upms.Domain.Settings;
|
|
using NPin.Framework.Upms.Domain.Shared.Consts;
|
|
using NPin.Framework.Upms.Domain.Shared.Enums;
|
|
using NPin.Framework.Upms.Domain.Shared.Model;
|
|
using NPin.Framework.Upms.Domain.Sms;
|
|
using Volo.Abp.Domain.Services;
|
|
|
|
namespace NPin.Framework.Upms.Domain.Managers;
|
|
|
|
public class SmsManager : DomainService
|
|
{
|
|
private readonly ILogger<SmsManager> _logger;
|
|
|
|
private readonly ISettingManager _settingManager;
|
|
|
|
private readonly IEnumerable<ISms> _smsProviders;
|
|
|
|
public SmsManager(ILogger<SmsManager> logger, ISettingManager settingManager, IEnumerable<ISms> smsProviders)
|
|
{
|
|
_logger = logger;
|
|
_settingManager = settingManager;
|
|
_smsProviders = smsProviders;
|
|
}
|
|
|
|
public async Task<SmsConfigModel> GetSmsConfigModelAsync()
|
|
{
|
|
var configJson = await _settingManager.GetOrNullUpmsAsync(ConfigConst.SmsConfigModelKey);
|
|
var settingsJson = await _settingManager.GetOrNullUpmsAsync(ConfigConst.SmsSettingsKey);
|
|
var providersJson = await _settingManager.GetOrNullUpmsAsync(ConfigConst.SmsProvidersKey);
|
|
var templateJson = await _settingManager.GetOrNullUpmsAsync(ConfigConst.SmsTemplatesKey);
|
|
|
|
var ret = JsonConvert.DeserializeObject<SmsConfigModel>(configJson ?? string.Empty) ?? new SmsConfigModel();
|
|
|
|
ret.Settings =
|
|
JsonConvert.DeserializeObject<Dictionary<SmsTypeEnum, SmsSettings>>(settingsJson ?? string.Empty) ??
|
|
new Dictionary<SmsTypeEnum, SmsSettings>();
|
|
|
|
ret.Providers = JsonConvert.DeserializeObject<List<SmsProvider>>(providersJson ?? string.Empty) ?? [];
|
|
ret.Templates = JsonConvert.DeserializeObject<List<SmsTemplate>>(templateJson ?? string.Empty) ?? [];
|
|
|
|
return ret;
|
|
}
|
|
|
|
public async Task SendSmsAsync(SmsTypeEnum smsType, string phoneNumbers, object templateParam)
|
|
{
|
|
try
|
|
{
|
|
var smsConfig = await GetSmsConfigModelAsync();
|
|
if (!smsConfig.Enabled)
|
|
{
|
|
throw new UserFriendlyException("短信服务未启用,无法发送短信。");
|
|
}
|
|
|
|
var settings = smsConfig.GetSetting(smsType);
|
|
if (settings is null)
|
|
{
|
|
throw new UserFriendlyException("未找到对应短信类型,无法发送短信。");
|
|
}
|
|
|
|
var providerConfig = smsConfig.GetProvider(settings);
|
|
var provider = _smsProviders.FirstOrDefault(i => i.ProviderType == providerConfig.ProviderType);
|
|
if (provider is null)
|
|
{
|
|
throw new NotImplementedException("未实现该方式的短信控制器");
|
|
}
|
|
|
|
await provider.SendSmsAsync(smsConfig, settings, phoneNumbers, templateParam);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, $"短信发送失败: {ex.Message}");
|
|
throw new UserFriendlyException($"短信发送失败: {ex.Message}");
|
|
}
|
|
}
|
|
} |