C#
Example |
|
---|---|
Environment |
.Net 7.0, Visual Studio Code 1.75.1, and plug-ins of C# v1.25.7 and Code Runner v0.12.0 (optional) |
- 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.
Download required SDKs and demos for C#. Take Visual Studio Code as an example. Select a directory in the local resource manager, for example, D:/sms, and use a terminal to access the directory.
- Run the dotnet new console command to generate a project.
- Copy Signer.cs and HttpEncoder.cs to D:/sms, create an empty SendSms.cs file in the sms folder, and copy the content in the following example to SendSms.cs.
- Use Visual Studio Code to open the project and run SendSms.cs.
Example of Sending SMSs
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 |
using System; using System.Net; using System.IO; using APIGATEWAY_SDK; using System.Text; namespace DEMO { class Program { static void Main(string[] args) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; // Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation. string apiAddress = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1"; // Application access address (obtain it from the Application Management page on the console) 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"; // APP_Key string appSecret = "q4Ii87Bh************80SfD7Al"; //APP_Secret string sender = "csms12345678"; // Channel number for Chinese mainland SMS signature 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, +86151****6789. Use commas (,) to separate multiple numbers. string receiver = "+86137****6781,+86137****6782"; // 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 ${1}", templateParas can be set to "[\"369751\"]". * Example of a dual-variable template: If the template content is "You have ${1} delivered to ${2}", templateParas can be set to "[\"3\",\"main gate of People's Park\"]". * Each variable in the template must be assigned a value, and the value cannot be empty. * To view more information, choose Service Overview > 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). Signer signer = new Signer(); signer.Key = appKey; signer.Secret = appSecret; HttpRequest r = new HttpRequest("POST", new Uri(apiAddress)); // Application access address (obtain it from the Application Management page on the console) and API access URI. // Request body var body = new Dictionary<string, string>() { {"from", sender}, {"to", receiver}, {"templateId", templateId}, {"templateParas", templateParas}, {"statusCallback", statusCallBack}, //{"signature", signature} // The signature must be entered when the universal template for Chinese mainland SMS is used. }; r.body =new FormUrlEncodedContent(body).ReadAsStringAsync().Result; r.headers.Add("Content-Type", "application/x-www-form-urlencoded"); HttpWebRequest req = signer.Sign(r); Console.WriteLine(req.Headers.GetValues("x-sdk-date")[0]); Console.WriteLine(string.Join(", ", req.Headers.GetValues("authorization"))); Console.WriteLine("body: " + r.body); // Do not verify the certificate. ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; try { var writer = new StreamWriter(req.GetRequestStream()); writer.Write(r.body); writer.Flush(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); var reader = new StreamReader(resp.GetResponseStream()); Console.WriteLine(reader.ReadToEnd()); } catch (WebException e) { HttpWebResponse resp = (HttpWebResponse)e.Response; if (resp != null) { Console.WriteLine((int)resp.StatusCode + " " + resp.StatusDescription); var reader = new StreamReader(resp.GetResponseStream()); Console.WriteLine(reader.ReadToEnd()); } else { Console.WriteLine(e.Message); } } } } } |
Example of Sending SMSs in Batches
Reference library: For Newtonsoft.Json 11.0.2 and later versions, visit https://www.newtonsoft.com/json.
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 |
using System; using System.Net; using System.IO; using APIGATEWAY_SDK; using System.Text; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; namespace DEMODiffSMS { class Program { static void Main(string[] args) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; // Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation. string apiAddress = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendDiffSms/v1"; // Application access address (obtain it from the Application Management page on the console) 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"; // APP_Key string appSecret = "q4Ii87Bh************80SfD7Al"; //APP_Secret string sender = "csms12345678"; // Channel number for Chinese mainland SMS signature or international SMS string templateId_1 = "8ff55eac1d0b478ab3c06c3c6a492300"; // Template ID 1 string templateId_2 = "8ff55eac1d0b478ab3c06c3c6a492301"; // 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 1"; // Signature 1 string signature_2 = "Huawei Cloud SMS test 2"; // Signature 2 // Mandatory. Global number format (including the country code), for example, +86151****6789. Use commas (,) to separate multiple numbers. string[] receiver_1 = { "+86151****6781", "+86151****6783" }; // Recipient number of template 1 string[] receiver_2 = { "+86151****6782", "+86151****6784" }; // 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 = "https://your.server.com/rest/callback/statusReport"; /* * 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 ${1}", templateParas can be set to ["369751"]. * Example of a dual-variable template: If the template content is "You have ${1} parcel delivered to ${2}", templateParas can be set to {"3","main gate of People's Park"}. * Each variable in the template must be assigned a value, and the value cannot be empty. * To view more information, choose Service Overview > 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) }; // Request body var body = new Dictionary<string, object>{ {"from", sender}, {"statusCallback", statusCallBack}, {"smsContent", smsContent} }; Signer signer = new Signer(); signer.Key = appKey; signer.Secret = appSecret; HttpRequest r = new HttpRequest("POST", new Uri(apiAddress)); r.body = JsonConvert.SerializeObject(body); r.headers.Add("Content-Type", "application/json"); HttpWebRequest req = signer.Sign(r); Console.WriteLine(req.Headers.GetValues("x-sdk-date")[0]); Console.WriteLine(string.Join(", ", req.Headers.GetValues("authorization"))); Console.WriteLine("body: " + r.body); // Do not verify the certificate. ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; try { var writer = new StreamWriter(req.GetRequestStream()); writer.Write(r.body); writer.Flush(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); var reader = new StreamReader(resp.GetResponseStream()); Console.WriteLine(reader.ReadToEnd()); } catch (WebException e) { HttpWebResponse resp = (HttpWebResponse)e.Response; if (resp != null) { Console.WriteLine((int)resp.StatusCode + " " + resp.StatusDescription); var reader = new StreamReader(resp.GetResponseStream()); Console.WriteLine(reader.ReadToEnd()); } else { Console.WriteLine(e.Message); } } } 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; } } } |
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")); } } } } |
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot