更新时间:2024-04-08 GMT+08:00
C#
- 本文档所述Demo在提供服务的过程中,可能会涉及个人数据的使用,建议您遵从国家的相关法律采取足够的措施,以确保用户的个人数据受到充分的保护。
- 本文档所述Demo仅用于功能演示,不允许客户直接进行商业使用。
- 本文档信息仅供参考,不构成任何要约或承诺。
发送短信
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography.X509Certificates; using System.Text; using Newtonsoft.Json; namespace sms { class SendSms { public class NamedParameter { //对key进行赋值 public string key { get; set; } //对value进行赋值 public string value { get; set; } } public class MtSmsMessage { //对mobiles进行赋值 public List<string> mobiles { get; set; } //对templateId进行赋值 public string templateId { get; set; } //对templateParas进行赋值 public Dictionary<string, string> templateParas { get; set; } //对signature进行赋值 public string signature { get; set; } //对messageId进行赋值 public string messageId { get; set; } //对extCode进行赋值 public string extCode { get; set; } //对extendInfos进行赋值 public List<NamedParameter> extendInfos { get; set; } } /// <summary> /// 构建请求参数 /// </summary> /// <param name="msisdn">手机号,多个以,号分隔</param> /// <param name="smsTemplateId">短信模板id</param> /// <param name="paramValues">键值对map,比如user,email</param> /// <param name="accout">真实账号</param> /// <param name="passward">真实密码</param> /// <param name="signature">短信签名</param> /// <returns>返回请求参数体</returns> private static Hashtable buildRequestBody(string msisdn, string smsTemplateId, Dictionary<string, string> paramValues, string accout, string passward, string signature) { if (null == msisdn || null == smsTemplateId || null == accout || null == passward) { Console.WriteLine("buildRequestBody(): mobiles, templateId or templateParas or account or password is null."); return null; } Hashtable map = new Hashtable(); List<Hashtable> requestLists = new List<Hashtable>(); Hashtable mtSmsMessage = new Hashtable(); List<string> mobiles = msisdn.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Cast<string>().ToList<string>(); mtSmsMessage.Add("mobiles", mobiles); mtSmsMessage.Add("templateId", smsTemplateId); //当发送短信使用的是无变量模板时,不需要添加templateParas参数。 mtSmsMessage.Add("templateParas", paramValues); mtSmsMessage.Add("signature", signature); requestLists.Add(mtSmsMessage); map.Add("account", accout); map.Add("password", passward); //状态报告通知地址,根据实际情况修改 map.Add("statusCallback", "https://ip:port/sms/notifySmsMessage"); map.Add("requestLists", requestLists); return map; } public static void Main(string[] args) { Dictionary<string, string> templateParas = new Dictionary<string, string>(); templateParas.Add("user", "$user"); templateParas.Add("email", "$email"); // ip:port根据实际情况填写 const string url = "https://ip:port/common/sms/sendTemplateMessage"; //手机号,多个手机号以,号分隔 const string msisdn = "12345678911,12345678912,12345678913"; //短信模板 const string smsTemplateId = "SMS_2003240016"; //实际账号 const string accout = "xxxxxx"; //实际密码 const string passward = "xxxxxx"; //短信签名 const string signature = "【华为云】"; // If the request body does not contain the signature name, set signature to null. Hashtable pars = buildRequestBody(msisdn, smsTemplateId, templateParas, accout, passward, signature); if (null == pars) { Console.WriteLine("body is null."); return; } Post(url, pars); Console.ReadLine(); } /// <summary> /// 发起post请求 /// </summary> /// <param name="url">请求url</param> /// <param name="pars">请求参数</param> /// <returns>响应结果</returns> public static string Post(string url, System.Collections.Hashtable pars) { HttpWebRequest request = null; if (url.Contains("https://")) { ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url)); } else { request = (HttpWebRequest)WebRequest.Create(url); } request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36"; request.Method = "POST";//post请求方式 request.ContentType = "application/json";//设置为json串格式 request.ProtocolVersion = HttpVersion.Version10; //对参数进行序列化,生成字节流 string buffer = JsonConvert.SerializeObject(pars); byte[] postmsg = Encoding.UTF8.GetBytes(buffer); //请求响应结果流 Stream myResponseStream = request.GetRequestStream(); myResponseStream.Write(postmsg, 0, postmsg.Length); myResponseStream.Flush(); HttpWebResponse response = null; StreamReader myStreamReader = null; string retString = ""; try { response = (HttpWebResponse)request.GetResponse(); using (myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { retString = myStreamReader.ReadToEnd(); Console.WriteLine("result="+retString); } } catch (Exception e) { return e.Message; } finally { if (response != null) { response.Close(); } myStreamReader.Close(); myResponseStream.Close(); if (request != null){ request.Abort(); } } return retString; } //设置对证书进行不校验,绕过https证书 public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } } }
上行短信接收
using System; using System.Web; namespace msgsms_csharp_demo { class UpData { static void Main(string[] args) { string updata = "mobile=%2B12345678911&content=***&sendTime=20220127020758&extCode="; onSmsUpData(updata); } /// <summary> /// 解析上行短信通知数据 /// </summary> /// <param name="data">短信平台推送的上行短信通知数据</param> static void onSmsUpData(string data) { var keyValues = HttpUtility.ParseQueryString(data); //解析上行短信通知数据 /** * Example: 此处以解析content为例,请按需解析所需参数并自行实现相关处理 * * 'mobile': 上行短信手机号 * 'content': 短信内容 * 'sendTime': 上行短信时间 * 'extCode': 扩展码 */ string content = keyValues.Get("content"); // 上行短信发送的内容 Console.WriteLine("Sms up data. Content: " + content); } } }
状态报告接收
using System; using System.Web; namespace msgsms_csharp_demo { class UpData { static void Main(string[] args) { /// String success_body = "requestId=20220126&mobile=12345678911&messageId=2022012619403400&status=DELIVRD&resultCode=000000&resultDesc=success&smsCount=null&receiveTime=null"; String failed_body = "requestId=20220126&mobile=12345678911&messageId=2022012619403400&status=E200027&resultCode=1020001&resultDesc=Parameter error&smsCount=null&receiveTime=null"; /// onSmsStatusReport(success_body); onSmsStatusReport(updata); } /// <summary> /// 解析状态报告数据 /// </summary> /// <param name="data">短信平台上报的状态报告数据</param> static void onSmsStatusReport(string data) { var keyValues = HttpUtility.ParseQueryString(data); //解析状态报告数据 /** * Example: 此处以解析status为例,,请按需解析所需参数并自行实现相关处理 * * 'messageId': 短信唯一标识 * 'smsCount': 长短信拆分条数 * 'receiveTime': 资源更新时间 * 'status': 状态码 */ string status = keyValues.Get("status"); // 状态报告枚举值 if ("DELIVRD".equalsIgnoreCase(status)) { Console.WriteLine("Send sms success. messageId: " + keyValues.get("messageId")); } else { // 发送失败,打印status Console.WriteLine("Send sms failed. messageId: " + keyValues.get("messageId")); Console.WriteLine("Failed status: " + status); } Console.WriteLine("Sms up data. status: " + status); } } }
父主题: API样例代码