You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
zongzhilinglan/GDZZ.Application/Help/TencentCloudSmsService.cs

96 lines
3.4 KiB

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<TencentCloudSmsService>();
}
/// <summary>
/// 发送验证码
/// </summary>
/// <param name="countryCode">电话号码</param>
/// <param name="mobile"></param>
/// <param name="code"></param>
/// <returns></returns>
public async Task<bool> 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<dynamic>(url, data);
_logger.LogDebug("Post data:\n" + JsonConvert.SerializeObject(data));
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<decimal>();
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")));
}
/// <summary>
/// 随机数
/// </summary>
/// <returns></returns>
private int GetRandom()
{
return new Random().Next(100000, 999999);
}
}
}