using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Linq; using System.Net.Http; using System.Net.Http.Json; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace GDZZ.Application.Help { public class TencentCloudSmsService { private static readonly HttpClient _httpClient = new HttpClient { BaseAddress = new Uri("https://yun.tim.qq.com") }; private readonly string _appId; private readonly string _appKey; private const string SIGNATURE = "..."; private const int DOMESTIC_TEMPLATE_ID = 1234; private const int OVERSEA_TEMPLATE_ID = 5678; private readonly ILogger _logger; public TencentCloudSmsService(IConfiguration conf, ILoggerFactory loggerFactory) { _appId = conf["tencentCloudSms:appId"]; if (string.IsNullOrEmpty(_appId)) throw new ArgumentException($"{nameof(_appId)} must have a value"); _appKey = conf["tencentCloudSms:appKey"]; if (string.IsNullOrEmpty(_appKey)) throw new ArgumentException($"{nameof(_appKey)} must have a value"); _logger = loggerFactory.CreateLogger(); } /// /// 发送验证码 /// /// 电话号码 /// /// /// public async Task SendCode(string countryCode, long mobile, int code) { var random = GetRandom(); var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds(); var data = new { tel = new { nationcode = countryCode.Replace("+", ""), mobile = mobile.ToString() }, sign = SIGNATURE, tpl_id = countryCode == "+86" ? DOMESTIC_TEMPLATE_ID : OVERSEA_TEMPLATE_ID, @params = new[] { code.ToString() }, sig = ComputeSignature(mobile, random, timestamp), time = timestamp, extend = "", ext = "" }; var url = $"/v5/tlssmssvr/sendsms?sdkappid={_appId}&random={random}"; _logger.LogDebug("Post to " + _httpClient.BaseAddress + url); var response = await _httpClient.PostAsJsonAsync(url, data); _logger.LogDebug("Post data:\n" + JsonConvert.SerializeObject(data)); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadFromJsonAsync(); if (result != 0) { //_logger.LogError($"Failed to send message to {countryCode}-{mobile}: {result.errmsg}"); return false; } return true; } private string ComputeSignature(long mobile, int random, long timestamp) { var input = $"appkey={_appKey}&random={random}&time={timestamp}&mobile={mobile}"; var hasBytes = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(input)); return string.Join("", hasBytes.Select(b => b.ToString("x2"))); } /// /// 随机数 /// /// private int GetRandom() { return new Random().Next(100000, 999999); } } }