? ? ? ? 基于騰訊云開發(Tencent Cloud Base)實現小程序郵箱驗證找回密碼功能的完整邏輯說明及關鍵代碼實現。結合安全性和開發效率,方案采用 ??云函數 + 小程序前端?? 的架構,使用 ??Nodemailer?? 發送郵件。Nodemailer 是一個專為 Node.js 設計的開源郵件發送庫,用于在服務端高效、靈活地處理電子郵件發送任務。它通過簡化郵件傳輸協議(如 SMTP)的復雜性,為開發者提供了強大的郵件管理能力。
一、實現原理
用“快遞站”比喻來解釋這個流程:?
-
??快遞站代發包裹(系統統一發驗證碼)??
公司搭了個快遞站(系統郵箱),專門代發驗證碼“包裹”。用戶填個收件地址(郵箱),站長立刻打包發出📮。 -
??用戶只管收件(注冊流程)??
用戶啥也不用干,留完地址就坐等收件。拆開包裹填個驗證碼,立馬進門(完成驗證)?。 -
??站長領把鑰匙(管理員配一次)??
給快遞站申請個專屬鑰匙(獲取QQ郵箱授權碼)🔑;把鑰匙存進公司保險柜(更新數據庫)。?從此站長隨時能開門發件,永不失效!
二、功能邏輯流程圖如下所示:
三、JavaScript代碼
Page({data: {account: '',email: '',code: '',newPassword: ''},// 輸入綁定onAccountInput(e) { this.setData({ account: e.detail.value }); },onEmailInput(e) { this.setData({ email: e.detail.value }); },onCodeInput(e) { this.setData({ code: e.detail.value }); },onPwdInput(e) { this.setData({ newPassword: e.detail.value }); },// 發送驗證碼async sendCode() {const { account, email } = this.data;try {const res = await wx.cloud.callFunction({name: 'sendEmailCode',data: { account, email }});wx.showToast({ title: '驗證碼已發送至郵箱' });} catch (err) {wx.showToast({ title: '發送失敗', icon: 'error' });}},// 重置密碼async resetPassword() {const { account, email, code, newPassword } = this.data;try {await wx.cloud.callFunction({name: 'verifyCodeAndReset',data: { account, email, code, newPassword }});wx.showToast({ title: '密碼重置成功' });} catch (err) {wx.showToast({ title: '驗證碼錯誤或已過期', icon: 'error' });}}
});
四、云函數實現(Node.js)
1. 發送驗證碼云函數 (sendEmailCode
)
const cloud = require('wx-server-sdk');
const nodemailer = require('nodemailer');
cloud.init();// 配置QQ郵箱(需開啟SMTP并獲取授權碼)
const transporter = nodemailer.createTransport({host: 'smtp.qq.com',port: 465,secure: true,auth: {user: 'your_email@qq.com', // 發件郵箱pass: 'your_authorization_code' // QQ郵箱授權碼}
});exports.main = async (event) => {const { account, email } = event;const db = cloud.database();// 校驗賬號和郵箱是否匹配const user = await db.collection('users').where({account,email}).get();if (user.data.length === 0) {throw new Error('賬號或郵箱不匹配');}// 生成6位隨機驗證碼const code = Math.random().toString().slice(2, 8);// 存儲驗證碼(有效期5分鐘)await db.collection('verificationCodes').add({data: {account,code,email,createdAt: new Date()}});// 發送郵件const mailOptions = {from: 'your_email@qq.com',to: email,subject: '密碼重置驗證碼',html: `<p>您的驗證碼是:<b>${code}</b>,5分鐘內有效</p>`};await transporter.sendMail(mailOptions);return { success: true };
};
2.驗證并重置密碼云函數 (verifyCodeAndReset
)
exports.main = async (event) => {const { account, email, code, newPassword } = event;const db = cloud.database();const now = new Date();// 查詢有效驗證碼(5分鐘內)const codeRecord = await db.collection('verificationCodes').where({account,email,code}).orderBy('createdAt', 'desc').get();// 驗證碼校驗if (codeRecord.data.length === 0 || now - codeRecord.data[0].createdAt > 5 * 60 * 1000) {throw new Error('驗證碼錯誤或已過期');}// 更新密碼(需加密存儲)const hashedPassword = require('crypto').createHash('md5').update(newPassword).digest('hex');await db.collection('users').where({ account }).update({data: { password: hashedPassword }});// 刪除已用驗證碼await db.collection('verificationCodes').doc(codeRecord.data[0]._id).remove();return { success: true };
};
3.在數據庫創建systemConfig集合
{"type": "email","email": "your_email@qq.com", // 完整的QQ郵箱地址"host": "smtp.qq.com", // SMTP服務器地址"port": 465, // 必須為465端口"authCode": "your_16_digit_code", // 從QQ郵箱設置獲取的16位授權碼"service": "QQ", // 服務標識(可選)"senderName": "系統通知", // 發件人顯示名稱(可選)"secure": true // 啟用SSL加密傳輸
}
五、安全增強建議
- ??郵箱授權碼管理??:將授權碼存入騰訊云??環境變量??(
process.env.EMAIL_AUTH_CODE
),避免硬編碼。 - ??驗證碼時效性?:數據庫存儲驗證碼時記錄時間戳,校驗時檢查是否超過5分鐘。
- ??防刷機制?:限制同一郵箱/賬號的發送頻率(如1分鐘1次),可在云函數中增加頻率校驗邏輯。
- ??密碼加密?:使用 ??MD5/SHA256?? 對新密碼加密存儲(示例中使用了MD5)。
?六、注意事項
- ??QQ郵箱配置??
- 需登錄QQ郵箱網頁版 → 設置 → 賬戶 → 開啟 ??SMTP服務?? → 獲取16位授權碼。
- ??云函數依賴安裝??
- 在云函數目錄下執行?
npm install nodemailer
?安裝郵件模塊。
- 在云函數目錄下執行?
- ??真機測試??
- 微信開發者工具中可能無法調用云函數發送郵件,需使用真機測試。