温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

OpenHarmony验证码怎么实现

发布时间:2026-09-01 15:36:27 来源:亿速云 阅读:95 作者:小樊 栏目:软件技术

OpenHarmony(鸿蒙) 里实现“验证码”通常分 两种场景

  1. 图形验证码(图片验证码)
  2. 短信 / 邮箱验证码(后端生成 + 前端校验)

下面我分别说 实现思路 + 示例代码(ArkTS)


一、短信 / 邮箱验证码(最常见)

✅ 验证码本身 不在前端生成,前端只负责:

  • 请求发送验证码
  • 用户输入
  • 提交校验

1️⃣ 前端(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))

2️⃣ 后端(示例:Node.js)

const codes = {}

function sendCode(phone) {
  const code = Math.floor(100000 + Math.random() * 900000)
  codes[phone] = code
  // 调短信服务
}

function verifyCode(phone, code) {
  return codes[phone] == code
}

安全建议

  • 验证码有效期(5 分钟)
  • 限制发送频率
  • 服务端校验,不信任前端

二、图形验证码(前端生成)

适合:登录防刷、简单验证

1️⃣ 使用 Canvas 绘制

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


如果你愿意,我可以:

  • 给你 完整 ArkTS 登录页示例
  • OpenHarmony + Spring Boot 验证码方案
  • 帮你做 滑块 / 拼图验证码

你现在是 App 登录验证 还是 接口防刷

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI