Nodejs完成短信验证码分分快三全天计划网站

作者:分分快三全天计划网站

最近在项目中遇到了群发短信的需求。

Nodejs

// 修改为您的apikey.可在官网(https://www.yunpian.com)登录后获取
var https = require('https');
var qs = require('querystring');

var apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// 修改为您要发送的手机号码,多个号码用逗号隔开
var mobile = 'xxxxxxxxxxx';
// 修改为您要发送的短信内容
var text = '【云片网】您的验证码是1234';
// 指定发送的模板编号
var tpl_id = 1;
// 指定发送模板的内容
var tpl_value =  {'#code#':'1234','#company#':'yunpian'};
// 语音短信的内容
var code = '1234';
// 查询账户信息https地址
var get_user_info_uri = '/v2/user/get.json';
// 智能匹配模板发送https地址
var sms_host = 'sms.yunpian.com';
var voice_host = 'voice.yunpian.com';

send_sms_uri = '/v2/sms/single_send.json';
// 指定模板发送接口https地址
send_tpl_sms_uri = '/v2/sms/tpl_single_send.json';
// 发送语音验证码接口https地址
send_voice_uri = '/v2/voice/send.json';





query_user_info(get_user_info_uri,apikey);

send_sms(send_sms_uri,apikey,mobile,text);

send_tpl_sms(send_tpl_sms_uri,apikey,mobile,tpl_id,tpl_value);

send_voice_sms(send_voice_uri,apikey,mobile,code);
function query_user_info(uri,apikey){
    var post_data = {  
    'apikey': apikey,  
    };//这是需要提交的数据
    var content = qs.stringify(post_data);  
    post(uri,content,sms_host);
}

function send_sms(uri,apikey,mobile,text){
    var post_data = {  
    'apikey': apikey,  
    'mobile':mobile,
    'text':text,
    };//这是需要提交的数据  
    var content = qs.stringify(post_data);  
    post(uri,content,sms_host);
}

function send_tpl_sms(uri,apikey,mobile,tpl_id,tpl_value){
    var post_data = {  
    'apikey': apikey,
    'mobile':mobile,
    'tpl_id':tpl_id,
    'tpl_value':qs.stringify(tpl_value),  
    };//这是需要提交的数据  
    var content = qs.stringify(post_data);  
    post(uri,content,sms_host); 
}
function send_voice_sms(uri,apikey,mobile,code){
    var post_data = {  
    'apikey': apikey,
    'mobile':mobile,
    'code':code,
    };//这是需要提交的数据  
    var content = qs.stringify(post_data);  
    console.log(content);
    post(uri,content,voice_host); 
}
function post(uri,content,host){
    var options = {  
        hostname: host,
        port: 443,  
        path: uri,  
        method: 'POST',  
        headers: {  
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'  
        }  
    };
    var req = https.request(options, function (res) {  
        // console.log('STATUS: '   res.statusCode);  
        // console.log('HEADERS: '   JSON.stringify(res.headers));  
        res.setEncoding('utf8');  
        res.on('data', function (chunk) {  
            console.log('BODY: '   chunk);  
        });  
    }); 
    //console.log(content);
    req.write(content);  

    req.end();   
}

上面就是云片的全部接口,在实际使用的过程中,可以根据自己的需求,选择对应的接口使用,具体的可以看这篇文章如何使用云片API发送短信验证码,里面讲了如何使用单发短信API、群发短信API、不同短信内容批量发送API,很实用。

另外最重要的是,云片的服务还不错,短信的到达率比较高,出了问题也有人及时回复,这点在国内所有SaaS厂家中,算是做得很好的一家。

  亿美,api中有群发短信的接口,一组最大为200条。

使用Nodejs的开发者愈来越多,基于Nodejs的后台开发也多了起来,像短信验证码、短信群发、国际短信这些需求,完全可以采用第三方接口来实现,云片就提供了这样的接口。

  1.发送的手机集合放进一个队列

  3.发送结果放进已发送短信结果集合

思路:

  2.并对发送短信做记录,成功或者失败。(SqlServer)

分分快三全天计划网站 1分分快三全天计划网站 2

SmsGroupHelper

短信接口:

 

Bulk insert

View Code

分分快三全天计划网站 3分分快三全天计划网站 4

  1.给符合条件的人群发优惠券短信

批量插入数据

  2.依次读取队列,放到待发送列表,当满足200(短信组个数可配置在web.config中)条时,调用接口发送,直到队列数据发完

代码:

需求点包括:

#region Bulk批量插入

        public static Type MapCommonType(string dbtype)
        {
            if (string.IsNullOrEmpty(dbtype)) return Type.Missing.GetType();
            dbtype = dbtype.ToLower();
            Type commonType = typeof(object);
            switch (dbtype)
            {
                case "bigint": commonType = typeof(long); break;
                case "binary": commonType = typeof(byte[]); break;
                case "bit": commonType = typeof(bool); break;
                case "char": commonType = typeof(string); break;
                case "date": commonType = typeof(DateTime); break;
                case "datetime": commonType = typeof(DateTime); break;
                case "datetime2": commonType = typeof(DateTime); break;
                case "datetimeoffset": commonType = typeof(DateTimeOffset); break;
                case "decimal": commonType = typeof(decimal); break;
                case "float": commonType = typeof(double); break;
                case "image": commonType = typeof(byte[]); break;
                case "int": commonType = typeof(int); break;
                case "money": commonType = typeof(decimal); break;
                case "nchar": commonType = typeof(string); break;
                case "ntext": commonType = typeof(string); break;
                case "numeric": commonType = typeof(decimal); break;
                case "nvarchar": commonType = typeof(string); break;
                case "real": commonType = typeof(Single); break;
                case "smalldatetime": commonType = typeof(DateTime); break;
                case "smallint": commonType = typeof(short); break;
                case "smallmoney": commonType = typeof(decimal); break;
                case "sql_variant": commonType = typeof(object); break;
                case "sysname": commonType = typeof(object); break;
                case "text": commonType = typeof(string); break;
                case "time": commonType = typeof(TimeSpan); break;
                case "timestamp": commonType = typeof(byte[]); break;
                case "tinyint": commonType = typeof(byte); break;
                case "uniqueidentifier": commonType = typeof(Guid); break;
                case "varbinary": commonType = typeof(byte[]); break;
                case "varchar": commonType = typeof(string); break;
                case "xml": commonType = typeof(string); break;
                default: commonType = typeof(object); break;
            }
            return commonType;
        }

     //获取表结构
        public static List<TableColumn> GetTableColumns(string tableName)
        {
            var columns =
                DapperHelper.GetList<TableColumn>(
                    string.Format(
                        "select COLUMN_NAME,DATA_TYPE from INFORMATION_SCHEMA.COLUMNS t where t.TABLE_NAME = '{0}'",
                        tableName), null);
            return columns;
        }

        /// <summary>
        /// 获取表数据
        /// </summary>
        /// <param name="tableName">数据表名称</param>
        /// <param name="lists">数据集合</param>
        /// <returns></returns>
        public static void BulkInsert<T>(string tableName, List<T> lists)
        {
            var type = typeof (T);
            var fields = type.GetProperties();
            var columns = GetTableColumns(tableName);
            DataTable dt = new DataTable();
            foreach (var column in columns)
            {
                dt.Columns.Add(new DataColumn(column.COLUMN_NAME, MapCommonType(column.DATA_TYPE)));
            }
            foreach (var l in lists)
            {
                var row = dt.NewRow();
                foreach (var column in columns)
                {
                    var column1 = column;
                    foreach (var field in fields.Where(field => String.Equals(column1.COLUMN_NAME, field.Name, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        row[column.COLUMN_NAME] = field.GetValue(l) ?? DBNull.Value;
                        break;
                    }
                }
                dt.Rows.Add(row);
            }
            BulkToDB(dt, tableName);
        }
     
       //批量插入数据     
        public static void BulkToDB(DataTable dt, string tableName)
        {
            SqlConnection con = DapperConnection.CreateCon(Temp_dbtype, Temp_dbConKey) as SqlConnection;
            SqlBulkCopy bulkCopy = new SqlBulkCopy(con);
            bulkCopy.DestinationTableName = tableName;
            bulkCopy.BatchSize = dt.Rows.Count;

            try
            {
                con.Open();
                if (dt != null && dt.Rows.Count != 0)
                    bulkCopy.WriteToServer(dt);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                if (bulkCopy != null)
                    bulkCopy.Close();
            }
        }
        #endregion

群发helper

public class TableColumn
    {
        public string COLUMN_NAME { get; set; }
        public string DATA_TYPE { get; set; }
    }

  4.把发送结果批量插入数据库

分分快三全天计划网站 5分分快三全天计划网站 6

/// <summary>
    /// 群发短信
    /// </summary>
    public class SmsGroupHelper
    {
        //每次发送短信数量
        private readonly static int SmsCount = Globals.SafeInt(Utils.GetAppSettingByKey("SmsCount"), 0);

        /// <summary>
        /// 群发短信
        /// </summary>
        /// <param name="content">短信内容</param>
        /// <param name="phones">手机号组</param>
        /// <returns></returns>
        public static SmsResult SendGroupSms(string content, List<string> phones)
        {
            var phoneQueue = new Queue<string>();

            var unSendSmsList = new List<string>(); //待发送

            var sendedSmsList = new List<Sms>(); //已发送数量

            var sendFailed = new List<string>(); //发送失败数量

            var sendSuccess = new List<string>(); //发送成功数量

            var smsResult = new SmsResult();
            smsResult.ErrMsg = "无";
            try
            {

                //1.先发送短信 ,根据短信发送情况,保存数据库记录
                foreach (var phone in phones)
                {
                    phoneQueue.Enqueue(phone);
                }

                //是否发送短信
                var isSendFlag = false;

                while (true)
                {
                    if (phoneQueue.Count > 0)
                    {
                        var phoneNum = phoneQueue.Dequeue();

                        unSendSmsList.Add(phoneNum);

                        //如果达到一个发送短信包数量
                        if (unSendSmsList.Count == SmsCount)
                        {
                            isSendFlag = true;
                        }
                    }
                    else
                    {
                        //如果还有短信没发出去
                        if (unSendSmsList.Count > 0)
                        {
                            isSendFlag = true;
                        }
                        else
                        {
                            isSendFlag = false;
                            break;
                        }
                    }

                    if (isSendFlag)
                    {

                        var phoneArr = unSendSmsList.ToArray();

                        var resposeMsg = "";

                        //发送短信短信接口
                        var flag = SMSHelper.SendSms(content, phoneArr, out resposeMsg);

                        var sendResult = "短信发送成功";

                        if (flag)
                        {
                            sendSuccess.AddRange(unSendSmsList);
                        }
                        else
                        {
                            sendResult = "短信发送失败";
                            sendFailed.AddRange(unSendSmsList);
                        }

                        //记录总发送数量
                        sendedSmsList.AddRange(
                                unSendSmsList.Select(
                                    un =>
                                        new Sms
                                        {
                                            Phone = un,
                                            CreateTime = DateTime.Now,
                                            MessageStatus = sendResult,
                                            MessageRemarks = content
                                        }));

                        //清空未发送列表
                        unSendSmsList = new List<string>();

                        isSendFlag = false;
                    }
                }
            }
            catch (Exception ex)
            {
                smsResult.ErrMsg = ex.Message;

                while (phoneQueue.Count > 0)
                {
                    var p = phoneQueue.Dequeue();
                    sendFailed.Add(p);
                    sendedSmsList.Add(new Sms()
                    {
                        Phone = p,
                        CreateTime = DateTime.Now,
                        MessageStatus = "短信发送失败",
                        MessageRemarks = content
                    });
                }
            }
        
        
       //批量插入短信结果到数据库
            DapperHelper.BulkInsert("SmsRecord", sendedSmsList);
            smsResult.Send = sendedSmsList.Count;
            smsResult.Success = sendSuccess.Count;
            smsResult.Failed = sendFailed.Count;

            return smsResult;
        }

本文由分分快三计划发布,转载请注明来源

关键词: 分分快三计划 开发笔记 前端开发