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())
}