emas_sms_sender.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package sms
  2. import (
  3. "bytes"
  4. "eta/eta_mini_ht_api/common/component/config"
  5. "eta/eta_mini_ht_api/common/component/database"
  6. "eta/eta_mini_ht_api/common/component/database/dialector"
  7. logger "eta/eta_mini_ht_api/common/component/log"
  8. "eta/eta_mini_ht_api/common/exception"
  9. "eta/eta_mini_ht_api/common/utils/sms"
  10. stringUtils "eta/eta_mini_ht_api/common/utils/string"
  11. emasSmsService "eta/eta_mini_ht_api/domian/sms"
  12. "gorm.io/gorm"
  13. "os"
  14. "text/template"
  15. )
  16. const (
  17. emasDriver = "mysql"
  18. )
  19. type EMASSmsSender struct {
  20. Url string
  21. Template string
  22. TemplateGenerator *template.Template
  23. SmsExpireMinute int
  24. }
  25. func initDBClient(url string) *gorm.DB {
  26. open, err := gorm.Open(dialector.GetGormDial(emasDriver).GetDial(url), &gorm.Config{})
  27. if err != nil {
  28. logger.Error("初始化亿美短信数据库失败:%v", err)
  29. os.Exit(0)
  30. }
  31. logger.Info("初始化亿美短信数据库成功")
  32. return open
  33. }
  34. func (emas *EMASSmsSender) InitSender(config *config.SMSConfig) {
  35. emas.Template = config.GetEMASTemplate()
  36. emas.Url = config.GetEMASUrl()
  37. emas.SmsExpireMinute = config.GetEMASExpireMinute()
  38. emas.TemplateGenerator = template.Must(template.New("smsTemplate").Parse(emas.Template))
  39. if stringUtils.IsEmptyOrNil(emas.Url) {
  40. panic("亿美短信平台初始化失败,数据库url不能为空")
  41. }
  42. database.Register(database.EMAS, initDBClient(emas.Url))
  43. }
  44. func (emas *EMASSmsSender) GetExpireMinute() int {
  45. return emas.SmsExpireMinute
  46. }
  47. type EMASResp struct {
  48. Reason string `json:"reason"`
  49. Result Result `json:"result"`
  50. ErrorCode int
  51. }
  52. type emasTemplate struct {
  53. ExpireMinute int
  54. Code string
  55. }
  56. func (emas *EMASSmsSender) SendSms(mobile string, code string, smId int) (result string, err error) {
  57. var content bytes.Buffer
  58. if err = emas.TemplateGenerator.Execute(&content, &emasTemplate{emas.SmsExpireMinute, code}); err != nil {
  59. // 处理错误,例如记录日志或返回错误给调用者
  60. logger.Warn("[短信发送]生成短信内容失败:%v", err)
  61. return SendFail, exception.New(exception.SendingSMSFailed)
  62. }
  63. msg := emasSmsService.Msg{SMId: smId, Mobile: mobile, Content: content.String()}
  64. err = emasSmsService.SendSms(msg)
  65. if err != nil {
  66. logger.Warn("[短信发送]发送短信失败:%v", err)
  67. return SendFail, exception.New(exception.SendingSMSFailed)
  68. }
  69. return SendSuccess, nil
  70. }
  71. func NewEMASClient() sms.SMSClient {
  72. return &EMASSmsSender{}
  73. }
  74. func init() {
  75. sms.Register(sms.Emas, NewEMASClient)
  76. }