ABP中有短信发送接口ISmsSender

 public interface ISmsSender
{
  Task<string> SendAsync(string number, string message);
}

使用阿里云短信服务实现这个接口,使得能够通过阿里云短信服务发送通知短信

ISmsSender一般是在Core项目中,所以实现类也放一起

首先是实现一个ISmsSender

 using Abp.Dependency;
using Castle.Core.Logging;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;
using System.Net.Http;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
using MyCompany.MyProject.Configuration;
using Microsoft.AspNetCore.Hosting; namespace MyCompany.MyProject.Identity
{
public class AliyunSmsSender : ISmsSender, ITransientDependency
{
public ILogger Logger { get; set; }
string appkey ;
string secret;
string serverUrl = "dysmsapi.aliyuncs.com";
string signName;
string TemplateCode;
private Dictionary<string, string> smsDict = new Dictionary<string, string>
{
{ "RegionId", "cn-hangzhou" },
{ "Action", "SendSms" },
{ "Version", "2017-05-25" },
};
private readonly IConfigurationRoot configuration; public AliyunSmsSender(ILogger Logger, IHostingEnvironment env)
{
configuration = env.GetAppConfiguration();
appkey = configuration["SmsConfiguration:AliSms:appkey"];
secret = configuration["SmsConfiguration:AliSms:secret"];
signName = configuration["SmsConfiguration:AliSms:SignName"];
TemplateCode = configuration["SmsConfiguration:AliSms:TemplateCode"]; smsDict.Add("SignName", signName);//签名
smsDict.Add("TemplateCode", TemplateCode);//模板
smsDict.Add("TemplateParam", "");//参数内容
smsDict.Add("PhoneNumbers", "");//发送到的手机号 }
public async Task<string> SendAsync(string number, string message)
{
try
{
smsDict["PhoneNumbers"] = number;
smsDict["TemplateParam"] = JsonConvert.SerializeObject(new { code = message });
var signatiure = new SignatureHelper();
string res = await signatiure.Request(appkey, secret, serverUrl, smsDict, logger: Logger);
Logger.Info("验证短信发送返回:" + res);
return res;
}
catch (Exception e)
{
Logger.Error(e.Message);
throw;
}
} /// <summary>
/// 签名助手
/// https://help.aliyun.com/document_detail/30079.html?spm=5176.7739992.2.3.HM7WTG
/// </summary>
public class SignatureHelper
{
private const string ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private const string ENCODING_UTF8 = "UTF-8";
public static string PercentEncode(String value)
{
StringBuilder stringBuilder = new StringBuilder();
string text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
byte[] bytes = Encoding.GetEncoding(ENCODING_UTF8).GetBytes(value);
foreach (char c in bytes)
{
if (text.IndexOf(c) >= )
{
stringBuilder.Append(c);
}
else
{
stringBuilder.Append("%").Append(
string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)c));
}
}
return stringBuilder.ToString();
}
public static string FormatIso8601Date(DateTime date)
{
return date.ToUniversalTime().ToString(ISO8601_DATE_FORMAT, CultureInfo.CreateSpecificCulture("en-US"));
} private static IDictionary<string, string> SortDictionary(Dictionary<string, string> dic)
{
IDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>(dic, StringComparer.Ordinal);
return sortedDictionary;
} public static string SignString(string source, string accessSecret)
{
using (var algorithm = new HMACSHA1())
{
algorithm.Key = Encoding.UTF8.GetBytes(accessSecret.ToCharArray());
return Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(source.ToCharArray())));
}
} public async Task<string> HttpGetAsync(string url, ILogger logger)
{
string responseBody = string.Empty;
using (var http = new HttpClient())
{
try
{
http.DefaultRequestHeaders.Add("x-sdk-client", "Net/2.0.0");
var response = await http.GetAsync(url);
response.EnsureSuccessStatusCode();
responseBody = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException !");
Console.WriteLine("Message :{0} ", e.Message);
throw;
}
}
return responseBody; } public async Task<string> Request(string accessKeyId, string accessKeySecret, string domain, Dictionary<string, string> paramsDict, ILogger logger, bool security = false)
{
var apiParams = new Dictionary<string, string>
{
{ "SignatureMethod", "HMAC-SHA1" },
{ "SignatureNonce", Guid.NewGuid().ToString() },
{ "SignatureVersion", "1.0" },
{ "AccessKeyId", accessKeyId },
{ "Timestamp", FormatIso8601Date(DateTime.Now) },
{ "Format", "JSON" },
}; foreach (var param in paramsDict)
{
if (!apiParams.ContainsKey(param.Key))
{
apiParams.Add(param.Key, param.Value);
}
}
var sortedDictionary = SortDictionary(apiParams);
string sortedQueryStringTmp = "";
foreach (var param in sortedDictionary)
{
sortedQueryStringTmp += "&" + PercentEncode(param.Key) + "=" + PercentEncode(param.Value);
} string stringToSign = "GET&%2F&" + PercentEncode(sortedQueryStringTmp.Substring());
string sign = SignString(stringToSign, accessKeySecret + "&");
string signature = PercentEncode(sign);
string url = (security ? "https" : "http") + $"://{domain}/?Signature={signature}{sortedQueryStringTmp}";
string result;
try
{
result = await HttpGetAsync(url, logger);
}
catch (Exception)
{ throw;
}
return result; }
}
}
}

然后在core项目的Mudule中配置注入关系

最后在配置文件中加上配置节点即可

"SmsConfiguration": {
"AliSms": {
"appkey": "",
"secret": "",
"SignName": "",
"TemplateCode": ""
}
}

对应上appkey secret,签名,模板code

最后在需要调用的地方注入ISmsSender, 调用其SendAsync方法,传入手机号和内容即可。

Abp 添加阿里云短信发送的更多相关文章

  1. 2018阿里云短信发送DEMO接入简单实例

    以下更新2018-04-2309:57:54 后续不再更新, 基本类: app/SignatureHelper.php <?php namespace aliyun_mns; /** * 签名助 ...

  2. spring boot集成阿里云短信发送接收短信回复功能

    1.集成阿里云通信发送短信: 在pom.xml文件里添加依赖 <!--阿里短信服务--> <dependency> <groupId>com.aliyun</ ...

  3. 阿里云短信发送服务SDK-Python3

    本文提供阿里云的短信发送服务SDK,使用Python3实现. # -*- coding: utf-8 -*- # pip install requests import requests import ...

  4. .net core 使用阿里云短信发送SMS

    阿里云官方的skd(aliyun-net-sdk-core,aliyun-net-sdk-dysmsapi)在dnc中发送短信会出错,nuget上的包貌似也一样不管用.直接改下sdk当然也可以,但就发 ...

  5. tp5阿里云短信发送

    到阿里云下载php版demo,下完整版的,不是轻量级的; 框架  :TP5 把下载下来的文件放到extend里面 文件名:alimsg 里面的文件 import('alimsg.api_demo.Sm ...

  6. java 阿里云短信发送

    记录自己的足迹,学习的路很长,一直在走着呢~ 第一步登录阿里云的控制台,找到此处: 点击之后就到此页面,如果发现账号有异常或者泄露什么,可以禁用或者删除  AccessKey: 此处方便测试,所以就新 ...

  7. ABP框架中短信发送处理,包括阿里云短信和普通短信商的短信发送集成

    在一般的系统中,往往也有短信模块的需求,如动态密码的登录,系统密码的找回,以及为了获取用户手机号码的短信确认等等,在ABP框架中,本身提供了对邮件.短信的基础支持,那么只需要根据自己的情况实现对应的接 ...

  8. 移动端获取短信验证码java实现——阿里云短信服务

    需求:移动端输入手机号,获取验证码.点击登录,验证验证码是否输入错误.是否超时等情况,一旦校验通过,将用户数据保存到数据中(业务逻辑). 前提:注册阿里用户,开通短信服务,申请key.秘钥.签名.短信 ...

  9. 浏览器端获取短信验证码java实现——阿里云短信服务

    需求:浏览器端输入手机号,获取验证码.点击登录,验证验证码是否输入错误.是否超时等情况,一旦校验通过,将用户数据保存到数据中(业务逻辑). 前提:注册阿里用户,开通短信服务,申请key.秘钥.签名.短 ...

随机推荐

  1. Hyperledger fablic 0.6 在centos7环境下的安装与部署

    原文:http://blog.csdn.net/zhaoliang1131/article/details/54617274 Hyperledger Fabric超级账本 项目约定共同遵守的 基本原则 ...

  2. cs2008中头文件交叉编译的问题

    使用全局变量 使用基类指针定义在头文件中,在实际使用中强制转型为需要的指针,当然应该也可以存为空指针.

  3. 使用hibernate validator出现

    1.javax.validation.UnexpectedTypeException: No validator could be found for type: java.lang.Integer ...

  4. mysql的简单操作

    创建数据库并设定字符集: CREATE  DATABASE hidb CHARACTER SET ‘utf8’; 使用数据库: use hidb; 删除数据库: DROP DATABASE hidb; ...

  5. java基础知识(10)---包

    包:定义包用package关键字. 1:对类文件进行分类管理. 2:给类文件提供多层名称空间. 如果生成的包不在当前目录下,需要最好执行classpath,将包所在父目录定义到classpath变量中 ...

  6. oracle sql 语句 示例

    --oracle 用户对象的导入导出 exp devimage/oracle@172.xx.x.xx/TESTDB owner='devimage' file=d:/devimage.dmp log= ...

  7. tomcat solr 限制ip

    <Context path="/solr" reloadable="false" docBase="/var/www"> < ...

  8. python 基础 字符串格式化

    print "hello %s %s" % ('wd','pc') c风格 print "hello {1} {0}".format("wd" ...

  9. javaScript之跨浏览器的事件对象

    跨浏览器的兼容代码 var eventHandler = { addHandler: function(element, type, handler){}, removeHandler: functi ...

  10. .net 缓存之文件缓存依赖

    CaCheHelp 类中代码如下: #region 根据键从缓存中读取保持的数据 /// <summary> /// 根据键从缓存中读取保持的数据 /// </summary> ...