温馨提示×

温馨提示×

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

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

OpenHarmony验证码怎么生成

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

OpenHarmony(基于 ArkTS / eTS 开发)中,生成验证码通常有两种常见方式:


一、纯前端生成验证码(推荐,简单)

适用于登录、注册等不需要服务器校验的场景。

1️⃣ 使用 Canvas 绘制验证码

示例:生成 4 位字母数字验证码

// VerificationCode.ets
import canvas from '@ohos.graphics.canvas'

@Entry
@Component
struct VerificationCode {
  private code: string = ''
  private canvasRef: CanvasRenderingContext2D | null = null

  aboutToAppear() {
    this.refreshCode()
  }

  // 生成随机验证码
  generateCode(length: number = 4): string {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
    let result = ''
    for (let i = 0; i < length; i++) {
      result += chars[Math.floor(Math.random() * chars.length)]
    }
    return result
  }

  // 绘制验证码
  drawCode() {
    if (!this.canvasRef) return
    const ctx = this.canvasRef
    ctx.clearRect(0, 0, 200, 80)

    // 背景
    ctx.fillStyle = '#f2f2f2'
    ctx.fillRect(0, 0, 200, 80)

    // 文字
    ctx.font = '40px sans-serif'
    for (let i = 0; i < this.code.length; i++) {
      ctx.fillStyle = this.randomColor()
      ctx.fillText(this.code[i], 30 + i * 40, 55)
    }

    // 干扰线
    for (let i = 0; i < 5; i++) {
      ctx.strokeStyle = this.randomColor()
      ctx.beginPath()
      ctx.moveTo(Math.random() * 200, Math.random() * 80)
      ctx.lineTo(Math.random() * 200, Math.random() * 80)
      ctx.stroke()
    }
  }

  randomColor(): string {
    const r = Math.floor(Math.random() * 256)
    const g = Math.floor(Math.random() * 256)
    const b = Math.floor(Math.random() * 256)
    return `rgb(${r},${g},${b})`
  }

  refreshCode() {
    this.code = this.generateCode()
    this.drawCode()
  }

  build() {
    Column() {
      Canvas(this.canvasRef)
        .width(200)
        .height(80)
        .onClick(() => this.refreshCode())

      Button('刷新验证码')
        .onClick(() => this.refreshCode())
    }
  }
}

✅ 特点:

  • 不依赖后端
  • 可点击刷新
  • 可加干扰线/噪点

二、后端生成验证码(安全,推荐登录场景)

适用于防止机器刷接口。

流程

  1. 前端请求验证码接口
  2. 后端:
    • 生成 code
    • 存入 Redis / Session
    • 返回图片(Base64 或流)
  3. 前端展示图片
  4. 登录时一起提交 code

示例(后端示意)

GET /api/captcha
Response:
{
  "captchaId": "abc123",
  "imageBase64": "data:image/png;base64,..."
}

前端:

Image(this.imageBase64)

三、短信 / 邮箱验证码(最常用)

// 获取短信验证码
Button('获取验证码')
  .onClick(async () => {
    await httpRequest.post('/api/sms/send', {
      phone: '13800000000'
    })
  })

后端负责:

  • 生成 6 位随机码
  • 有效期 60s
  • 防刷限制

四、推荐方案总结

场景 推荐方式
内部管理页面 前端 Canvas
用户登录 后端图片验证码
注册 / 改密 短信 / 邮箱验证码

如果你需要:

  • ✅ OpenHarmony API 9 / 10 示例
  • ✅ 验证码 组件封装
  • ✅ 配合 ArkUI-X / 鸿蒙 Next

可以告诉我你的具体版本和场景,我可以直接帮你写完整代码。

向AI问一下细节

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

AI