sunpengfei
2025-08-18 ab92e760e8461f0a48b37786b0f5a78db744dca6
FlexJobApi.Core/Utils/SmsUtils/AliyunSmsUtils.cs
@@ -17,16 +17,13 @@
    {
        private readonly IOptions<AliyunOptions> options;
        private readonly IHttpRemoteService httpRemoteService;
        private readonly IHttpContextAccessor httpContextAccessor;
        public AliyunSmsUtils(
            IOptions<AliyunOptions> options,
            IHttpRemoteService httpRemoteService,
            IHttpContextAccessor httpContextAccessor)
            IHttpRemoteService httpRemoteService)
        {
            this.options = options;
            this.httpRemoteService = httpRemoteService;
            this.httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
@@ -38,75 +35,72 @@
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        /// <exception cref="Oops"></exception>
        //public async Task SendAsync(string phoneNumber, EnumSmsTemplateType templateCode, string templateParam, CancellationToken cancellationToken)
        //{
        //    if (options.Value.Sms?.Enable != true)
        //    {
        //        httpContextAccessor.AddAdditionalData("TemplateParam", templateParam);
        //        return;
        //    }
        //    if (options.Value.Sms != null
        //        && options.Value.Sms.Version.IsNotNull()
        //        && options.Value.Sms.RegionId.IsNotNull()
        //        && options.Value.Sms.SignName.IsNotNull()
        //        && options.Value.AccessKeyId.IsNotNull()
        //        && options.Value.AccessKeySecret.IsNotNull())
        //    {
        //        var _templateCode = options.Value.Sms.TemplateCodes[templateCode.ToString()];
        //        var _params = new Dictionary<string, string>
        //        {
        //            {"Action", "SendSms"},
        //            {"Version", options.Value.Sms.Version},
        //            {"RegionId", options.Value.Sms.RegionId},
        //            {"PhoneNumbers", phoneNumber},
        //            {"SignName", options.Value.Sms.SignName},
        //            {"TemplateCode",  _templateCode}
        //        };
        //        if (!string.IsNullOrWhiteSpace(templateParam))
        //        {
        //            _params.Add("TemplateParam", templateParam);
        //        }
        //        var timestamp = DateTime.Now.ToUniversalTime()
        //            .ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.CreateSpecificCulture("en-US"));
        public async Task SendAsync(string phoneNumber, EnumSmsTemplateCode templateCode, string templateParam, CancellationToken cancellationToken)
        {
            if (options.Value.SMS?.Enable != true)
            {
                return;
            }
            if (options.Value.SMS != null
                && options.Value.SMS.Version.IsNotNull()
                && options.Value.SMS.RegionId.IsNotNull()
                && options.Value.SMS.SignName.IsNotNull()
                && options.Value.SMS.AccessKeyId.IsNotNull()
                && options.Value.SMS.AccessSecret.IsNotNull())
            {
                var _templateCode = options.Value.SMS.TemplateCodes[templateCode.ToString()];
                var _params = new Dictionary<string, string>
                {
                    {"Action", "SendSms"},
                    {"Version", options.Value.SMS.Version},
                    {"RegionId", options.Value.SMS.RegionId},
                    {"PhoneNumbers", phoneNumber},
                    {"SignName", options.Value.SMS.SignName},
                    {"TemplateCode",  _templateCode}
                };
                if (!string.IsNullOrWhiteSpace(templateParam))
                {
                    _params.Add("TemplateParam", templateParam);
                }
                var timestamp = DateTime.Now.ToUniversalTime()
                    .ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.CreateSpecificCulture("en-US"));
        //        _params.Add("AccessKeyId", options.Value.AccessKeyId);
        //        _params.Add("Timestamp", timestamp);
        //        _params.Add("Format", "JSON");
        //        _params.Add("SignatureMethod", "HMAC-SHA1");
        //        _params.Add("SignatureVersion", "1.0");
        //        _params.Add("SignatureNonce", Guid.NewGuid().ToString());
                _params.Add("AccessKeyId", options.Value.SMS.AccessKeyId);
                _params.Add("Timestamp", timestamp);
                _params.Add("Format", "JSON");
                _params.Add("SignatureMethod", "HMAC-SHA1");
                _params.Add("SignatureVersion", "1.0");
                _params.Add("SignatureNonce", Guid.NewGuid().ToString());
        //        //排序
        //        var sortDic = new SortedDictionary<string, string>(_params, StringComparer.Ordinal);
                //排序
                var sortDic = new SortedDictionary<string, string>(_params, StringComparer.Ordinal);
        //        //生成Url参数
        //        var urlParams = "";
        //        foreach (var dic in sortDic)
        //        {
        //            urlParams += $"{PercentEncode(dic.Key)}={PercentEncode(dic.Value)}&";
        //        }
        //        urlParams = urlParams.TrimEnd('&');
                //生成Url参数
                var urlParams = "";
                foreach (var dic in sortDic)
                {
                    urlParams += $"{PercentEncode(dic.Key)}={PercentEncode(dic.Value)}&";
                }
                urlParams = urlParams.TrimEnd('&');
        //        //签名
        //        var stringToSign = $"GET&{PercentEncode("/")}&{PercentEncode(urlParams)}";
        //        string signature = PercentEncode(ToHmacsha1(stringToSign, options.Value.AccessKeySecret + "&"));
                //签名
                var stringToSign = $"GET&{PercentEncode("/")}&{PercentEncode(urlParams)}";
                string signature = PercentEncode(ToHmacsha1(stringToSign, options.Value.SMS.AccessSecret + "&"));
        //        var req = $"http://dysmsapi.aliyuncs.com/?Signature={signature}&{urlParams}"
        //            .SetMethod(HttpMethod.Get);
        //        var res = await http.SendAsync(req, cancellationToken);
        //        var callback = res.Callback?.JsonTo(new
        //        {
        //            Code = "",
        //            Message = "",
        //            RequestId = "",
        //            BizId = ""
        //        });
        //        if (callback == null || callback.Code != "OK")
        //        {
        //            throw new Oops(FriendlyCallbackCode.Error, "发送短信失败", $"发送短信异常:{callback?.Message}");
        //        }
        //    }
        //}
                var res = await httpRemoteService.GetAsStringAsync($"http://dysmsapi.aliyuncs.com/?Signature={signature}&{urlParams}");
                var callback = res.JsonTo(new
                {
                    Code = "",
                    Message = "",
                    RequestId = "",
                    BizId = ""
                });
                if (callback == null || callback.Code != "OK")
                {
                    throw Oops.Oh(EnumErrorCodeType.s510, $"发送短信失败:{callback?.Message},请联系管理员");
                }
            }
        }
        /// <summary>
        /// 排除敏感字符串