1、需要安装qcloudsms_js,npm i qcloudsms_js --save
2、需要去腾讯云申请短信的签名和短信模板(腾讯云网址)
3、代码如下所示:
//生成4位验证码
function RndNum(n){
var rnd="";
for(var i=0;i<n;i++)
rnd+=Math.floor(Math.random()*10);
return rnd;
}
send(req,res){
// 前端页面传过来的值
const {phone,type} =req.body
const QcloudSms = require("qcloudsms_js");
// 短信应用SDK AppID
const appid = SDK AppID; // SDK AppID是1400开头
// 短信应用SDK AppKey
const appkey = "";
// 短信模板ID,需要在短信应用中申请 判断类型使用哪个短信模板
const templateId = 0;
// 签名
const SmsSign = "";
// 实例化QcloudSms
let qcloudsms = QcloudSms(appid, appkey);
let VerificationCode=RndNum(4);
//设置定期器
const countDown = (second) => {
const s = second % 60;
const m = Math.floor(second / 60);
return `${`00${m}`.slice(-2)} : ${`00${s}`.slice(-2)}`;
};
let time = 5 * 60;
const timer = setInterval(() => {
if(time < 0) {
VerificationCode=-1;
clearInterval(timer);
}
}, 1000);
let ssender = qcloudsms.SmsSingleSender();
const params = [VerificationCode];
ssender.sendWithParam(86, phone, templateId,params, SmsSign,"","",(err, row, resCode)=> {
if (err) {
console.log("err: ", err);
} else {
console.log("resCode:resCode ", resCode);
console.log("row:row", row);
}
});
}