send-verification-code.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (C) 2020 Tencent Cloud.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. 'use strict';
  17. const sendSMS = require('./send-sms');
  18. const { verificationCodeCollection, verificationCodeTemplateId, verificationCodeLength } = require('./config');
  19. /**
  20. * 发送短信验证码
  21. * @async
  22. * @param {object} params - 参数包装对象
  23. * @param {string} params.phoneNumber - 手机号码
  24. * @return {Promise<void>} 验证码发送状态(无异常代表发送成功)
  25. */
  26. async function sendVerificationCode({ phoneNumber }) {
  27. // 配置校验
  28. if (!verificationCodeCollection) {
  29. throw new Error('请在云函数SMS模块中配置verificationCodeCollection');
  30. }
  31. if (!verificationCodeTemplateId) {
  32. throw new Error('请在云函数SMS模块中配置verificationCodeTemplateId');
  33. }
  34. if (isNaN(verificationCodeLength) || verificationCodeLength < 4 || verificationCodeLength > 8) {
  35. throw new Error('请在云函数SMS模块中配置有效的verificationCodeLength');
  36. }
  37. // 参数校验
  38. if (!phoneNumber) {
  39. throw new Error('手机号码不能为空');
  40. }
  41. // 自动为无前缀手机号码添加+86前缀
  42. if (!phoneNumber.startsWith('+')) {
  43. phoneNumber = `+86${phoneNumber}`;
  44. }
  45. // 生成随机验证码并存入云数据库
  46. const verificationCode = `${Math.random()}`.substr(2, verificationCodeLength);
  47. const db = uniCloud.database();
  48. const verificationCodes = db.collection(verificationCodeCollection);
  49. await verificationCodes.add({
  50. phoneNumber,
  51. verificationCode,
  52. createTime: new Date().getTime(),
  53. checkCounter: 0
  54. });
  55. // 发送短信
  56. const { SendStatusSet } = await sendSMS({
  57. phoneNumbers: [phoneNumber],
  58. templateId: verificationCodeTemplateId,
  59. templateParams: [verificationCode]
  60. });
  61. if (SendStatusSet[0].Code !== 'Ok') {
  62. throw new Error(SendStatusSet[0].Message);
  63. }
  64. }
  65. module.exports = sendVerificationCode;