【分享】调用TX云短信平台发送短信API调用代码原创
金蝶云社区-湖南客户成功吴双得
湖南客户成功吴双得
81人赞赏了该文章 273次浏览 未经作者许可,禁止转载编辑于2024年05月31日 09:27:39

前几天做了个调用TX云短信平台接口发短信的小开发,TX建议用SDK,但SDK太大,且使用的Newtonsoft.Json.dll 版本需要是 13.0以上,但金蝶云星空安装目录下是 4.0,不适合这样处理。只能使用http调用接口。

TXAPI接口生成的http模式调用代码在 .net 4.5 下报错。所以通过修改后得以下代码,分享记录。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Net.Http;

namespace SyncBillToTencentCloud
{
    public class TencentSMS
    {

        public static string DoRequest(string secretId, string secretKey, string host, string body, string action, string region)
        {
            string token = "";
            string service = "sms";
            string version = "2021-01-11";
            using (HttpClient Client = new HttpClient())
            {
                var request = BuildRequest(secretId, secretKey, host, service, version, action, body, region, token);
                HttpResponseMessage response = Client.SendAsync(request).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

        private static HttpRequestMessage BuildRequest(
            string secretId, string secretKey, string host,
            string service, string version, string action,
            string body, string region, string token
        )
        {
            var url = "" + host;
            var contentType = "application/json; charset=utf-8";
            var timestamp = ((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString();
            var auth = GetAuth(secretId, secretKey, host, contentType, timestamp, body);
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Post;
            request.Headers.Add("Host", host);
            request.Headers.Add("X-TC-Timestamp", timestamp);
            request.Headers.Add("X-TC-Version", version);
            request.Headers.Add("X-TC-Action", action);
            request.Headers.Add("X-TC-Region", region);
            request.Headers.Add("X-TC-Token", token);
            request.Headers.Add("X-TC-RequestClient", "SDK_NET_BAREBONE");
            request.Headers.TryAddWithoutValidation("Authorization", auth);
            // request.Headers.Authorization = new AuthenticationHeaderValue(auth);
            request.RequestUri = new Uri(url);
            request.Content = new StringContent(body, Encoding.UTF8, "application/json");// MediaTypeWithQualityHeaderValue.Parse(contentType));

            //request.Content = new StringContent(body, MediaTypeWithQualityHeaderValue.Parse(contentType));
            Console.WriteLine(request);
            return request;
        }

        private static string GetAuth(
            string secretId, string secretKey, string host, string contentType,
            string timestamp, string body
        )
        {
            var canonicalURI = "/";
            var canonicalHeaders = "content-type:" + contentType + "\nhost:" + host + "\n";
            var signedHeaders = "content-type;host";
            var hashedRequestPayload = Sha256Hex(body);
            var canonicalRequest = "POST" + "\n"
                                          + canonicalURI + "\n"
                                          + "\n"
                                          + canonicalHeaders + "\n"
                                          + signedHeaders + "\n"
                                          + hashedRequestPayload;

            var algorithm = "TC3-HMAC-SHA256";
            var date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(int.Parse(timestamp))
                .ToString("yyyy-MM-dd");
            var service = host.Split('.')[0];
            var credentialScope = date + "/" + service + "/" + "tc3_request";
            var hashedCanonicalRequest = Sha256Hex(canonicalRequest);
            var stringToSign = algorithm + "\n"
                                         + timestamp + "\n"
                                         + credentialScope + "\n"
                                         + hashedCanonicalRequest;

            var tc3SecretKey = Encoding.UTF8.GetBytes("TC3" + secretKey);
            var secretDate = HmacSha256(tc3SecretKey, Encoding.UTF8.GetBytes(date));
            var secretService = HmacSha256(secretDate, Encoding.UTF8.GetBytes(service));
            var secretSigning = HmacSha256(secretService, Encoding.UTF8.GetBytes("tc3_request"));
            var signatureBytes = HmacSha256(secretSigning, Encoding.UTF8.GetBytes(stringToSign));
            var signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower();

            return algorithm + " "
                             + "Credential=" + secretId + "/" + credentialScope + ", "
                             + "SignedHeaders=" + signedHeaders + ", "
                             + "Signature=" + signature;
        }

        private static string Sha256Hex(string s)
        {
            using (SHA256 algo = SHA256.Create())
            {
                byte[] hashbytes = algo.ComputeHash(Encoding.UTF8.GetBytes(s));
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < hashbytes.Length; ++i)
                {
                    builder.Append(hashbytes[i].ToString("x2"));
                }

                return builder.ToString();
            }
        }

        private static byte[] HmacSha256(byte[] key, byte[] msg)
        {
            using (HMACSHA256 mac = new HMACSHA256(key))
            {
                return mac.ComputeHash(msg);
            }
        }
    }
}

调用代码

static void Main(string[] args)
        {
            var secretId = "";
            var secretKey = "";
            var host = "";
            var body = "{\"PhoneNumberSet\":[\"+\"],\"SmsSdkAppId\":\"应用ID\",\"SignName\":\"签名\",\"TemplateId\":\"模板ID\",\"TemplateParamSet\":[\"1\",\"2\",\"3数量\",\"4单据\",\"5\",\"6\"]}";
            var region = "ap-guangzhou";
            string action = "SendSms";
            var resp = TencentSMS.DoRequest(secretId, secretKey, host, body, action, region);
            

            Console.WriteLine(resp);
        }


赞 81