学无先后达者为师!
不忘初心,砥砺前行。

拒绝臃肿,一个文件搞定 C# 调用阿里云短信服务发送短信

短信发送是软件开发中的一个常见功能,在国内常用于基于短信验证码的用户注册、找回密码和操作授权等场景。阿里云的短信服务在调用时需要实现一个不是那么容易的签名算法,但如果只是为了发送短信这一个功能就去引用其提供的 SDK 显得非常不经济。同时该 SDK 并未对 .NET 5 进行适配,编译时会提示警告信息:

warning NU1701: 已使用“.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8”而不是项目目标框架“.NETStandard,Version=v2.0”还原包“BouncyCastle 1.8.6.1”。此包可能与项目不完全兼容。

为了解决上述问题,笔者参照其 SDK 实现了一个简洁版的 AliSmsSender :仅包含短信发送功能,无需依赖阿里云的 SDK ,仅需要一个文件。

public class AliSmsSender
{
    private static readonly HashSet<char> TextTable =
        new HashSet<char>("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~");

    private static readonly HttpClient HttpClient = new HttpClient();

    public AliSmsSender(string accessKeyId, string accessKeySecret, string signName)
    {
        if (string.IsNullOrWhiteSpace(accessKeyId))
        {
            throw new ArgumentNullException(nameof(accessKeyId));
        }

        if (string.IsNullOrWhiteSpace(accessKeySecret))
        {
            throw new ArgumentNullException(nameof(accessKeySecret));
        }

        if (string.IsNullOrWhiteSpace(signName))
        {
            throw new ArgumentNullException(nameof(signName));
        }

        AccessKeyId = accessKeyId;
        AccessKeySecret = accessKeySecret;
        SignName = signName;
    }

    public string AccessKeyId { get; }
    public string AccessKeySecret { get; }
    public string SignName { get; }

    public async Task<SendSmsResponse> SendAsync(string phone, string templateCode, object param)
    {
        var dictionary = new SortedDictionary<string, string>(StringComparer.Ordinal)
        {
            {"AccessKeyId", AccessKeyId},
            {"Action", "SendSms"},
            {"Format", "JSON"},
            {"PhoneNumbers", phone},
            {"SignatureMethod", "HMAC-SHA1"},
            {"SignatureNonce", Guid.NewGuid().ToString()},
            {"SignatureVersion", "1.0"},
            {"SignName", SignName},
            {"TemplateCode", templateCode},
            {"TemplateParam", JsonConvert.SerializeObject(param)},
            {"Timestamp", GetTimeStamp()},
            {"Version", "2017-05-25"}
        };
        var source = ComposeStringToSign("POST", dictionary);
        var value = SignString(source, AccessKeySecret + "&");
        dictionary.Add("Signature", value);
        using (var request = new HttpRequestMessage(
                HttpMethod.Post,
                "http://dysmsapi.aliyuncs.com"
            )
            {
                Content = new FormUrlEncodedContent(dictionary)
            }
        )
        {
            using (var response = await HttpClient.SendAsync(request))
            {
                var json = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<SendSmsResponse>(json);
            }
        }
    }

    private string SignString(string source, string accessSecret)
    {
        string result;
        using (var keyedHashAlgorithm = KeyedHashAlgorithm.Create("HMACSHA1"))
        {
            keyedHashAlgorithm.Key = Encoding.UTF8.GetBytes(accessSecret.ToCharArray());
            result = Convert.ToBase64String(
                keyedHashAlgorithm.ComputeHash(
                    Encoding.UTF8.GetBytes(
                        source.ToCharArray()
                    )
                )
            );
        }

        return result;
    }

    private string ComposeStringToSign(string method, IEnumerable<KeyValuePair<string, string>> items)
    {
        var data = ComposeStringToSign(items);
        return $"{method}&{PercentEncode("/")}&{PercentEncode(data)}";
    }

    private string ComposeStringToSign(IEnumerable<KeyValuePair<string, string>> items)
    {
        var builder = new StringBuilder();
        foreach (var item in items)
        {
            builder.Append(PercentEncode(item.Key))
                .Append('=')
                .Append(PercentEncode(item.Value))
                .Append('&');
        }

        if (builder.Length > 0)
        {
            builder.Length--;
        }

        return builder.ToString();
    }

    private string GetTimeStamp()
    {
        return DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", DateTimeFormatInfo.InvariantInfo);
    }

    private string PercentEncode(string value)
    {
        var stringBuilder = new StringBuilder();
        var bytes = Encoding.UTF8.GetBytes(value);
        foreach (var b in bytes)
        {
            var c = (char) b;
            if (TextTable.Contains(c))
            {
                stringBuilder.Append(c);
            }
            else
            {
                stringBuilder.Append('%')
                    .Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int) c));
            }
        }

        return stringBuilder.ToString();
    }

    public class SendSmsResponse
    {
        [JsonProperty("RequestId")] public string RequestId { get; set; }

        [JsonProperty("Message")] public string Message { get; set; }

        [JsonProperty("BizId")] public string BizId { get; set; }

        [JsonProperty("Code")] public string Code { get; set; }
    }
}

该实现依赖 Newtonsoft.Json 做 Json 反序列化,同时需要引入以下命名空间:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

使用时,先用阿里云提供的访问密钥及签名信息构造 AliSmsSender 的实例,并调用其 SendAsync 方法即可:

var sender = new AliSmsSender("accessKeyId", "accessKeySecret", "签名");
var result = await sender.SendAsync("13888888888", "模板Code", new { arg = "模板参数值" });
if (result.Code == "OK")
{
	Console.WriteLine("发送成功");
}
else
{
	Console.WriteLine("发送失败:{0}", result.Code);
}

以上代码也可以在 GitHub 上获得,查看地址:

https://gist.github.com/Soar360/18b9fea0ad08e5068e1e072ee4a21aa9

赞(11) 打赏
未经允许不得转载:码农很忙 » 拒绝臃肿,一个文件搞定 C# 调用阿里云短信服务发送短信

评论 抢沙发

给作者买杯咖啡

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册