C#短信发送接口源码

短信发送接口源码(注册,登录,改密)

using DQGame.Web.Helper;
using DQGame.Web.Models;
using Game.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Web;

namespace DQGame.Web.Module.SmsManager
{
    /// <summary>
    /// 短信发送接口
    /// type 验证码类别 1注册;2修改密码;3绑定
    /// mobile 手机号
    /// </summary>
    public class SMS : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            string mobile = GameRequest.GetString<SMSModel>("mobile").ToLower();
            int type = GameRequest.GetInt<SMSModel>("type", 1);
            if (type<1||type>3)
            {
                CommonHelper.WriteJson("error", "短信类型错误");
            }
            if (string.IsNullOrEmpty(mobile))
            {
                CommonHelper.WriteJson("error", "请输入手机号码");
            }

            if (!new Regex(@"^\d{11}$").IsMatch(mobile))
            {
                CommonHelper.WriteJson("error", "手机号码输入错误,请重新输入");
            }
            //判断发送是否频繁

            var result = IsSendCaptchaTooQuick(mobile);
            if (result != -1 && result < 120)
            {
                CommonHelper.WriteJson("error", "请在" + (120 - result).ToString().Split('.')[0] + "秒后尝试");
            }

            //验证码
            string yzmNum = new Random().Next(100000, 1000000).ToString();
            //发送短信
            //1注册;2修改密码;3绑定
            string[] templateids = { "313914", "313928", "313929" };
            string res = SendSms(mobile, yzmNum, templateids[type - 1]);
            //记录日志
            AddSmsLog("", mobile, "您本次的验证码为" + yzmNum + ",120秒有效", res, yzmNum);

            CommonHelper.WriteJson("ok", "成功");
        }


        #region 发送短信
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="mobile">The mobile.</param>
        /// <param name="content">The content.</param>
        /// <returns></returns>
        public string SendSms(string mobile, string yzmNum, string templateid)
        {
            try
            {
                HttpClient hc = new HttpClient();
                string str = "{\"sid\":\"b79f05e1c8d10423df77987ee8e50f33\",\"token\":\"e0a4ded4abe5fb8940b88b9773897275\",\"appid\":\"d74f52d3c261475ca7c226fe2ebc19ff\",\"templateid\":" + templateid + ",\"param\":" + yzmNum + ",\"mobile\":\"" + mobile
                    + "\",\"uid\":\"2d92c6132139467b989d087c84a365d8\"}";
                //必须是json格式
                StringContent sc = new StringContent(str);
                //必须添加报文头ContentType
                sc.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                HttpResponseMessage res = hc.PostAsync("https://open.ucpaas.com/ol/sms/sendsms", sc).Result;
                JObject json = (JObject)JsonConvert.DeserializeObject(res.Content.ReadAsStringAsync().Result);

                return json["code"].ToString();
            }
            catch
            {

                return "发送失败";
            }

        }


        /// <summary>
        /// 判断手机验证码是否发送频繁
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        protected virtual double IsSendCaptchaTooQuick(string mobile)
        {
            if (string.IsNullOrEmpty(mobile))
            {
                throw new ArgumentNullException("mobile");
            }


            string sql = @"select top 1 CreatedOn from SmsLog where smstype=0 and Reciever = @Reciever and [ReturnVal]='000000'
                    order by CreatedOn DESC";

            SQLHelper helper = new SQLHelper("QPAccountsDBConnstr");
            var createdOn = helper.ExecuteScalar(sql, new SqlParameter() { ParameterName = "@Reciever", Value = mobile });
            if (createdOn != null)
            {
                var sendTime = Convert.ToDateTime(createdOn);
                TimeSpan ts = DateTime.Now.Subtract(sendTime);

                return ts.TotalSeconds;
            }

            return -1;
        }

        /// <summary>
        /// 新增短信日志
        /// </summary>
        /// <param name="sender">没用</param>
        /// <param name="reciever">手机号</param>
        /// <param name="content">没用</param>
        /// <param name="returnVal">接口返回的数据,这个接口000000表示正确</param>
        /// <param name="smsValue">发送的验证码</param>
        private void AddSmsLog(string sender, string reciever, string content,
            string returnVal = null, string smsValue = null)
        {

            SqlParameter[] parameters = {
                    new SqlParameter("@Id",Guid.NewGuid().ToString()),
                    new SqlParameter("@Sender", sender),
                    new SqlParameter("@Reciever",reciever),
                    new SqlParameter("@Content", content),
                    new SqlParameter("@ReturnVal", returnVal),
                    new SqlParameter("@SmsValue", smsValue),
                    new SqlParameter("@CreatedOn", DateTime.Now)};
            //默认0表示是没有使用的 
            var sql = @"
           INSERT INTO [SmsLog]
           (Id,[SmsType],[Sender],[Reciever],[Content],[ReturnVal],SmsValue,[CreatedOn])
         VALUES
           (@Id,0,@Sender,@Reciever,@Content,@ReturnVal,@SmsValue,@CreatedOn)";

            SQLHelper helper = new SQLHelper("QPAccountsDBConnstr");
            int count = helper.ExecuteNonQuery(sql, parameters);
        }

        #endregion


        #region 验证短信
        private void VerificationSms(string mobile, string smscode, int type)
        {
            string sql = @"select top 1 CreatedOn from SmsLog where smstype=@type and Reciever = @Reciever and [ReturnVal]='000000' and SmsValue=@smsValue
                    order by CreatedOn DESC";
            SQLHelper helper = new SQLHelper("QPAccountsDBConnstr");
            var createdOn = helper.ExecuteScalar(sql, new SqlParameter() { ParameterName = "@Reciever", Value = mobile }, new SqlParameter() { ParameterName = "@smsValue", Value = smscode }, new SqlParameter() { ParameterName = "@type", Value = type });
            if (createdOn != null)
            {
                var sendTime = Convert.ToDateTime(createdOn);
                TimeSpan ts = DateTime.Now.Subtract(sendTime);

                if (ts.TotalSeconds > 120)
                {
                    CommonHelper.WriteJson("error", "验证码已过期");
                }
                else
                {
                    CommonHelper.WriteJson("ok", "成功");
                }
            }
            else
            {
                CommonHelper.WriteJson("error", "验证码错误");
            }

        }

        #endregion


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
短信二次开发接口适用于WAVECOM、西门子、诺基亚、摩托罗拉等支持标准AT 指令的GSM 短信终端 使用方式: 将sms.dll 文件拷贝到系统安装目录中的system32 文件夹中,然后再根据以下接口函数说明和提供的例 程源码开发 接口函数: 1、Sms_Connection(Com_Port As Integer,Com_BaudRate As Integer, Mobile_Type As String) As Integer Sms_Connection 函数说明如下: 功能描述:用于初始化终端与串口的连接 Com_Port:串口号(0 为红外接口,1,2,3,...为串口) Com_BaudRate:波特率 Mobile_Type:返回终端型号 Sms_Connection:返回值(0:连接终端失败;1:连接终端成功) 2、Sms_Send(Sms_TelNum As String, Sms_Text As String) As Integer Sms_Send 函数说明如下: 功能描述:发送短信 Sms_TelNum:发送给的终端号码 Sms_Text:发送短信内容 Sms_Send:返回值(0:发送短信失败;1:发送短信成功) 3、Sms_Receive(Sms_Type As String, Sms_Text As String) As Integer Sms_Receive 函数说明如下: 功能描述:接收指定型的短信 Sms_Type:短信型(0:未读短信;1:已读短信;2:待发短信;3:已发短信;4:全部短信) Sms_Text:返回指定型的短信内容字符串(短信内容字符串说明:短信短信之前用"|"符号 作为分隔符,每条短信中间的各字段用"#"符号作为分隔符) 4、Sms_Delete(ByVal Sms_Index As String) As Integer Sms_Delete 函数说明如下: 功能描述:删除指定的短信 Sms_Index:短信的索引号 5、Sms_AutoFlag()As Integer Sms_AutoFlag 函数说明如下: 功能描述:检测连接的终端是否支持自动收发短信
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值