uniapp验证码校验
验证码校验的实现方法
在UniApp中实现验证码校验通常涉及前端生成或获取验证码,以及后端验证逻辑。以下是常见的实现方式:
前端生成图形验证码
使用canvas绘制随机验证码图形:

// 在vue文件中
<template>
<canvas canvas-id="verifyCanvas" @tap="refreshCode"></canvas>
</template>
<script>
export default {
data() {
return {
verifyCode: ''
}
},
methods: {
createCode() {
const ctx = uni.createCanvasContext('verifyCanvas')
const pool = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
this.verifyCode = ''
for (let i = 0; i < 4; i++) {
const char = pool[Math.floor(Math.random() * pool.length)]
this.verifyCode += char
ctx.setFontSize(20)
ctx.setFillStyle(this.getRandomColor())
ctx.fillText(char, 10 + i * 15, 20)
}
// 绘制干扰线
for (let i = 0; i < 3; i++) {
ctx.strokeStyle = this.getRandomColor()
ctx.beginPath()
ctx.moveTo(Math.random() * 60, Math.random() * 30)
ctx.lineTo(Math.random() * 60, Math.random() * 30)
ctx.stroke()
}
ctx.draw()
},
getRandomColor() {
return `rgb(${Math.floor(Math.random() * 200)},
${Math.floor(Math.random() * 200)},
${Math.floor(Math.random() * 200)})`
},
refreshCode() {
this.createCode()
}
},
mounted() {
this.createCode()
}
}
</script>
短信验证码集成
对接短信服务商API发送验证码:
methods: {
sendSmsCode() {
if (this.countdown > 0) return
uni.request({
url: 'https://your-api.com/send-sms',
method: 'POST',
data: {
phone: this.phoneNumber
},
success: (res) => {
if (res.data.success) {
this.countdown = 60
const timer = setInterval(() => {
this.countdown--
if (this.countdown <= 0) clearInterval(timer)
}, 1000)
}
}
})
}
}
验证码校验逻辑
提交表单时验证用户输入:

verifyInput() {
if (this.userInput !== this.verifyCode) {
uni.showToast({
title: '验证码错误',
icon: 'none'
})
return false
}
return true
}
后端验证实现
Node.js示例验证接口:
// Express路由
app.post('/verify', (req, res) => {
const { phone, code } = req.body
// 从缓存获取该手机号的验证码
const storedCode = cache.get(`sms_${phone}`)
if (!storedCode || storedCode !== code) {
return res.json({ success: false, message: '验证码错误或已过期' })
}
// 验证成功后清除缓存
cache.del(`sms_${phone}`)
res.json({ success: true })
})
安全增强措施
验证码应当设置有效期(通常5-10分钟),并限制发送频率(如同一手机号60秒内只能发送一次)。后端需要记录发送时间戳和验证码,使用Redis等缓存服务存储临时验证码。
图形验证码应增加扭曲、噪点等干扰因素防止OCR识别。短信验证码建议使用6位随机数字组合,避免使用连续或重复数字。






