4、ABPZero系列教程之拼多多卖家工具 集成短信发送模块
ABPZero并没有手机短信发送功能,现在我们来集成一个,为后面注册、登录作铺垫。
阿里云短信服务
首先需要在阿里云开通短信服务,连接地址
开通后,在签名管理中添加一个签名
在模板管理中添加一个模板,如下图所示
最后需要使用阿里云提供的.NET发送短信类库,下面可以直接下载我上传的类库,也可以去官方下载,然后提取我所说的2个类库(aliyun-net-sdk-core.dll、aliyun-net-sdk-dysmsapi.dll)
直接下载文件:https://files.cnblogs.com/files/shensigzs/aliyun-net-sdk.zip (里面包含2个类库,把这2个类库引用到Core项目)
.NET发送短信SDK:https://help.aliyun.com/document_detail/59836.html?spm=5176.doc55284.6.573.GaNxg6
安装类库
如下图所示
使用的模块是Abp.Net.Sms,源码地址:https://github.com/berkaroad/Abp.Net.Sms
Core项目添加实现
添加AliDayuSmsSender类,实现2个方法(一个同步、一个异步)
文件路径:D:\abp version\aspnet-zero-3.4.0\aspnet-zero-3.4.0\src\MyCompanyName.AbpZeroTemplate.Core\Authorization\Users\AliDayuSmsSender.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Abp.Dependency; using Abp.Net.Sms; using Abp.UI; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Exceptions; using Aliyun.Acs.Core.Profile; using Aliyun.Acs.Dysmsapi.Model.V20170525; using Castle.Core.Logging; namespace MyCompanyName.AbpZeroTemplate.Authorization.Users { public class AliDayuSmsSender : SmsSenderBase, ITransientDependency { private IClientProfile profile = null; public ILogger Logger { get; set; } public AliDayuSmsSender(ISmsSenderConfiguration configuration) : base(configuration) { Logger = NullLogger.Instance; profile = DefaultProfile.GetProfile("cn-hangzhou", configuration.GetAppKey(), configuration.GetAppSecret()); } protected override void SendSms(SmsMessage sms) { DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com"); IAcsClient acsClient = new DefaultAcsClient(profile); SendSmsRequest request = new SendSmsRequest(); try { //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式 request.PhoneNumbers = sms.To; //必填:短信签名-可在短信控制台中找到 request.SignName = sms.FreeSignName; //必填:短信模板-可在短信控制台中找到 request.TemplateCode = string.IsNullOrEmpty(sms.TemplateCode) ? _configuration.GetDefaultSmsTemplateCode() : sms.TemplateCode; //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.TemplateParam = sms.TemplateParams; //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 //request.OutId = "yourOutId"; //请求失败这里会抛ClientException异常 SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request); Logger.Info("发送返回:" + sendSmsResponse.Message); } catch (ServerException e) { throw new UserFriendlyException("短信发送失败", new Exception(string.Format("to:{0},errCode:{1},errMsg:{2}", sms.To, e.ErrorCode, e.Message))); } catch (ClientException e) { throw new UserFriendlyException("短信发送失败", new Exception(string.Format("to:{0},errCode:{1},errMsg:{2}", sms.To, e.ErrorCode, e.Message))); } } protected override Task SendSmsAsync(SmsMessage sms) { DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com"); var task = new Task(() => { IAcsClient acsClient = new DefaultAcsClient(profile); SendSmsRequest request = new SendSmsRequest(); try { //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式 request.PhoneNumbers = sms.To; //必填:短信签名-可在短信控制台中找到 request.SignName = sms.FreeSignName; //必填:短信模板-可在短信控制台中找到 request.TemplateCode = string.IsNullOrEmpty(sms.TemplateCode) ? _configuration.GetDefaultSmsTemplateCode() : sms.TemplateCode; //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.TemplateParam = sms.TemplateParams; //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 //request.OutId = "yourOutId"; //请求失败这里会抛ClientException异常 SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request); Logger.Info("发送返回:" + sendSmsResponse.Message); } catch (ServerException e) { throw new UserFriendlyException("短信发送失败", new Exception(string.Format("to:{0},errCode:{1},errMsg:{2}", sms.To, e.ErrorCode, e.Message))); } catch (ClientException e) { throw new UserFriendlyException("短信发送失败", new Exception(string.Format("to:{0},errCode:{1},errMsg:{2}", sms.To, e.ErrorCode, e.Message))); } }); task.Start(); return task; } } }
修改AppSettingProvider.cs,在return new[]里面添加如下代码
文件路径:D:\abpweb\PddSellerAssistant\PddSellerAssistant.Core\Configuration\AppSettingProvider.cs
return new[] { // Sms config new SettingDefinition(SmsSettingNames.ServiceUrl, ConfigurationManager.AppSettings[SmsSettingNames.ServiceUrl] ?? ""), new SettingDefinition(SmsSettingNames.AppKey, ConfigurationManager.AppSettings[SmsSettingNames.AppKey] ?? ""), new SettingDefinition(SmsSettingNames.AppSecret, ConfigurationManager.AppSettings[SmsSettingNames.AppSecret] ?? ""), new SettingDefinition(SmsSettingNames.DefaultFreeSignName, ConfigurationManager.AppSettings[SmsSettingNames.DefaultFreeSignName] ?? ""), new SettingDefinition(SmsSettingNames.DefaultSmsTemplateCode, ConfigurationManager.AppSettings[SmsSettingNames.DefaultSmsTemplateCode] ?? ""), //Host settings
修改web.config,添加如下配置节点
<!-- 短信api配置开始--> <add key="Abp.Net.Sms.AppKey" value="" /> <add key="Abp.Net.Sms.AppSecret" value="" /> <add key="Abp.Net.Sms.DefaultFreeSignName" value="填写签名名称" /> <add key="Abp.Net.Sms.DefaultSmsTemplateCode" value="填写模板ID" /> <add key="Abp.Net.Sms.ServiceUrl" value="" /> <!-- 短信api配置结束-->
AppKey、AppSecret都可以在阿里云后台获取
修改AbpZeroTemplateCoreModule,代码修改如下
文件路径:D:\abp version\aspnet-zero-3.4.0\aspnet-zero-3.4.0\src\MyCompanyName.AbpZeroTemplate.Core\AbpZeroTemplateCoreModule.cs
if (DebugHelper.IsDebug) { //调试模式禁用邮件发送 //IocManager.Register<IEmailSender, NullEmailSender>(DependencyLifeStyle.Transient); //调试模式禁用手机短信发送 //IocManager.Register<ISmsSender, NullSmsSender>(DependencyLifeStyle.Transient); }
可以看到我都备注掉,因为我就是要在调试模式下测试邮件、短信是否能够发送。
[DependsOn(typeof(AbpZeroCoreModule), typeof(AbpZeroLdapModule), typeof(AbpAutoMapperModule), typeof(AbpNetSmsModule) )]
此处是添加短信模块依赖
Application项目
添加文件ISmsMessageService.cs
文件路径:D:\abp version\aspnet-zero-3.4.0\aspnet-zero-3.4.0\src\MyCompanyName.AbpZeroTemplate.Application\Authorization\Users\ISmsMessageService.cs
public interface ISmsMessageService : IApplicationService { void Send(string to, string templateCode, string templateParams); Task SendAsync(string to, string templateCode, string templateParams); }
再添加实现文件SmsMessageService.cs
文件路径:D:\abp version\aspnet-zero-3.4.0\aspnet-zero-3.4.0\src\MyCompanyName.AbpZeroTemplate.Application\Authorization\Users\SmsMessageService.cs
public class SmsMessageService: ISmsMessageService { private readonly ISmsSender _smsSender; public SmsMessageService(ISmsSender smsSender) { _smsSender = smsSender; } public void Send(string to, string templateCode, string templateParams) { _smsSender.Send(to, templateCode, templateParams); } public async Task SendAsync(string to, string templateCode, string templateParams) { await _smsSender.SendAsync(to, templateCode, templateParams); } }
测试短信发送
最后,生成项目
浏览器打开:http://localhost:8088/swagger/ui/index(8088是IIS配置的端口)
找到app_smsMessageService服务进行测试
同步、异常都测试通过,至此手机短信发送模块集成完成。