一、阿里云短信服务
打开阿里云短信服务控制台
1.新增资质
2.新增模板与签名
3.等待审核通过
二、node代码
1.首先需要下载依赖
npm i @alicloud/pop-core --save
2.引入依赖
关键信息建议放环境变量中
accessKeyId和accessKeySecret在这里↓
以下是代码
const Core = require('@alicloud/pop-core');
const Captcha = require("../common/Captcha")
const capt = Captcha()
let client = new Core({
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint: 'https://dysmsapi.aliyuncs.com',
apiVersion: '2017-05-25'
});
let requestOption = {
method: 'POST',
formatParams: false,
};
3.验证代码的实现
function Captcha() {
let captchaObj = {}
let status = {over: 0, success: 1, error: 2}
let setCode = (phone, code) => {
let time = Date.now()
if (captchaObj[phone] && captchaObj[phone].time && !isExceed60Seconds(captchaObj[phone].time, time)) {
return false
} else {
captchaObj[phone] = {code, time}
return true
}
}
//是否正确且不超时
let checkCode = (phone, code) => {
let time = Date.now()
let before = captchaObj[phone].time
let isOver = isTimeDifferenceGreaterThanFiveMinutes(before, time)
if (isOver) {
return status.over
} else {
return checkIfDif(captchaObj[phone], code)
}
}
function checkIfDif(before, cur) {
// console.log(before, cur)
if (before && before.code === cur) {
return status.success
} else {
return status.error
}
}
const getCode = (phone) => {
return captchaObj[phone]?.code
}
function isTimeDifferenceGreaterThanFiveMinutes(before, cur) {
// 计算时间差(单位:毫秒)
let difference = Math.abs(cur - before); // 使用Math.abs确保时间差始终为正数
// 将毫秒转换为分钟
let differenceInMinutes = difference / (1000 * 60);
// 判断时间差是否大于五分钟
return differenceInMinutes > 5;
}
function isExceed60Seconds(before, cur) {
// 计算时间差,单位为毫秒
let diff = cur - before;
// 将毫秒转换为秒
let secondsDiff = diff / 1000;
// 判断是否超过60秒
return secondsDiff > 60;
}
return {setCode, checkCode, getCode}
}
module.exports = Captcha
4.在接口中使用
router.post("/sendCode", (req, res) => {
const {tel_number} = req.body
let code = methods.generateFourDigitRandom()
let setResult = capt.setCode(tel_number, code)
if (setResult) {
let params = {
"SignName": process.env['ALIBABA_CLOUD_SIGN_NAME'],//资质名称
"TemplateCode": process.env['ALIBABA_CLOUD_TMP_CODE'],//模板CODE
"PhoneNumbers": tel_number,
"TemplateParam": JSON.stringify(({code: code}))
}
client.request('SendSms', params, requestOption).then((result) => {
res.send(Result.success({msg: "成功!", data: result}))
}, (ex) => {
res.send(Result.fail({errmsg: "请求失败!", error: ex}))
})
} else {
res.send(Result.validateFailed({errmsg: "发送太过频繁,请稍后再试!"}))
}
})
标签:code,短信,nodejs,验证码,captchaObj,phone,let,return,before
From: https://blog.csdn.net/xswl233333/article/details/141123953