在 OpenHarmony(鸿蒙) 里实现“验证码”通常分 两种场景:
下面我分别说 实现思路 + 示例代码(ArkTS)。
✅ 验证码本身 不在前端生成,前端只负责:
- 请求发送验证码
- 用户输入
- 提交校验
// 发送验证码
async function sendCode(phone: string) {
const res = await fetch('https://your-api.com/sendCode', {
method: 'POST',
body: JSON.stringify({ phone })
})
const data = await res.json()
if (data.success) {
console.info('验证码已发送')
}
}
// 校验验证码
async function verifyCode(phone: string, code: string) {
const res = await fetch('https://your-api.com/verifyCode', {
method: 'POST',
body: JSON.stringify({ phone, code })
})
const data = await res.json()
return data.success
}
UI 示例(简化):
TextInput({ placeholder: '手机号' })
TextInput({ placeholder: '验证码' })
Button('获取验证码').onClick(() => sendCode(phone))
Button('登录').onClick(() => verifyCode(phone, code))
const codes = {}
function sendCode(phone) {
const code = Math.floor(100000 + Math.random() * 900000)
codes[phone] = code
// 调短信服务
}
function verifyCode(phone, code) {
return codes[phone] == code
}
✅ 安全建议
适合:登录防刷、简单验证
import canvas from '@ohos.graphics.canvas'
@Entry
@Component
struct CaptchaPage {
private code: string = ''
private ctx: CanvasRenderingContext2D
aboutToAppear() {
this.generateCode()
}
generateCode() {
this.code = Math.random().toString(36).slice(2, 6)
}
build() {
Column() {
Canvas(this.ctx)
.width(120)
.height(40)
.onReady(() => {
this.ctx.fillStyle = '#eee'
this.ctx.fillRect(0, 0, 120, 40)
this.ctx.fillStyle = '#333'
this.ctx.font = '24px'
this.ctx.fillText(this.code, 10, 30)
})
Button('刷新')
.onClick(() => {
this.generateCode()
})
}
}
}
| 场景 | 推荐 |
|---|---|
| 登录 / 注册 | 短信验证码 |
| 管理后台 | 图形验证码 |
| 高安全 | 图形 + 短信 |
❌ 前端生成验证码并校验(不安全)
❌ 验证码不过期
❌ 明文存储
✅ 服务端生成
✅ 限时 + 限次
✅ HTTPS
如果你愿意,我可以:
你现在是 App 登录验证 还是 接口防刷?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。