using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; namespace Infrastructure.Sms { public class NetEasySmsSender : ISmsSender { private readonly ILogger _logger; private readonly Uri _appUrl; private readonly string _appKey; private readonly string _appSecret; private readonly IHttpClientFactory _httpClientFactory; public NetEasySmsSender(ILogger logger, IConfiguration configuration, IHttpClientFactory httpClientFactory) { if (configuration is null) { throw new ArgumentNullException(nameof(configuration)); } this._logger = logger; this._appUrl = new Uri(configuration.GetSection("sms").GetValue("url")); this._appKey = configuration.GetSection("sms").GetValue("key"); this._appSecret = configuration.GetSection("sms").GetValue("secret"); this._httpClientFactory = httpClientFactory; } public void Send(string number, out string code) { try { #pragma warning disable CA2000 // 丢失范围之前释放对象 var client = this._httpClientFactory.CreateClient(); #pragma warning restore CA2000 // 丢失范围之前释放对象 var formData = new List> { new KeyValuePair("AppKey", this._appKey), new KeyValuePair("Nonce", Guid.NewGuid().ToString()) }; var seconds = ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds).ToString(CultureInfo.InvariantCulture); formData.Add(new KeyValuePair("CurTime", seconds)); var sumValue = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", this._appSecret, formData[1].Value, formData[2].Value); var sumBytes = Encoding.UTF8.GetBytes(sumValue); #pragma warning disable CA5350 // 不要使用弱加密算法 using var sha1 = SHA1.Create(); #pragma warning restore CA5350 // 不要使用弱加密算法 var sumHash = sha1.ComputeHash(sumBytes); var hashValue = string.Empty; var builder = new StringBuilder(); builder.Append(hashValue); foreach (var item in sumHash) { builder.Append(item.ToString("x2", CultureInfo.InvariantCulture)); } hashValue = builder.ToString(); formData.Add(new KeyValuePair("CheckSum", hashValue)); using var content = new FormUrlEncodedContent(new List> { new KeyValuePair("mobile", number) }); foreach (var item in formData) { content.Headers.Add(item.Key, item.Value); } content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" }; var task = client.PostAsync(this._appUrl, content); task.Wait(); var result = task.Result; var responseContent = result.Content.ReadAsStringAsync().Result; var returnModel = new { code = "", msg = "", obj = "" }; returnModel = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(responseContent, returnModel); code = returnModel.obj; } catch (Exception ex) { this._logger.LogError(ex.Message); code = string.Empty; } } } }