• 通过node实现阿里云短信接口,并将手机号缓存,通过Redis过期时间限制频繁发短信


    1,首先安装Redis , npm install redis --save

    RedisHelper.js

    const redis = require('redis'); function SetString(key,value) { let redishost = global.urls.controllers.RedisServer.split(":")[0]; let redisport = global.urls.controllers.RedisServer.split(":")[1]; const client = redis.createClient(redisport, redishost, {}); client.select(2, function() { /* ... */ }); //错误监听? client.on("error", function (err) { console.log("Error " + err); }); client.set(key, value,redis.print); // 三分钟后过期 client.expire(key, 180); client.quit(); } function GetString(key) { return new Promise((resolve, reject) => { let redishost = global.urls.controllers.RedisServer.split(":")[0]; let redisport = global.urls.controllers.RedisServer.split(":")[1]; const client = redis.createClient(redisport, redishost, {}); client.select(2, function() { /* ... */ }); //错误监听? client.on("error", function (err) { console.log("Error " + err); }); // This will return a JavaScript String client.get(key,function(err,reply){ if (err) throw err; console.log('Got: ' + reply); resolve(reply) client.quit(); }); }) } exports.SetString = SetString; exports.GetString = GetString;
    config.josn

    controllers:{"RedisServer":"127.0.0.1:6379"}
    //生成随机数和;将配置文件放到全局变量中
    let fs = require("fs"); function RangeCode(length) { //随机产生指定位数验证码 var range = function (start, end) { var array = []; for (var i = start; i < end; ++i) array.push(i); return array; }; let getnum = function () { let num = Math.floor(Math.random() * 10); if(num==0){ return getnum(); } else return num; } var randomstr = range(0, length).map(function (x) { return getnum(); }).join(''); return randomstr; } function UpdateConfig() { let configfile = "../config/ServerConfig.json"; var urls = JSON.parse(fs.readFileSync(configfile)); global.urls = urls; return true; } exports.RangeCode = RangeCode; exports.UpdateConfig = UpdateConfig;

    2,发短信

    //npm install @alicloud/pop-core -S

    const log = require('./logger');
    const utiltools = require('./UtilTools');
    const redis = require("./RedisHelper");
    async function SendSMSCode(ip, phonenum, callback) {
        try {
            // 生成短信码
            let code = utiltools.RangeCode(6);
            // 设置验证码过期时间3min,实例化类
            let codeobj = new smsCode.CMSCode(ip, code, phonenum, 1, new Date((new Date()).getTime() + 3 * 60 * 1000));
            const SMSClient = require('@alicloud/sms-sdk')
            // ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
            const accessKeyId = '***'
            const secretAccessKey = '***'
            //初始化sms_client
            var smsClient = new SMSClient({accessKeyId, secretAccessKey})
            let redisTemp =await redis.GetString(phonenum);
            if(redisTemp && new Date().getTime() - redisTemp < 1000){
                log.logger.info("获取Redis缓存手机时间:" + redisTemp);
                let returnobj = {Result: 0, Resultobj: "操作过于频繁!"};
                callback.send(returnobj);
                callback.end();
                return;
            }
    
            //发送短信
            smsClient.sendSMS({
                PhoneNumbers: phonenum,
                SignName: '钓鱼App',
                TemplateCode: 'SMS_***',
                TemplateParam: '{"code":' + code + '}'
            }).then(function (res) {
                let {Code} = res;
                if (Code === 'OK') {
                    //处理返回参数
                    log.logger.info("发送成功num:" + phonenum + "code:" + code);
                    SetSMSArray(codeobj);
                    let returnobj = {Result: 1};
                    callback.send(returnobj);
                    callback.end();
                }else {
                    log.logger.error("发送失败:" + Code);
                    let returnobj = {Result: 0, Resultobj: "返回失败",err};
                    callback.send(returnobj);
                    callback.end();
                }
            }, function (err) {
                log.logger.error(err);
                var returnobj = {Result: 0, Resultobj: "错误",err};
                callback.send(returnobj);
                callback.end();
            })
        } catch (Exception) {
            log.logger.error(Exception);
        }
    }
    function CompareSmsCode(phonenum, code) {
        var i = global.SMScodearray.length;
        while (i--) {
            if (global.SMScodearray[i].getPhonum() == phonenum) {
                if ((global.SMScodearray[i].getExpireTime() - new Date()) > 0) {
                    log.logger.debug("验证未过期:" + global.SMScodearray[i].getExpireTime());
                    return code == global.SMScodearray[i].getCode();
                }
                else {
                    log.logger.debug("验证码已过期:" + global.SMScodearray[i].getExpireTime());
                    return false;
                }
    
            }
        }
        return false;
    }
    function SetSMSArray(smsmodel) {
    // 定义全局存手机号和验证码
    var i = global.SMScodearray.length;
    let isexist = false;
    while (i--) {
    if (global.SMScodearray[i].getPhonum() == smsmodel.getPhonum()) {
    global.SMScodearray[i].setTimes(global.SMScodearray[i].getTimes() + 1);
    global.SMScodearray[i].setCode(smsmodel.getCode());
    global.SMScodearray[i].setExpireTime(smsmodel.getExpireTime());
    isexist = true;
    }
    }
    if (!isexist) {
    global.SMScodearray.push(smsmodel);
    }
      //动态存手机号
    redis.SetString(smsmodel.getPhonum(), new Date().getTime())
    }
     
    本想把日子过成诗,时而简单,时而精致,不料日子却过成了一首歌,时而不靠谱,时而不着调
  • 相关阅读:
    【Coursera】Third Week(2)
    【TCP/IP详解 卷一:协议】第二章:链路层
    【Coursera】Third Week(1)
    【Coursera】SecondWeek(2)
    【Coursera】SecondWeek(1)
    【Coursera】History: Dawn of Electronic Computing学后小结
    【TCP/IP详解 卷一:协议】第一章概论 学习笔记
    NS3 fifth.cc 拥塞窗口实例
    NS3 利用Gnuplot生成拥塞窗口例子fifth.cc的png图像
    C++小结:迟到的小结和重新起航的故事
  • 原文地址:https://www.cnblogs.com/chuanq/p/12055890.html
Copyright © 2020-2023  润新知