captcha.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. // components/captcha/captcha.js
  2. Component({
  3. /**
  4. * 组件的属性列表
  5. */
  6. properties: {
  7. phone: {
  8. type: String,
  9. required: true
  10. },
  11. },
  12. /**
  13. * 组件的初始数据
  14. */
  15. data: {
  16. generateCode: '-999999', // 点击发送验证码时生成的验证码
  17. userCode: '', // 用户输入的验证码
  18. defaultCode: '989898', // 测试时使用
  19. },
  20. /**
  21. * 组件的方法列表
  22. */
  23. methods: {
  24. /**
  25. * 监听验证码输入
  26. * @param {*} e
  27. */
  28. onInputCode(e) {
  29. this.setData({
  30. userCode: e.detail.value
  31. })
  32. },
  33. // 获取验证码
  34. getCode() {
  35. const { phone } = this.data;
  36. if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
  37. wx.showToast({
  38. title: '请输入有效的手机号码',
  39. icon: 'none'
  40. });
  41. return;
  42. }
  43. const generateCode = this.generateCode(); // 本地生成验证码(用于发送)
  44. this.setData({ generateCode, isSending: true });
  45. wx.showLoading({ title: '获取中...', mask: true });
  46. // 保存验证码到 data
  47. this.setData({ generateCode });
  48. wx.cloud.callFunction({
  49. // 云函数名称
  50. name: 'lxp',
  51. // 传给云函数的参数
  52. data: {
  53. mobile: this.data.phone,
  54. code: generateCode,
  55. },
  56. }).then(res => {
  57. if (res.result.response.code === 200) {
  58. console.log('数据获取成功 =>', res.result.response);
  59. wx.showToast({
  60. title: '验证码发送成功',
  61. icon: 'none'
  62. });
  63. // 启动倒计时
  64. this.startCountdown(60);
  65. } else {
  66. console.error('数据获取失败 =>', res.result.response);
  67. wx.showToast({
  68. title: '验证码发送失败',
  69. icon: 'none'
  70. });
  71. }
  72. }).catch(error => {
  73. console.error(error)
  74. wx.showToast({
  75. title: '验证码发送失败',
  76. icon: 'none'
  77. });
  78. })
  79. },
  80. /**
  81. * 生成验证码
  82. */
  83. generateCode() {
  84. return Math.floor(100000 + Math.random() * 900000).toString();
  85. },
  86. /**
  87. * 校验验证码
  88. */
  89. validCaptcha() {
  90. const { generateCode, userCode, defaultCode } = this.data
  91. const flag = generateCode === userCode || defaultCode === userCode
  92. const result = {
  93. flag,
  94. msg: '',
  95. }
  96. if (!flag) {
  97. result.msg = '验证码输入错误'
  98. }
  99. if (!userCode) {
  100. result.msg = '请输入验证码'
  101. }
  102. return result
  103. },
  104. startCountdown(seconds) {
  105. this.setData({ countdown: seconds });
  106. const timer = setInterval(() => {
  107. if (this.data.countdown <= 1) {
  108. clearInterval(timer);
  109. this.setData({ countdown: 0, isSending: false }); // 倒计时结束后重置 isSending
  110. } else {
  111. this.setData({ countdown: this.data.countdown - 1 });
  112. }
  113. }, 1000);
  114. },
  115. }
  116. })