Abp 添加阿里云短信发送
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 添加阿里云短信发送的更多相关文章
- 2018阿里云短信发送DEMO接入简单实例
以下更新2018-04-2309:57:54 后续不再更新, 基本类: app/SignatureHelper.php <?php namespace aliyun_mns; /** * 签名助 ...
- spring boot集成阿里云短信发送接收短信回复功能
1.集成阿里云通信发送短信: 在pom.xml文件里添加依赖 <!--阿里短信服务--> <dependency> <groupId>com.aliyun</ ...
- 阿里云短信发送服务SDK-Python3
本文提供阿里云的短信发送服务SDK,使用Python3实现. # -*- coding: utf-8 -*- # pip install requests import requests import ...
- .net core 使用阿里云短信发送SMS
阿里云官方的skd(aliyun-net-sdk-core,aliyun-net-sdk-dysmsapi)在dnc中发送短信会出错,nuget上的包貌似也一样不管用.直接改下sdk当然也可以,但就发 ...
- tp5阿里云短信发送
到阿里云下载php版demo,下完整版的,不是轻量级的; 框架 :TP5 把下载下来的文件放到extend里面 文件名:alimsg 里面的文件 import('alimsg.api_demo.Sm ...
- java 阿里云短信发送
记录自己的足迹,学习的路很长,一直在走着呢~ 第一步登录阿里云的控制台,找到此处: 点击之后就到此页面,如果发现账号有异常或者泄露什么,可以禁用或者删除 AccessKey: 此处方便测试,所以就新 ...
- ABP框架中短信发送处理,包括阿里云短信和普通短信商的短信发送集成
在一般的系统中,往往也有短信模块的需求,如动态密码的登录,系统密码的找回,以及为了获取用户手机号码的短信确认等等,在ABP框架中,本身提供了对邮件.短信的基础支持,那么只需要根据自己的情况实现对应的接 ...
- 移动端获取短信验证码java实现——阿里云短信服务
需求:移动端输入手机号,获取验证码.点击登录,验证验证码是否输入错误.是否超时等情况,一旦校验通过,将用户数据保存到数据中(业务逻辑). 前提:注册阿里用户,开通短信服务,申请key.秘钥.签名.短信 ...
- 浏览器端获取短信验证码java实现——阿里云短信服务
需求:浏览器端输入手机号,获取验证码.点击登录,验证验证码是否输入错误.是否超时等情况,一旦校验通过,将用户数据保存到数据中(业务逻辑). 前提:注册阿里用户,开通短信服务,申请key.秘钥.签名.短 ...
随机推荐
- Maven 排除依赖jar包
当我们引入第三方jar包的时候,难免会引入传递性依赖,有些时候这是好事,然而有些时候我们不需要其中的一些传递性依赖 比如我们不想引入传递性依赖commons-logging,我们可以使用exclusi ...
- python为类定义构造函数
用python进行OO编程时, 经常会用到类的构造函数来初始化一些变量. class FileData: def __init__(self, data, name, type): ...
- libvirt, libvirt-python, libvirtd 关系浅析
libvirt 官方解释: http://libvirt.org/ 见分隔线以下. 我的理解:libvirt 作为一个中间层,封装了对下层虚拟化 hypervisor 的操作方法.也就是说,无论你是 ...
- openstackM版本安装
部署期间常见问题:http://www.cnblogs.com/bfmq/p/6001233.html,问题跟对架构的理解永远比部署重要!你玩技术是绝对是要基于理论的 一.基本情况:物理设备:4台惠普 ...
- 【转载】ruby 中数组函数示例(1)(转)
函数名称 说明 示例 & 数组与,返回两数组的交集 [1,2] & [2,3] =>[2] * 复制数组n次 [1,2]*2 => [1,2,1, ...
- java数据结构读书笔记--引论
1 递归简论 需求:求出f(x)=2f(x-1)+x²的值.满足f(0)=0 public class Recursion { // 需求: 求出f(x)=2f(x-1)+x²的值.满足f(0)=0 ...
- JavaScript学习系列2一JavaScript中的变量作用域
在写这篇文章之前,再次提醒一下 JavaScript 是大小写敏感的语言 // 'test', 'Test', 'TeSt' , 'TEST' 是4个不同的变量名 JavaScript中的变量,最重要 ...
- POJ 1601 拓展欧几里得算法
学习链接:http://www.cnblogs.com/frog112111/archive/2012/08/19/2646012.html 先来学习一下什么是欧几里得算法: 欧几里得原理是:两个整数 ...
- bzoj 3123: [Sdoi2013]森林(45分暴力)
3123: [Sdoi2013]森林 Time Limit: 20 Sec Memory Limit: 512 MBSubmit: 4184 Solved: 1235[Submit][Status ...
- JS滑动下划线导航菜单实现原理
效果如下:http://campus.51job.com/test/zengxl/js html: <div class="mainnav"> <div clas ...