1, first install 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"}
// and generates a random number; the configuration file in a global variable
the let the require FS = ( "FS" ); function RangeCode (length) { // randomly generated codes specified number var Range = function (Start, End) { var Array = []; for ( var I = Start; I <End; ++ I) Array.push (I); return Array; }; the let getnum = function () { the let NUM = Math.floor (Math.random () * 10 ); IF (NUM == 0 ) { return getnum (); } the 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, texting
//npm install @alicloud/pop-core -S
const log = require('./logger');
const utiltools = require('./UtilTools');
const redis = require("./RedisHelper");
the async function SendSMSCode (IP, phoneNum, the callback) { the try { // forming short code the let utiltools.RangeCode code = (. 6 ); // set the expiration time codes 3min, the class is instantiated the let codeobj = new new smsCode.CMSCode (IP, code, phoneNum,. 1, new new a Date (( new new a Date ()) the getTime (). 3 * 60 + * 1000. )); const the SMSClient = the require ( '@ alicloud / SMS-SDK' ) // ACCESS_KEY_ID / actual application ACCESS_KEY_SECRET Alternatively account information const accessKeyId = '***' const secretAccessKey = '***' // initialization sms_client var SMSClient = new new the SMSClient ({accessKeyId, secretAccessKey}) the let redisTemp = the await redis.GetString (phoneNum); IF (redisTemp && new new . a Date () the getTime () - redisTemp <1000 ) { log.logger.info ( "Get Redis cache Mobile time: "+ redisTemp); the let returnobj = {the Result: 0, resultObj:"! occurs too often " }; callback.send (returnobj); callback.end (); return ; } // send message smsClient.sendSMS ({ PhoneNumbers: phoneNum, SignName: 'fishing App', TemplateCode: 'the SMS *** _' , TemplateParam: '{ "code":' + + code '}' }) the then (. Function (RES) { the let {Code} = RES; IF (Code === 'the OK ' ) { // returns the process parameters log.logger.info ( "sent successfully NUM:" phoneNum + + "code:" + code); SetSMSArray (codeobj); the let returnobj = {the Result:. 1 }; callback.send (returnobj ); callback.end (); } the 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())
}