上一篇
html页面的短信验证
- 行业动态
- 2025-04-30
- 3
HTML页面实现短信验证需结合前端表单与后端接口,前端采集手机号并触发验证码发送,后端调用云通信服务(如阿里云/ 酷盾安全)生成并下发验证码,通过Session/Redis存储校验码,前端提交后比对验证结果,配合倒计时按钮防重复发送,确保数据安全与
短信验证功能实现流程
基本流程说明
短信验证通常包含以下步骤:
- 用户在前端输入手机号
- 前端发送请求到后端
- 后端生成验证码并发送短信
- 用户收到短信并输入验证码
- 前端发送验证请求到后端
- 后端校验验证码有效性
前端实现
HTML结构
<div id="sms-container"> <input type="tel" id="phone-input" placeholder="请输入手机号" maxlength="11" /> <button id="send-code">获取验证码</button> <input type="text" id="code-input" placeholder="请输入验证码" /> <button id="verify-code">验证</button> <div id="message"></div> </div>
JavaScript逻辑
let timer = null; const sendBtn = document.getElementById('send-code'); const verifyBtn = document.getElementById('verify-code'); const messageDiv = document.getElementById('message'); // 获取验证码按钮事件 sendBtn.addEventListener('click', () => { const phone = document.getElementById('phone-input').value; // 基础验证 if (!/^1[3-9]d{9}$/.test(phone)) { messageDiv.innerText = '请输入正确的手机号'; return; } // 禁用按钮并启动倒计时 sendBtn.disabled = true; countdown(60); // 发送网络请求 fetch('/api/send-sms', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({phone}) }) .then(res => res.json()) .then(data => { if (data.success) { messageDiv.innerText = '验证码已发送'; } else { messageDiv.innerText = data.message; resetSendButton(); } }); }); // 验证验证码 verifyBtn.addEventListener('click', () => { const phone = document.getElementById('phone-input').value; const code = document.getElementById('code-input').value; fetch('/api/verify-sms', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({phone, code}) }) .then(res => res.json()) .then(data => { messageDiv.innerText = data.message; }); }); // 倒计时函数 function countdown(seconds) { let count = seconds; sendBtn.innerText = `${count}秒后重试`; timer = setInterval(() => { count--; sendBtn.innerText = `${count}秒后重试`; if (count <= 0) { clearInterval(timer); resetSendButton(); } }, 1000); } // 重置发送按钮 function resetSendButton() { sendBtn.disabled = false; sendBtn.innerText = '获取验证码'; }
后端实现(示例:Node.js + Express)
路由配置
const express = require('express'); const router = express.Router(); const smsService = require('../services/smsService'); // 短信服务模块 // 发送短信接口 router.post('/send-sms', async (req, res) => { const { phone } = req.body; try { const code = generateVerificationCode(); await smsService.sendSMS(phone, code); // 调用短信服务 // 存储验证码到缓存(如Redis) cache.set(phone, code, 'EX', 5 60); // 设置5分钟有效期 res.json({ success: true }); } catch (error) { res.json({ success: false, message: error.message }); } }); // 验证接口 router.post('/verify-sms', (req, res) => { const { phone, code } = req.body; const storedCode = cache.get(phone); if (storedCode === code) { res.json({ success: true, message: '验证成功' }); } else { res.json({ success: false, message: '验证码错误' }); } });
短信服务模块示例(使用Twilio)
const twilio = require('twilio'); const client = new twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN); function generateVerificationCode() { return Math.floor(100000 + Math.random() 900000).toString(); // 6位随机数 } async function sendSMS(phone, code) { await client.messages.create({ body: `您的验证码是:${code}`, from: process.env.TWILIO_PHONE_NUMBER, // 短信发送号码 to: phone }); } module.exports = { sendSMS, generateVerificationCode };
主流短信服务商对比
服务商 | 特点 | 国内支持 | 价格(每条) | API语言支持 |
---|---|---|---|---|
Twilio | 国际短信服务,稳定性高,文档完善 | 否 | $0.01 USD起 | Node.js/Python/Java等 |
阿里云短信服务 | 国内三网合一,支持全球短信,大厂服务 | 是 | ¥0.045起 | Java/Python/PHP/Node.js |
酷盾安全短信 | 国内三网合一,性价比高,提供签名定制 | 是 | ¥0.045起 | Java/Python/Node.js/Go |
网易云信 | 即时通讯+短信验证一体化服务,适合社交应用 | 是 | ¥0.048起 | JavaScript/Java/Object-C |
Plivo | 低成本国际短信,适合初创企业 | 否 | $0.01 USD起 | Python/Node.js/PHP |
Nexmo | 全球覆盖,支持语音和短信,企业级解决方案 | 是 | $0.007 USD起 | Node.js/Java/Python |
常见问题与解答
Q1:如何选择短信验证码服务商?
A:主要考虑以下因素:
- 业务范围:是否需要国际短信支持
- 到达率:选择通道稳定的服务商(建议测试不同地区)
- 价格:对比单价和阶梯计价规则
- API易用性:SDK支持情况和文档完善程度
- 附加功能:如语音验证码、状态回调等扩展功能
- 合规性:是否满足数据安全要求(如GDPR)
Q2:如何防止短信验证码被暴力破解?
A:可采取以下措施:
- 限制发送频率:同一手机号每天最多获取5次验证码
- 验证码有效期:设置5-10分钟有效时间(需后端校验)
- 错误次数限制:连续错误3次后锁定验证功能1小时
- 图形验证码:在获取短信前增加滑动/点击验证
- IP限流:限制同一IP的请求频率(结合地理位置判断)
- 异常监控:记录异常请求