sms.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const {
  2. setMobileVerifyCode
  3. } = require('./verify-code')
  4. const {
  5. getVerifyCode
  6. } = require('../../common/utils')
  7. /**
  8. * 发送短信
  9. * @param {object} param
  10. * @param {string} param.mobile 手机号
  11. * @param {object} param.code 可选,验证码
  12. * @param {object} param.scene 短信场景
  13. * @param {object} param.templateId 可选,短信模板id
  14. * @returns
  15. */
  16. async function sendSmsCode ({
  17. mobile,
  18. code,
  19. scene,
  20. templateId
  21. } = {}) {
  22. const requiredParams = [
  23. 'name',
  24. 'smsKey',
  25. 'smsSecret',
  26. 'codeExpiresIn'
  27. ]
  28. const smsConfig = (this.config.service && this.config.service.sms) || {}
  29. for (let i = 0; i < requiredParams.length; i++) {
  30. const key = requiredParams[i]
  31. if (!smsConfig[key]) {
  32. throw new Error(`Missing config param: service.sms.${key}`)
  33. }
  34. }
  35. if (!code) {
  36. code = getVerifyCode()
  37. }
  38. let action
  39. switch (scene) {
  40. case 'login-by-sms':
  41. action = this.t('login')
  42. break
  43. default:
  44. action = this.t('verify-mobile')
  45. break
  46. }
  47. const sceneConfig = smsConfig.scene || {}
  48. if (!templateId) {
  49. templateId = sceneConfig.templateId
  50. }
  51. if (!templateId) {
  52. throw new Error('"templateId" is required')
  53. }
  54. const codeExpiresIn = sceneConfig.codeExpiresIn || smsConfig.codeExpiresIn
  55. await setMobileVerifyCode.call(this, {
  56. mobile,
  57. code,
  58. expiresIn: codeExpiresIn,
  59. scene
  60. })
  61. await uniCloud.sendSms({
  62. smsKey: smsConfig.smsKey,
  63. smsSecret: smsConfig.smsSecret,
  64. phone: mobile,
  65. templateId,
  66. data: {
  67. name: smsConfig.name,
  68. code,
  69. action,
  70. expMinute: '' + Math.round(codeExpiresIn / 60)
  71. }
  72. })
  73. return {
  74. errCode: 0
  75. }
  76. }
  77. module.exports = {
  78. sendSmsCode
  79. }