瀏覽代碼

Add SmsTool

warr.qian 2 年之前
父節點
當前提交
8de7cbf5f7

+ 19 - 0
Tools/SmsTool/Models/SendSmsModel.cs

@@ -0,0 +1,19 @@
+using System.Collections.Generic;
+using System.Linq;
+
+namespace SmsTool.Models
+{
+    public class SendSmsModel
+    {
+        /// <summary>模板id</summary>
+        public string TemplateId { get; set; } = string.Empty;
+        /// <summary>发送手机号</summary>
+        public List<string> Mobiles { get; set; } = new List<string>();
+        /// <summary>发送参数</summary>
+        public List<string> Params { get; set; } = new List<string>();
+        /// <summary>短信签名</summary>
+        public string SignName { get; set; } = "杏聆荟";
+
+        public List<string> FormatterMobiles => Mobiles.Select(x => $"+86{x}").ToList();
+    }
+}

+ 17 - 0
Tools/SmsTool/Models/VerifyCodeModel.cs

@@ -0,0 +1,17 @@
+using System;
+
+namespace SmsTool.Models
+{
+    public class VerifyCodeModel
+    {
+        public string VerifyCode { get; set; }
+
+        public int ValidMinutes { get; set; }
+
+        public DateTime CreateTime { get; set; }
+
+        public DateTime OverdueTime => CreateTime.AddMinutes(ValidMinutes);
+
+        public bool IsOverdue => OverdueTime < DateTime.Now;
+    }
+}

+ 131 - 0
Tools/SmsTool/Program.cs

@@ -0,0 +1,131 @@
+using System.Collections.Concurrent;
+using SmsTool.Models;
+using SmsTool.Tencent;
+using TencentCloud.Sms.V20210111.Models;
+
+TencentHelper.Init();
+var builder = WebApplication.CreateBuilder(args);
+var port = builder.Configuration.GetSection("Sms")["Port"];
+builder.WebHost.UseUrls($"http://*:{port}");
+var app = builder.Build();
+
+ConcurrentDictionary<string, VerifyCodeModel> _mobileVerifyCodes = new ConcurrentDictionary<string, VerifyCodeModel>();
+
+
+app.MapPost("/SendVerifyCode", (string mobile,string templateId) => {
+    //var verifyCodeLength = param.GetStringValue("codeLen").ToInt();
+    var validMinutes = 10;
+
+    var verifyCode = _getVerifyCodeWithTime(mobile, validMinutes);
+    var model = new SendSmsModel
+    {
+        Mobiles = new List<string> { mobile },
+        TemplateId = templateId,
+        Params = new List<string> { verifyCode }
+    };
+    //重置密码无需传入有效时间参数
+    if (templateId == "1009241")
+    {
+        model.Params.Add(validMinutes.ToString());
+    }
+    var result = TencentHelper.SendSmsSync(model);
+    return new
+    {
+        msg = "",
+        obj = verifyCode,
+        code = _getSendSmsCode(result)
+    };
+});
+
+
+app.MapPost("/CheckVerifyCode",(string mobile, string verifyCode)=>
+{
+    var mobileVerifyCode = _getVerifyCode(mobile);
+    Console.WriteLine($"[{DateTime.Now:MM-dd HH:mm:ss}]{mobile},{verifyCode},curr:{mobileVerifyCode.VerifyCode},{mobileVerifyCode.OverdueTime:MM-dd HH:mm:ss}");
+    if (mobileVerifyCode == null || string.IsNullOrWhiteSpace(mobileVerifyCode.VerifyCode))
+    {
+        return new
+        {
+            code = 404
+        };
+    }
+    if (mobileVerifyCode.IsOverdue)
+    {
+        return new
+        {
+            code = 413
+        };
+    }
+    if (mobileVerifyCode.VerifyCode != verifyCode)
+    {
+        return new
+        {
+            code = 414
+        };
+    }
+    return new
+    {
+        code = 200
+    };
+});
+
+app.MapPost("/SendMessage", (string mobiles, string templateId, string paras)=>
+{
+    var mobileList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(mobiles);
+    var messageDatas = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(paras);
+
+    var result = TencentHelper.SendSmsSync(new SendSmsModel
+    {
+        Mobiles = mobileList,
+        TemplateId = templateId,
+        Params = messageDatas
+    });
+    return new
+    {
+        msg = "",
+        code = _getSendSmsCode(result)
+    };
+});
+
+string _getVerifyCodeWithTime(string mobile, int validMinutes)
+{
+    if (_mobileVerifyCodes.ContainsKey(mobile))
+    {
+        _mobileVerifyCodes.TryRemove(mobile, out _);
+    }
+    var mobileVerifyCode = _mobileVerifyCodes.GetOrAdd(mobile, new VerifyCodeModel
+    {
+        VerifyCode = new Random().Next(1000, 9999).ToString(),
+        ValidMinutes = validMinutes,
+        CreateTime = DateTime.Now,
+    });
+    return mobileVerifyCode.VerifyCode;
+}
+
+VerifyCodeModel _getVerifyCode(string mobile)
+{
+    if (_mobileVerifyCodes.ContainsKey(mobile))
+    {
+        return _mobileVerifyCodes[mobile];
+    }
+    return null;
+}
+
+int _getSendSmsCode(SendSmsResponse result)
+{
+    if (result == null || result.SendStatusSet == null || !result.SendStatusSet.Any())
+    {
+        return 9999;
+    }
+    if (result.SendStatusSet.Any(x => x.Code == "Ok"))
+    {
+        return 200;
+    }
+    if (result.SendStatusSet.Any(x => x.Code == "LimitExceeded.PhoneNumberDailyLimit"))
+    {
+        return 416;
+    }
+    return 9999;
+}
+
+app.Run();

+ 28 - 0
Tools/SmsTool/Properties/launchSettings.json

@@ -0,0 +1,28 @@
+{
+  "iisSettings": {
+    "windowsAuthentication": false,
+    "anonymousAuthentication": true,
+    "iisExpress": {
+      "applicationUrl": "http://localhost:4642",
+      "sslPort": 44331
+    }
+  },
+  "profiles": {
+    "SmsTool": {
+      "commandName": "Project",
+      "dotnetRunMessages": true,
+      "launchBrowser": true,
+      "applicationUrl": "https://localhost:7023;http://localhost:5111",
+      "environmentVariables": {
+        "ASPNETCORE_ENVIRONMENT": "Development"
+      }
+    },
+    "IIS Express": {
+      "commandName": "IISExpress",
+      "launchBrowser": true,
+      "environmentVariables": {
+        "ASPNETCORE_ENVIRONMENT": "Development"
+      }
+    }
+  }
+}

+ 13 - 0
Tools/SmsTool/SmsTool.csproj

@@ -0,0 +1,13 @@
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+  <PropertyGroup>
+    <TargetFramework>net6.0</TargetFramework>
+    <Nullable>enable</Nullable>
+    <ImplicitUsings>enable</ImplicitUsings>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="TencentCloudSDK" Version="3.0.655" />
+  </ItemGroup>
+
+</Project>

+ 56 - 0
Tools/SmsTool/Tencent/TencentHelper.cs

@@ -0,0 +1,56 @@
+using SmsTool.Models;
+using System;
+using TencentCloud.Common;
+using TencentCloud.Common.Profile;
+using TencentCloud.Sms.V20210111;
+using TencentCloud.Sms.V20210111.Models;
+
+namespace SmsTool.Tencent
+{
+    public class TencentHelper
+    {
+        private static SmsClient _client;
+        private static string _smsSdkAppId = "1400537314";//应用id
+
+        public static void Init()
+        {
+            var credential = new Credential
+            {
+                SecretId = "AKIDMSIsADUUpvJGwJOKvsb5IDrGtGNBRzzi",
+                SecretKey = "4sQhdJBl5HI7f3oLbZIlwqXOyILyLWP0"
+            };
+            ClientProfile clientProfile = new ClientProfile();
+            HttpProfile httpProfile = new HttpProfile();
+            httpProfile.Endpoint = ("sms.tencentcloudapi.com");
+            clientProfile.HttpProfile = httpProfile;
+            _client = new SmsClient(credential, "ap-nanjing", clientProfile);
+        }
+
+        public static SendSmsResponse SendSmsSync(SendSmsModel model)
+        {
+            try
+            {
+                SendSmsResponse resp = _client.SendSmsSync(new SendSmsRequest
+                {
+                    TemplateId = model.TemplateId,
+                    PhoneNumberSet = model.FormatterMobiles.ToArray(),
+                    TemplateParamSet = model.Params.ToArray(),
+                    SignName = model.SignName,
+                    SmsSdkAppId = _smsSdkAppId
+                });
+                //Console.WriteLine(AbstractModel.ToJsonString(resp));
+                Console.WriteLine($"[{DateTime.Now:MM-dd HH:mm:ss}]{resp.RequestId}");
+                foreach (var item in resp.SendStatusSet)
+                {
+                    Console.WriteLine($"[{DateTime.Now:MM-dd HH:mm:ss}]{item.PhoneNumber},{item.Code},{item.Message}");
+                }
+                return resp;
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine($"[{DateTime.Now:MM-dd HH:mm:ss}]templateId:{model.TemplateId},mobiles:{string.Join(";", model.Mobiles)},params:{string.Join(";", model.Params)},{ex.Message}");
+                return null;
+            }
+        }
+    }
+}

+ 12 - 0
Tools/SmsTool/appsettings.Development.json

@@ -0,0 +1,12 @@
+{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft.AspNetCore": "Warning"
+    }
+  },
+  "AllowedHosts": "*",
+  "Sms": {
+    "Port":8302
+  }
+}

+ 12 - 0
Tools/SmsTool/appsettings.json

@@ -0,0 +1,12 @@
+{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft.AspNetCore": "Warning"
+    }
+  },
+  "AllowedHosts": "*",
+  "Sms": {
+    "Port":8302
+  }
+}