腾讯云短信服务使用记录与.NET Core C#代码分享

2021-05-01 15:26

阅读:560

标签:腾讯云   success   extend   ram   针对   readasa   obj   als   ilo   

1、即使是相同的短信签名与短信正文模板,也需要针对“国内文本短信”与“海外文本短信”分别申请。开始不知道,以为只要申请一次,给国外手机发短信时给api传对应的国家码就行,后来才发现需要分别申请。

2、短信服务web api响应“手机号内容频率限制”错误。这是由于在30秒内向同一手机号多次发送了相同内容的短信,这是腾讯云短信服务的默认限制——“相同内容短信对同一个手机号,30秒内发送短信条数不超过1条”,可以通过“应用配置”的“短信频率配置”修改这个限制。

3、腾讯云短信服务没有提供 .NET Core 的 SDK,我们自己实现的代码如下:

public class TencentCloudSmsService : ISmsService
{
    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 Taskbool> 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.PostAsJsonAsyncdynamic>(url, data);
        _logger.LogDebug("Post data:\n" + JsonConvert.SerializeObject(data));
        response.EnsureSuccessStatusCode();

        var result = await response.Content.ReadAsAsyncdynamic>();
        if(result.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);
    }
}

腾讯云短信服务使用记录与.NET Core C#代码分享

标签:腾讯云   success   extend   ram   针对   readasa   obj   als   ilo   

原文地址:http://www.cnblogs.com/dudu/p/7782376.html


评论


亲,登录后才可以留言!