sms.js 1.8 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
const {
  setMobileVerifyCode
} = require('./verify-code')
const {
  getVerifyCode
} = require('../../common/utils')

/**
 * 发送短信
 * @param {object} param
 * @param {string} param.mobile       手机号
 * @param {object} param.code         可选,验证码
 * @param {object} param.scene        短信场景
 * @param {object} param.templateId   可选,短信模板id
 * @returns
 */
async function sendSmsCode ({
  mobile,
  code,
  scene,
  templateId
} = {}) {
  const requiredParams = [
    'name',
    'smsKey',
    'smsSecret',
    'codeExpiresIn'
  ]
  const smsConfig = (this.config.service && this.config.service.sms) || {}
  for (let i = 0; i < requiredParams.length; i++) {
    const key = requiredParams[i]
    if (!smsConfig[key]) {
      throw new Error(`Missing config param: service.sms.${key}`)
    }
  }
  if (!code) {
    code = getVerifyCode()
  }
  let action
  switch (scene) {
    case 'login-by-sms':
      action = this.t('login')
      break
    default:
      action = this.t('verify-mobile')
      break
  }
  const sceneConfig = (smsConfig.scene || {})[scene] || {}
  if (!templateId) {
    templateId = sceneConfig.templateId
  }
  if (!templateId) {
    throw new Error('"templateId" is required')
  }
  const codeExpiresIn = sceneConfig.codeExpiresIn || smsConfig.codeExpiresIn
  await setMobileVerifyCode.call(this, {
    mobile,
    code,
    expiresIn: codeExpiresIn,
    scene
  })
  await uniCloud.sendSms({
    smsKey: smsConfig.smsKey,
    smsSecret: smsConfig.smsSecret,
    phone: mobile,
    templateId,
    data: {
      name: smsConfig.name,
      code,
      action,
      expMinute: '' + Math.round(codeExpiresIn / 60)
    }
  })
  return {
    errCode: 0
  }
}

module.exports = {
  sendSmsCode
}