发送短信功能

短信发送前需要借助第三方程序,这里用的是“飞鸽通信云平台”   (网站--飞鸽通信云平台

在通知短信-短信发送-模板管理-添加模板

选择需要的模板,内容可以自定义(虽然需要审核,但速度之快,切出去敲两行就审核好了),主要需要的就是这个模板id

 

这里我把所有用到的都扔在一个文件夹了

ConfigItem.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RepairApi.SendMessage
{
    public class ConfigItem
    {
        public static string UploadDirectory
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["UploadDirectory"];
            }
        }

        public static string PDFDirectory
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["PDFDirectory"];
            }
        }

        public static string TempFileDirectory
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["TempFileDirectory"];
            }
        }

        public static string AllowUploadFileEx
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["AllowUploadFileEx"];
            }
        }

        public static string WebApiServiceRootUrl
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["WebApiServiceRootUrl"];
            }
        }

        public static string WebApiServicePublicUrl
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["WebApiServicePublicUrl"];
            }
        }

        public static int UploadMaxFileSize
        {
            get
            {
                var uploadMaxFileSizeStr = System.Configuration.ConfigurationManager.AppSettings["UploadMaxFileSize"];
                if (string.IsNullOrEmpty(uploadMaxFileSizeStr))
                    return 0;
                else if (int.TryParse(uploadMaxFileSizeStr, out int uploadMaxFileSize))
                    return uploadMaxFileSize;
                else
                    return 0;
            }
        }

        public static bool IsSessionBrowse
        {
            get
            {
                var isSessionBrowseStr = System.Configuration.ConfigurationManager.AppSettings["IsSessionBrowse"];
                if (string.IsNullOrEmpty(isSessionBrowseStr))
                    return false;
                else if (bool.TryParse(isSessionBrowseStr, out bool isSessionBrowse))
                    return isSessionBrowse;
                else
                    return false;
            }
        }

        public static int SessionMinutes
        {
            get
            {
                var sessionMinutesStr = System.Configuration.ConfigurationManager.AppSettings["SessionMinutes"];
                if (string.IsNullOrEmpty(sessionMinutesStr))
                    return 30;
                else if (int.TryParse(sessionMinutesStr, out int sessionMinutes))
                    return sessionMinutes;
                else
                    return 30;
            }
        }

        public static string FileSiteURL
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["FileSiteURL"];
            }
        }

        public static bool IsCanSendSms
        {
            get
            {
                 var config = System.Configuration.ConfigurationManager.AppSettings["IsCanSendSms"];
                if (string.IsNullOrEmpty(config))
                    return false;
                else if (bool.TryParse(config, out bool boolValue))
                    return boolValue;
                else
                    return false;
            }
        }

        public static int RepeatSendSmsCount
        {
            get
            {
                var config = System.Configuration.ConfigurationManager.AppSettings["RepeatSendSmsCount"];
                if (string.IsNullOrEmpty(config))
                    return 1;
                else if (int.TryParse(config, out int intValue))
                    return intValue;
                else
                    return 1;
            }
        }

        public static decimal VIPDiscount
        {
            get
            {
                var config = System.Configuration.ConfigurationManager.AppSettings["VIPDiscount"];
                if (string.IsNullOrEmpty(config))
                    return 1;
                else if (decimal.TryParse(config, out decimal decValue))
                    return decValue;
                else
                    return 1;
            }
        }
    }
}

 Result.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RepairApi.SendMessage
{
    public class Result
    {
        public Result()
        {
            Code = 400;
            IsSuccessful = false;
            ErrorType = ExceptionType.Business;
        }
        public bool IsSuccessful { get; set; }
        [JsonProperty(PropertyName = "msg")]
        public string Message { get; set; }
        [JsonProperty(PropertyName = "code")]
        public int Code { get; set; }
        public ExceptionType ErrorType { get; set; }
        protected Exception Exception { get; set; }
        public void Success()
        {
            SetValue(true, String.Empty, null, ExceptionType.None);
        }

        public void Failure(string message)
        {
            SetValue(false, message, null, ExceptionType.Business);
        }
        public void Failure(string message, ExceptionType errorType)
        {
            SetValue(false, message, null, errorType);
        }
        public void Failure(string message, Exception exception, ExceptionType errorType)
        {
            SetValue(false, message, exception, errorType);
        }

        public void SetValue(bool isSuccessful, string message, Exception exception, ExceptionType errorType)
        {
            if (isSuccessful)
            {
                Code = 0;
            }
            else
            {
                Code = 400;
            }
            IsSuccessful = isSuccessful;
            Message = message;
            Exception = exception;
            ErrorType = errorType;
            if (exception != null)
            {
                var errlog = new StringBuilder();
                errlog.AppendLine(message);
                errlog.AppendLine(exception.ToString());
                if (exception.InnerException != null)
                {
                    errlog.AppendLine("InnerException:");
                    errlog.AppendLine(exception.InnerException.ToString());
                }
                //Log.WriteErrorLog(errlog.ToString());
            }
        }
    }

    public class Result<T> : Result
    {
        public Result() : base() { }

        [JsonProperty(PropertyName = "count")]
        public int Count { get; set; }

        [JsonProperty(PropertyName = "data")]
        public T ResultData { get; set; }

        public void Success(T resultData)
        {
            ResultData = resultData;
            SetValue(true, String.Empty, null, ExceptionType.None);
        }
    }
    public enum ExceptionType
    {
        None,
        Service,
        DataBase,
        Business,
        Unkown,
        Cancel,
        Background,
        NoFind,
        Notice
    }
}

SendSmsMessage.cs

这里的 TemplateId = 132234; 就是刚刚审核过的模板id,只需要换这就可以替换模板

上面部分内容需要自己注册后替换成自己的相关内容

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using RepairApi.SendMessage;

namespace RepairApi
{
    public class SendSmsMessage
    {
        public Result Send(SmsSend sendMsg)
        {
            var ret = new Result();

            sendMsg.ApiKey = "";//换成自己的
            sendMsg.Secret = "";//换成自己的
            sendMsg.SignId = ;//换成自己的
            try
            {
                using (var client = new HttpClient())
                {
                    var url = "https://api.4321.sh/sms/template";
                    var json = JsonConvert.SerializeObject(sendMsg);
                    var content = new StringContent(json, Encoding.UTF8);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var tmpResult = client.PostAsync(url, content).Result;
                    tmpResult.EnsureSuccessStatusCode();
                    var result = tmpResult.Content.ReadAsStringAsync().Result;
                    var back = JsonConvert.DeserializeObject<SmsBack>(result);
                    sendMsg.SendCount++;
                    if (back.Code == 0)
                    {
                        sendMsg.IsSend = true;
                        sendMsg.SendDateTime = DateTime.Now;
                        ret.Success();
                    }
                    else
                    {
                        throw new Exception(back.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                ret.Failure("发送短信失败。", ex, ExceptionType.Service);
            }
            return ret;
        }

        /// <summary>
        /// 发送创建订单短信
        /// </summary>
        /// <param name="mobilePhone">注册手机号</param>
        /// <returns></returns>
        public Result SendCreateOrderMessage(string mobilePhone)
        {
            //var ret = new Result();
            var smsSend = new SmsSend()
            {
                Mobile = mobilePhone,
                Content = "",
                TemplateId = 132234
            };
            var sms = new SendSmsMessage();
            var ret = sms.Send(smsSend);
            return ret;
        }
    }
}

SmsBack.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RepairApi.SendMessage
{
    public class SmsBack
    {
        [JsonProperty(PropertyName = "msg_no")]
        public string SendId { get; set; }
        [JsonProperty(PropertyName = "fee")]
        public decimal Fee { get; set; }
        [JsonProperty(PropertyName = "count")]
        public int Count { get; set; }
        [JsonProperty(PropertyName = "code")]
        public int Code { get; set; }
        [JsonProperty(PropertyName = "msg")]
        public string Message { get; set; }
    }
}

SmsSend.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RepairApi.SendMessage
{
    public class SmsSend
    {
        public SmsSend()
        {
            IsSend = false;
            SendCount = 0;
        }
        [JsonProperty(PropertyName = "apikey")]
        public string ApiKey { get; set; }
        [JsonProperty(PropertyName = "secret")]
        public string Secret { get; set; }
        [JsonProperty(PropertyName = "content")]
        public string Content { get; set; }
        [JsonProperty(PropertyName = "mobile")]
        public string Mobile { get; set; }
        [JsonProperty(PropertyName = "sign_id")]
        public int SignId { get; set; }
        [JsonProperty(PropertyName = "template_id")]
        public int TemplateId { get; set; }
        [JsonIgnore]
        public bool IsSend { get; set; }
        [JsonIgnore]
        public int SendCount { get; set; }
        [JsonIgnore]
        public DateTime? SendDateTime { get; set; }
    }
}

这个文件夹配置好后,需要用到的时候,只需要两句话

var sendSms = new SendSmsMessage();
sendSms.SendCreateOrderMessage("110");//要接收短信的手机号

 比如:

 //倒计时事件
        public void SendWarn()
        {
            List<string> phoneList = CheckPhone();
            for(int i = 0; i < phoneList.Count; i++)
            {
                string phone = phoneList[i];
                var sendSms = new SendSmsMessage();
                sendSms.SendCreateOrderMessage(phone);
            }
        }

记得引用一下配置好的文件夹

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值