前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

微信小程序验证码实现指南

qiguaw 2025-05-14 15:53:36 资源文章 2 ℃ 0 评论

在微信小程序中实现验证码功能通常需要前后端协作,以下是关键步骤和示例代码:

一、前端实现(小程序端)

javascript

// WXML

<button bindtap="getCode" disabled="{{isCounting}}">

{{countdownText}}

</button>


// JS

Page({

data: {

isCounting: false,

countdownText: '获取验证码'

},


getCode() {

const phone = this.data.phone; // 需先获取用户输入的手机号

if (!/^1[3-9]\d{9}$/.test(phone)) {

wx.showToast({ title: '手机号格式错误', icon: 'none' });

return;

}


this.setData({ isCounting: true });

let seconds = 60;


// 发送请求

wx.request({

url: 'https://yourdomain.com/api/send-code',

method: 'POST',

data: { phone },

success: (res) => {

if (res.data.code === 200) {

wx.showToast({ title: '验证码已发送' });

}

}

});


// 倒计时

const timer = setInterval(() => {

seconds--;

this.setData({

countdownText: `${seconds}秒后重发`

});


if (seconds <= 0) {

clearInterval(timer);

this.setData({

isCounting: false,

countdownText: '重新获取'

});

}

}, 1000);

}

})

二、后端实现(示例Node.js)

javascript

const express = require('express');

const Redis = require('ioredis');

const redis = new Redis();

const router = express.Router();


// 发送验证码接口

router.post('/send-code', async (req, res) => {

const { phone } = req.body;


// 频率限制(1分钟间隔)

const lastSent = await redis.get(`sms_cooldown:${phone}`);

if (lastSent && Date.now() - lastSent < 60000) {

return res.json({ code: 400, msg: '操作过于频繁' });

}


// 生成6位随机码

const code = Math.floor(100000 + Math.random() * 900000);


// 存储验证码(5分钟有效)

await redis.setex(`sms_code:${phone}`, 300, code);

await redis.setex(`sms_cooldown:${phone}`, 60, Date.now());


// 调用短信服务(示例用伪代码)

try {

await sendSMS(phone, `您的验证码是:${code},5分钟内有效`);

res.json({ code: 200, msg: '发送成功' });

} catch (err) {

console.error('短信发送失败', err);

res.json({ code: 500, msg: '发送失败' });

}

});


// 验证码校验接口

router.post('/verify-code', async (req, res) => {

const { phone, code } = req.body;

const storedCode = await redis.get(`sms_code:${phone}`);


if (!storedCode || storedCode !== code.toString()) {

return res.json({ code: 400, msg: '验证码错误或已过期' });

}


// 验证通过后删除缓存

await redis.del(`sms_code:${phone}`);

res.json({ code: 200, msg: '验证成功' });

});

三、关键注意事项

  1. 安全防护

O 添加图形验证码/滑动验证(通过<button open-type="getPhoneNumber">获取微信官方手机号)

O IP限流(防止恶意调用)

O 敏感操作日志记录

  1. 短信服务选择

O 腾讯云短信(推荐,与微信生态集成好)

O 阿里云、云片等第三方服务

O 需提前申请短信模板和签名

  1. 用户体验优化

O 本地缓存倒计时状态(防止页面切换后状态丢失)

O 错误重试机制

O 国际化手机号处理(+86前缀等)

  1. 微信规范要求

O 手机号获取需用户主动触发

O 敏感信息需加密传输

O 遵守《微信小程序运营规范》

建议优先考虑使用微信官方提供的手机号快速验证组件,通过<button open-type="getPhoneNumber">获取加密数据后到后端解密,可免去手动输入手机号的步骤,同时更符合平台规范。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表