Updated on 2024-07-03 GMT+08:00

C#

Example

Sending SMSs (Example 1), Sending SMSs in Batches (Example 1)

Sending SMSs (Example 2), Sending SMSs in Batches (Example 2)

Receiving Status Reports

Environment

Example 1: .NET Core 2.0 or later, or .NET Framework 4.6 or later

Example 2: .NET Core 1.0 or later, or .NET Framework 2.0 or later

Library

For Newtonsoft.Json 11.0.2 and later versions, see https://www.newtonsoft.com/json.

  • Sending SMSs shows an example of sending group SMSs with a single template. Sending SMSs in batches shows an example of sending group SMSs with multiple templates.
  • The examples described in this document may involve the use of personal data. You are advised to comply with relevant laws and regulations and take measures to ensure that personal data is fully protected.
  • The examples described in this document are for demonstration purposes only. Commercial use of the examples is prohibited.
  • Information in this document is for your reference only. It does not constitute any offer or commitment.

Sending SMSs (Example 1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace msgsms_csharp_demo
{
    class SendSms
    {
        static void Main(string[] args)
        {
           // Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation.
            string apiAddress = "https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendSms/v1"; // Application access address and API access URI
            // Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables.
            string appKey = "c8RWg3ggEcyd4D3p94bf3Y7x1Ile"; //Application Key
            string appSecret = "q4Ii87Bh************80SfD7Al"; //Application Secret
            string sender = "csms12345678"; // Channel number for Chinese mainland SMS or international SMS
            string templateId = "8ff55eac1d0b478ab3c06c3c6a492300"; // Template ID

            // Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template.
            // This parameter is not required for international SMS.
            //string signature = "Huawei Cloud SMS test"; // Signature

          // Mandatory. Global number format (including the country code), for example, +8615123456789. Use commas (,) to separate multiple numbers.
            string receiver = "+8615123456789,+8615234567890"; // Recipient numbers

            // Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports.
            string statusCallBack = "";

            /*
             * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, string templateParas = "";
              * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to "[\"369751\"]".
              * Example of a dual-variable template: If the template content is "You have ${NUM_2} delivered to ${TXT_20}", templateParas can be set to "[\"3\",\"main gate of People's Park\"]".
             * For details, see Template and Variable Specifications.
             */
            string templateParas = "[\"369751\"]"; // Template variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569).

            try
            {
               // Ignore the certificate trust issues to prevent API calling failures caused by HTTPS certificate authentication failures.
                HttpClient client = new HttpClient();
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                // Request headers
                client.DefaultRequestHeaders.Add("Authorization", "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"");
                client.DefaultRequestHeaders.Add("X-WSSE", BuildWSSEHeader(appKey, appSecret));
                // Request body
                var body = new Dictionary<string, string>() {
                    {"from", sender},
                    {"to", receiver},
                    {"templateId", templateId},
                    {"templateParas", templateParas},
                    {"statusCallback", statusCallBack},
                    //{"signature", signature} // Uncomment this line if the universal template for Chinese mainland SMS is used.
                };

                HttpContent content = new FormUrlEncodedContent(body);

                var response = client.PostAsync(apiAddress, content).Result;
                Console.WriteLine(response.StatusCode); // Record the result code of the response.
                var res = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(res); //Record the response.
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.Message);
            }
        }

        /// <summary>
       /// Construct the value of X-WSSE.
        /// </summary>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        static string BuildWSSEHeader(string appKey, string appSecret)
        {
            string now = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); //Created
            string nonce = Guid.NewGuid().ToString().Replace("-", ""); //Nonce

            byte[] material = Encoding.UTF8.GetBytes(nonce + now + appSecret);
            byte[] hashed = SHA256Managed.Create().ComputeHash(material);
            string hexdigest = BitConverter.ToString(hashed).Replace("-", "");
            string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(hexdigest)); //PasswordDigest

            return String.Format("UsernameToken Username=\"{0}\",PasswordDigest=\"{1}\",Nonce=\"{2}\",Created=\"{3}\"",
                            appKey, base64, nonce, now);
        }
    }
}

Sending SMSs (Example 2)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace msgsms_csharp_demo
{
    class SendSms
    {
        static void Main(string[] args)
        {
           // Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation.
            string apiAddress = "https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendSms/v1"; // Application access address and API access URI
            // Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables.
            string appKey = "c8RWg3ggEcyd4D3p94bf3Y7x1Ile"; //Application&nbsp;Key
            string appSecret = "q4Ii87Bh************80SfD7Al"; //Application&nbsp;Secret
            string sender = "csms12345678"; // Channel number for Chinese mainland SMS or international SMS
            string templateId = "8ff55eac1d0b478ab3c06c3c6a492300"; // Template ID

            // Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template.
            // This parameter is not required for international SMS.
            //string signature = "Huawei Cloud SMS test"; // Signature

          // Mandatory. Global number format (including the country code), for example, +8615123456789. Use commas (,) to separate multiple numbers.
            string receiver = "+8615123456789,+8615234567890"; // Recipient numbers

            // Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports.
            string statusCallBack = "";

            /*
             * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, string templateParas = "";
              * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to "[\"369751\"]".
              * Example of a dual-variable template: If the template content is "You have ${NUM_2} delivered to ${TXT_20}", templateParas can be set to "[\"3\",\"main gate of People's Park\"]".
             * For details, see Template and Variable Specifications.
             */
            string templateParas = "[\"369751\"]"; // Template variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569).

            try
            {
               // Ignore the certificate trust issues to prevent API calling failures caused by HTTPS certificate authentication failures.
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                // Set the security protocol type to 3072 to use TLS 1.2.
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)3072;

                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(apiAddress);
                // Request method
                myReq.Method = "POST";
                // Request headers
                myReq.ContentType = "application/x-www-form-urlencoded";
                myReq.Headers.Add("Authorization", "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"");
                myReq.Headers.Add("X-WSSE", BuildWSSEHeader(appKey, appSecret));
                // Request body
                NameValueCollection keyValues = new NameValueCollection
                {
                    {"from", sender},
                    {"to", receiver},
                    {"templateId", templateId},
                    {"templateParas", templateParas},
                    {"statusCallback", statusCallBack},
                    //{"signature", signature} // Uncomment this line if the universal template for Chinese mainland SMS is used.
                };
                string body = BuildQueryString(keyValues);

                // Send request data.
                StreamWriter req = new StreamWriter(myReq.GetRequestStream());
                req.Write(body);
                req.Close();

                // Obtain response data.
                HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
                StreamReader resp = new StreamReader(myResp.GetResponseStream());
                string result = resp.ReadToEnd();
                myResp.Close();
                resp.Close();

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.Message);
            }
        }

        /// <summary>
       /// Construct the value of X-WSSE.
        /// </summary>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        static string BuildWSSEHeader(string appKey, string appSecret)
        {
            string now = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); //Created
            string nonce = Guid.NewGuid().ToString().Replace("-", ""); //Nonce

            byte[] material = Encoding.UTF8.GetBytes(nonce + now + appSecret);
            byte[] hashed = SHA256Managed.Create().ComputeHash(material);
            string hexdigest = BitConverter.ToString(hashed).Replace("-", "");
            string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(hexdigest)); //PasswordDigest

            return String.Format("UsernameToken Username=\"{0}\",PasswordDigest=\"{1}\",Nonce=\"{2}\",Created=\"{3}\"",
                            appKey, base64, nonce, now);
        }

        /// <summary>
        /// Construct the request body.
        /// </summary>
        /// <param name="keyValues"></param>
        /// <returns></returns>
        static string BuildQueryString(NameValueCollection keyValues)
        {
            StringBuilder temp = new StringBuilder();
            foreach (string item in keyValues.Keys)
            {
                temp.Append(item).Append("=").Append(HttpUtility.UrlEncode(keyValues.Get(item))).Append("&");
            }
            return temp.Remove(temp.Length - 1, 1).ToString();
        }
    }
}

Sending SMSs in Batches (Example 1)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;

namespace msgsms_csharp_demo
{
    class SendDiffSms
    {
        static void Main(string[] args)
        {
           // Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation.
            string apiAddress = "https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendDiffSms/v1"; // Application access address and API access URI
            // Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables.
            string appKey = "c8RWg3ggEcyd4D3p94bf3Y7x1Ile"; //Application&nbsp;Key
            string appSecret = "q4Ii87Bh************80SfD7Al"; //Application&nbsp;Secret
            string sender = "csms12345678"; // Channel number for Chinese mainland SMS or international SMS
            string templateId_1 = "979b639cbd0b4b6b88e0fd5de4ad6f85"; // Template ID 1
            string templateId_2 = "979b639cbd0b4b6b88e0fd5de4ad6f85"; // Template ID 2

            // Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template.
            // This parameter is not required for international SMS.
            string signature_1 = "Huawei Cloud SMS test"; // Signature 1
            string signature_2 = "Huawei Cloud SMS test"; // Signature 2

          // Mandatory. Global number format (including the country code), for example, +8615123456789. Use commas (,) to separate multiple numbers.
            string[] receiver_1 = { "+8615123456789", "+8615234567890" }; // Recipient number of template 1
            string[] receiver_2 = { "+8615123456789", "+8615234567890" }; // Recipient number of template 2

            // Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports.
            string statusCallBack = "";

            /*
             * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, string[] templateParas = {};
            * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to ["369751"].
             * Example of a dual-variable template: If the template content is "You have ${NUM_2} delivered to ${TXT_20}", templateParas can be set to {"3","main gate of People's Park"}.
             * For details, see Template and Variable Specifications.
             */
            string[] templateParas_1 = { "123456" }; // Template 1 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569).
            string[] templateParas_2 = { "234567" }; // Template 2 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569).

            ArrayList smsContent = new ArrayList
            {
            // smsContent. If the signature name is not required, set signature to null.
                InitDiffSms(receiver_1, templateId_1, templateParas_1, signature_1),
                InitDiffSms(receiver_2, templateId_2, templateParas_2, signature_2)
            };

            try
            {
               // Ignore the certificate trust issues to prevent API calling failures caused by HTTPS certificate authentication failures.
                HttpClient client = new HttpClient();
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                // Request headers
                client.DefaultRequestHeaders.Add("Authorization", "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"");
                client.DefaultRequestHeaders.Add("X-WSSE", BuildWSSEHeader(appKey, appSecret));
                // Request body
                var body = new Dictionary<string, object>{
                    {"from", sender},
                    {"statusCallback", statusCallBack},
                    {"smsContent", smsContent}
                };

                HttpContent content = new StringContent(JsonConvert.SerializeObject(body));
                // Content-Type in the request headers
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                var response = client.PostAsync(apiAddress, content).Result;
                Console.WriteLine(response.StatusCode); // Record the result code of the response.
                var res = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(res); //Record the response.
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.Message);
            }
        }

        /// <summary>
       /// Construct the value of smsContent.
        /// </summary>
        /// <param name="receiver"></param>
        /// <param name="templateId"></param>
        /// <param name="templateParas"></param>
        ///<param name="signature">Signature name, which must be specified when the universal template for Chinese mainland SMS is used.</param>
        /// <returns></returns>
        static Dictionary<string, object> InitDiffSms(string[] receiver, string templateId, string[] templateParas, string signature)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>
            {
                {"to", receiver},
                {"templateId", templateId},
                {"templateParas", templateParas}
            };
            if (!signature.Equals(null) && signature.Length > 0)
            {
                dic.Add("signature", signature);
            }

            return dic;
        }

        /// <summary>
       /// Construct the value of X-WSSE.
        /// </summary>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        static string BuildWSSEHeader(string appKey, string appSecret)
        {
            string now = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); //Created
            string nonce = Guid.NewGuid().ToString().Replace("-", ""); //Nonce

            byte[] material = Encoding.UTF8.GetBytes(nonce + now + appSecret);
            byte[] hashed = SHA256Managed.Create().ComputeHash(material);
            string hexdigest = BitConverter.ToString(hashed).Replace("-", "");
            string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(hexdigest)); //PasswordDigest

            return String.Format("UsernameToken Username=\"{0}\",PasswordDigest=\"{1}\",Nonce=\"{2}\",Created=\"{3}\"",
                            appKey, base64, nonce, now);
        }
    }
}

Sending SMSs in Batches (Example 2)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace msgsms_csharp_demo
{
    class SendDiffSms
    {
        static void Main(string[] args)
        {
           // Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation.
            string apiAddress = "https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendDiffSms/v1"; // Application access address and API access URI
            // Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables.
            string appKey = "c8RWg3ggEcyd4D3p94bf3Y7x1Ile"; //Application&nbsp;Key
            string appSecret = "q4Ii87Bh************80SfD7Al"; //Application&nbsp;Secret
            string sender = "csms12345678"; // Channel number for Chinese mainland SMS or international SMS
            string templateId_1 = "979b639cbd0b4b6b88e0fd5de4ad6f85"; // Template ID 1
            string templateId_2 = "979b639cbd0b4b6b88e0fd5de4ad6f85"; // Template ID 2

            // Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template.
            // This parameter is not required for international SMS.
            string signature_1 = "Huawei Cloud SMS test"; // Signature 1
            string signature_2 = "Huawei Cloud SMS test"; // Signature 2

          // Mandatory. Global number format (including the country code), for example, +8615123456789. Use commas (,) to separate multiple numbers.
            string[] receiver_1 = { "+8615123456789", "+8615234567890" }; // Recipient number of template 1
            string[] receiver_2 = { "+8615123456789", "+8615234567890" }; // Recipient number of template 2

            // Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports.
            string statusCallBack = "";

            /*
             * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, string[] templateParas = {};
            * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to ["369751"].
             * Example of a dual-variable template: If the template content is "You have ${NUM_2} delivered to ${TXT_20}", templateParas can be set to {"3","main gate of People's Park"}.
             * For details, see Template and Variable Specifications.
             */
            string[] templateParas_1 = {"123456"}; // Template 1 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569).
            string[] templateParas_2 = {"234567"}; // Template 2 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569).

            ArrayList smsContent = new ArrayList
            {
                // smsContent. If the signature name is not required, set signature to null.
                InitDiffSms(receiver_1, templateId_1, templateParas_1, signature_1),
                InitDiffSms(receiver_2, templateId_2, templateParas_2, signature_2)
            };

            try
            {
               // Ignore the certificate trust issues to prevent API calling failures caused by HTTPS certificate authentication failures.
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                // Set the security protocol type to 3072 to use TLS 1.2.
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)3072;

                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(apiAddress);
                // Request method
                myReq.Method = "POST";
                // Request headers
                myReq.ContentType = "application/json";
                myReq.Headers.Add("Authorization", "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"");
                myReq.Headers.Add("X-WSSE", BuildWSSEHeader(appKey, appSecret));
                // Request body
                var body = new Dictionary<string, object>() {
                    {"from", sender},
                    {"statusCallback", statusCallBack},
                    {"smsContent", smsContent}
                };

                string jsonData = JsonConvert.SerializeObject(body);

                // Send request data.
                StreamWriter req = new StreamWriter(myReq.GetRequestStream());
                req.Write(jsonData);
                req.Close();

                // Obtain response data.
                HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
                StreamReader resp = new StreamReader(myResp.GetResponseStream());
                string result = resp.ReadToEnd();
                myResp.Close();
                resp.Close();

                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.Message);
            }
        }

        /// <summary>
       /// Construct the value of smsContent.
        /// </summary>
        /// <param name="receiver"></param>
        /// <param name="templateId"></param>
        /// <param name="templateParas"></param>
        ///<param name="signature">Signature name, which must be specified when the universal template for Chinese mainland SMS is used.</param>
        /// <returns></returns>
        static Dictionary<string, object> InitDiffSms(string[] receiver, string templateId, string[] templateParas, string signature)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>
            {
                {"to", receiver},
                {"templateId", templateId},
                {"templateParas", templateParas}
            };
            if (!signature.Equals(null) && signature.Length > 0)
            {
                dic.Add("signature", signature);
            }

            return dic;
        }

        /// <summary>
       /// Construct the value of X-WSSE.
        /// </summary>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        static string BuildWSSEHeader(string appKey, string appSecret)
        {
            string now = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); //Created
            string nonce = Guid.NewGuid().ToString().Replace("-", ""); //Nonce

            byte[] material = Encoding.UTF8.GetBytes(nonce + now + appSecret);
            byte[] hashed = SHA256Managed.Create().ComputeHash(material);
            string hexdigest = BitConverter.ToString(hashed).Replace("-", "");
            string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(hexdigest)); //PasswordDigest

            return String.Format("UsernameToken Username=\"{0}\",PasswordDigest=\"{1}\",Nonce=\"{2}\",Created=\"{3}\"",
                            appKey, base64, nonce, now);
        }
    }
}

Receiving Status Reports

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Web;

namespace msgsms_csharp_demo
{
    class Report
    {
        static void Main(string[] args)
        {
            //string success_body = "sequence=1&total=1&updateTime=2018-10-31T08%3A43%3A41Z&source=2&smsMsgId=2ea20735-f856-4376-afbf-570bd70a46ee_11840135&status=DELIVRD";
            string failed_body = "orgCode=E200027&sequence=1&total=1&updateTime=2018-10-31T08%3A43%3A41Z&source=2&smsMsgId=2ea20735-f856-4376-afbf-570bd70a46ee_11840135&status=RTE_ERR";

            //onSmsStatusReport(success_body);
            onSmsStatusReport(failed_body);
        }

        /// <summary>
        /// Parse the status report data.
        /// </summary>
       ///<param name="data">Status report data reported by the SMS platform</param>
        static void onSmsStatusReport(string data)
        {
            var keyValues = HttpUtility.ParseQueryString(data); // Parse the status report data.

            /**
             * Example: Parsing status is used as an example. 
             * 
             * 'smsMsgId': Unique ID of an SMS
             * 'total': Number of SMS segments
             * 'sequence': Sequence number of an SMS after splitting
             * 'source': Status report source
             * 'updateTime': Resource update time
             * 'status': Enumeration values of the status report
             * 'orgCode': Status code
             */
            string status = keyValues.Get("status"); // Enumerated values of the status report
           // Check whether the SMS is successfully sent based on the value of status.
            if ("DELIVRD".Equals(status.ToUpper()))
            {
                Console.WriteLine("Send sms success. smsMsgId: " + keyValues.Get("smsMsgId"));
            }
            else
            {
               // The SMS fails to be sent. The values of status and orgCode are recorded.
                Console.WriteLine("Send sms failed. smsMsgId: " + keyValues.Get("smsMsgId"));
                Console.WriteLine("Failed status: " + status);
                Console.WriteLine("Failed orgCode: " + keyValues.Get("orgCode"));
            }
        }
    }
}