using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Profile; using DS.Module.Core; using DS.Module.UserModule; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using NLog; using SqlSugar; namespace DS.Module.SMS; public class SendMessageService : ISendMessageService { private readonly IServiceProvider _serviceProvider; private readonly ISqlSugarClient db; private readonly IUser user; private readonly string accessKeyId; private readonly string accessSecret; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); /// /// 构造函数 /// /// public SendMessageService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; db = _serviceProvider.GetRequiredService(); user = _serviceProvider.GetRequiredService(); accessKeyId = AppSetting.app(new string[] { "AliSMS", "AccessKeyId" }); accessSecret = AppSetting.app(new string[] { "AliSMS", "AccessKeySecret" }); } public async Task SendAliYunMessage(TemplateMessages model) { IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessSecret); DefaultAcsClient client = new DefaultAcsClient(profile); CommonRequest request = new CommonRequest(); request.Method = MethodType.POST; request.Domain = "dysmsapi.aliyuncs.com"; request.Version = "2017-05-25"; request.Action = "SendSms"; // request.Protocol = ProtocolType.HTTP; request.AddQueryParameters("PhoneNumbers", model.PhoneNumbers); request.AddQueryParameters("SignName", model.SignName); request.AddQueryParameters("TemplateCode", model.TemplateCode); request.AddQueryParameters("TemplateParam", model.TemplateParam); try { CommonResponse response = client.GetCommonResponse(request); var content = System.Text.Encoding.Default.GetString(response.HttpResponse.Content); var res = JsonConvert.DeserializeObject(content); if (res.Code == "OK") { return await Task.FromResult(DataResult.Successed("发送成功!")); } else { Logger.Log(LogLevel.Error, "阿里云短信发送失败 " + DateTime.Now.ToString() + "\r\n" + content); return await Task.FromResult(DataResult.Successed("发送失败!-" + res.Message)); } // Console.WriteLine(content); } catch (Exception e) { Logger.Log(LogLevel.Error, DateTime.Now.ToString() + "\r\n" + e.ToString()); return await Task.FromResult(DataResult.Failed(e.ToString())); } } }