C#.NET短信通用接口设计-调用短信API案例|C/S框架网
作者:作者不详  发布日期:2019-02-14 16:16:39
  C#.NET短信通用接口设计-调用短信API案例|C/S框架网

我们在研发不同平台的C#.NET软件项目时,如:C/S Winform项目、B/S Web项目、移动端APP等项目,通常会在某个业务流程给终端用户发送短信,或者系统自动发送短信,或者触发某个事件发送短信,类似这种需求我们有多个成功案例,调用不同短信供应商的API接口,请参考下面源码:

C#.NET短信通用接口架构设计-调用短信API案例

短信通用接口:


C# Code:

/// <summary>
/// 短信服务供应商统一接口
/// </summary>
public interface ISMSSupplier
{
   /// <summary>
   /// 短信签名
   /// </summary>
   string Singatrure { get; set; }
   
   /// <summary>
   /// 短信服务商名称
   /// </summary>
   string SupplierName { get; }
   
   /// <summary>
   /// 每条短信最大长度
   /// </summary>
   int MessageMaxLength { get; }
   
   /// <summary>
   /// 短信接口初始化
   /// </summary>
   void Init();
   
   /// <summary>
   /// 注销
   /// </summary>
   void Logout();
   
   /// <summary>
   /// 发送短信
   /// </summary>
   /// <param name="phoneNos">手机号码</param>
   /// <param name="message">短信内容</param>
   /// <returns></returns>
   bool Send(string[] phoneNos, string message);
   
   /// <summary>
   /// 查询单价
   /// </summary>
   /// <returns></returns>
   double GetPrice();
   
   /// <summary>
   /// 查询余额
   /// </summary>
   /// <returns></returns>
   double GetBalance();
   
   /// <summary>
   /// 充值
   /// </summary>
   /// <param name="cardNo">卡号</param>
   /// <param name="cardPassword">密码</param>
   /// <returns></returns>
   bool Charge(string cardNo, string cardPassword);
   
   /// <summary>
   /// 根据短信模板生成短信
   /// </summary>
   /// <param name="param"></param>
   /// <returns></returns>
   string BuildSMS(int templateID, string[] param);
}

//来源:C/S框架网(www.csframework.com) QQ:23404761



阿里云短信接口实例:


C# Code:

/// <summary>
/// 阿里云短信接口
/// </summary>
public class SMS_Aliyun : ISMSSupplier
{
   public string Singatrure { get; set; }
   
   public string SupplierName { get { return "阿里云短信"; } }
   
   public int MessageMaxLength { get { return 0; } }
   
   public SMS_Aliyun()
   {
      this.Singatrure = "C/S框架网";
   }
   
   public void Init()
   {
   }
   
   public void Logout()
   {
   }
   
   public string BuildSMS(int templateID, string[] param)
   {
      if (templateID == 1 && param.Length == 1)
      {
         return "{\"code\":\"" + param[0] + "\"}";
      }
      return "";
   }
   
   public bool Send(string[] phoneNos, string message)
   {
      String product = "Dysmsapi";//短信API产品名称
      String domain = "dysmsapi.aliyuncs.com";//短信API产品域名
      String accessKeyId = "XLAINMW7DcywFd58";//你的accessKeyId
      String accessKeySecret = "5kN9GQGSTLk3zUdGtm33Z5Qq2YZMZ9x";//你的accessKeySecret
      
      IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
      
      DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
      IAcsClient acsClient = new DefaultAcsClient(profile);
      SendSmsRequest request = new SendSmsRequest();
      try
      {
         //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
         request.PhoneNumbers = GetPhoneString(phoneNos);
         //必填:短信签名-可在短信控制台中找到
         request.SignName = "C/S框架网";
         //必填:短信模板-可在短信控制台中找到
         request.TemplateCode = "SMS_138920016";
         //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
         request.TemplateParam = message;
         //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
         request.OutId = Guid.NewGuid().ToString().ToLower();
         
         //请求失败这里会抛ClientException异常
         SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
         
         System.Console.WriteLine(sendSmsResponse.Message);
         
         return sendSmsResponse.Code == "OK";
      }
      catch (ServerException e)
      {
         return false;
      }
      catch (ClientException e)
      {
         return false;
      }
   }
   
   private string GetPhoneString(string[] phones)
   {
      StringBuilder sb = new StringBuilder();
      foreach (String S in phones)
      sb.Append(S + ",");
      return sb.ToString();
   }
   
   public double GetPrice()
   {
      return 0;
   }
   
   public double GetBalance()
   {
      return 0;
   }
   
   public bool Charge(string cardNo, string cardPassword)
   {
      return true;
   }
   
}

//来源:C/S框架网(www.csframework.com) QQ:23404761



上海互亿无线短信接口实例:


 /// <summary>
    /// 上海互亿无线
    /// </summary>
    public class SMS_IHUYI : ISMSSupplier
    {
        public string Singatrure { get; set; }

        public string SupplierName { get { return "上海互亿无线"; } }

        public int MessageMaxLength { get { return 0; } }

        public void Init()
        {
        }

        public void Logout()
        {
        }

        public string BuildSMS(int templateID, string[] param)
        {
            if (templateID == 1 && param.Length == 1)
            {
                string tmp = "您的验证码是:[" + param[0] + "]。";
                return tmp;
            }

            return "";
        }

        public bool Send(string[] phoneNos, string message)
        {
            //http://106.ihuyi.cn/webservice/sms.php?method=Submit
            //http://106.ihuyi.cn/webservice/sms.php?smsService

            try
            {
                string account = "cf_yq66sc";
                string password = "fb4f7ee87686920be1717a23552fd22";
                string mobile = phoneNos[0];

                string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}";
                string PostUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

                UTF8Encoding encoding = new UTF8Encoding();
                byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, message));

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = postData.Length;

                Stream newStream = myRequest.GetRequestStream();                
                newStream.Write(postData, 0, postData.Length);
                newStream.Flush();
                newStream.Close();

                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                if (myResponse.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

                    string res = reader.ReadToEnd();
                    int len1 = res.IndexOf("</code>");
                    int len2 = res.IndexOf("<code>");
                    string code = res.Substring((len2 + 6), (len1 - len2 - 6));
                    //Response.Write(code);
                    //405
                    //你提交过来的短信内容必须与报备过的模板格式相匹配
                    int len3 = res.IndexOf("</msg>");
                    int len4 = res.IndexOf("<msg>");
                    string msg = res.Substring((len4 + 5), (len3 - len4 - 5));
                    return code == "2";
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public double GetPrice()
        {
            return 0;
        }

        public double GetBalance()
        {
            return 0;
        }

        public bool Charge(string cardNo, string cardPassword)
        {
            return true;
        }

    }


短信API对象工厂:

C# Code:

/// <summary>
/// 短信中心
/// </summary>
public class SMSFactory
{
   
   //当前短信供应商
   private static ISMSSupplier _Supplier = null;
   
   static SMSFactory()
   {
      string supplier = System.Configuration.ConfigurationManager.AppSettings["SMSSupplier"];
      if (supplier == "Aliyun") _Supplier = new SMS_Aliyun();
      if (supplier == "IHUYI") _Supplier = new SMS_IHUYI();
   }
   
   /// <summary>
   /// 当前短信供应商
   /// </summary>
   public static ISMSSupplier Supplier { get { return _Supplier; } set { _Supplier = value; } }
   
}

//来源:C/S框架网(www.csframework.com) QQ:23404761



如何使用?


C# Code:

//短信验证码
string code="212343";
//构建短信模板
string msg = SMSFactory.Supplier.BuildSMS(1, new string[] { code });
bool send = SMSFactory.Supplier.Send(new string[] { phone }, msg);




上一篇 下一篇