uniapp图形验证码
uniapp 图形验证码实现方法
在 uniapp 中实现图形验证码功能可以通过多种方式完成,以下是几种常见的实现方案:
使用第三方验证码服务
接入第三方验证码服务如极验、腾讯云验证码等,这些服务通常提供 SDK 或 API 接口。
在项目中引入第三方服务的 JavaScript SDK,按照文档进行配置和调用。这种方式安全性较高,但可能需要付费。

自定义绘制验证码
通过 Canvas 自行绘制验证码图形,适用于简单需求。
// 在 vue 文件中
<template>
<view>
<canvas canvas-id="verifyCanvas" @tap="refreshCode"></canvas>
<input v-model="inputCode" placeholder="请输入验证码"/>
</view>
</template>
<script>
export default {
data() {
return {
code: '',
inputCode: ''
}
},
onLoad() {
this.refreshCode()
},
methods: {
refreshCode() {
const ctx = uni.createCanvasContext('verifyCanvas', this)
const code = this.generateCode(4)
this.code = code
ctx.clearRect(0, 0, 150, 50)
ctx.setFillStyle(this.randomColor(180, 240))
ctx.fillRect(0, 0, 150, 50)
ctx.setFontSize(30)
ctx.setFillStyle(this.randomColor(50, 160))
for (let i = 0; i < code.length; i++) {
ctx.setFillStyle(this.randomColor(50, 160))
ctx.fillText(code[i], 20 + i * 30, 35)
}
for (let i = 0; i < 5; i++) {
ctx.strokeStyle = this.randomColor(40, 180)
ctx.beginPath()
ctx.moveTo(Math.random() * 150, Math.random() * 50)
ctx.lineTo(Math.random() * 150, Math.random() * 50)
ctx.stroke()
}
ctx.draw()
},
generateCode(length) {
const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
let code = ''
for (let i = 0; i < length; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length))
}
return code
},
randomColor(min, max) {
const r = min + Math.floor(Math.random() * (max - min))
const g = min + Math.floor(Math.random() * (max - min))
const b = min + Math.floor(Math.random() * (max - min))
return `rgb(${r}, ${g}, ${b})`
}
}
}
</script>
使用后端生成的验证码
通过接口从服务器获取验证码图片,这种方式更安全,可以防止前端生成的验证码被破解。

前端通过接口请求获取验证码图片,后端返回 base64 格式的图片数据或图片 URL。
// 前端请求示例
getVerifyCode() {
uni.request({
url: 'https://your-api.com/getVerifyCode',
success: (res) => {
this.verifyCodeUrl = res.data.url
this.verifyCodeToken = res.data.token
}
})
}
验证码校验逻辑
无论采用哪种方式生成验证码,都需要实现校验逻辑:
checkVerifyCode() {
if (this.inputCode.toLowerCase() !== this.code.toLowerCase()) {
uni.showToast({
title: '验证码错误',
icon: 'none'
})
return false
}
return true
}
注意事项
- 验证码应包含数字和字母组合,增加复杂度
- 建议对验证码进行大小写不敏感处理
- 验证码应有有效期限制,通常为 3-5 分钟
- 重要操作应配合后端二次验证
- 防止暴力破解,限制验证码尝试次数
以上方法可根据项目实际需求选择或组合使用,安全要求高的场景建议采用后端生成验证码的方式。





