sms_service.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package sms
  2. import (
  3. "eta_mini_ht_api/common/component/cache"
  4. logger "eta_mini_ht_api/common/component/log"
  5. "eta_mini_ht_api/common/utils/redis"
  6. "eta_mini_ht_api/models/sms"
  7. )
  8. const (
  9. secondToMinute = 60
  10. )
  11. var (
  12. redisCache *cache.RedisCache
  13. )
  14. type CodeDTO struct {
  15. Mobile string
  16. Code string
  17. ExpireMinute int
  18. }
  19. func rd() *cache.RedisCache {
  20. if redisCache == nil {
  21. redisCache = cache.GetInstance()
  22. }
  23. return redisCache
  24. }
  25. func TryExpireCode(codeDTO CodeDTO) (err error) {
  26. verificationRecord := convertCodeDTO(codeDTO)
  27. verificationRecord.Status = sms.StatusExpired
  28. return sms.UpdateVerificationRecordByCode(codeDTO.Mobile, codeDTO.Code, verificationRecord)
  29. }
  30. func TryVerifiedCode(codeDTO CodeDTO) (err error) {
  31. verificationRecord := convertCodeDTO(codeDTO)
  32. verificationRecord.Status = sms.StatusVerified
  33. return sms.UpdateVerificationRecordByCode(codeDTO.Mobile, codeDTO.Code, verificationRecord)
  34. }
  35. func VerifiedCodeTask() (err error) {
  36. return sms.ExpiredCodesByTask()
  37. }
  38. func SendSMSCode(codeDTO CodeDTO) (smid int, err error) {
  39. verificationRecord := convertCodeDTO(codeDTO)
  40. //写库
  41. smid, err = sms.InsertVerificationRecord(verificationRecord)
  42. if err != nil {
  43. logger.Error("插入验证记录失败:", err)
  44. return
  45. }
  46. //设置redis
  47. err = rd().SetString(redis.GenerateSmsKey(codeDTO.Mobile), codeDTO.Code, codeDTO.ExpireMinute*secondToMinute)
  48. if err != nil {
  49. logger.Error("redis验证记录操作失败:", err)
  50. return
  51. }
  52. return
  53. }
  54. func convertCodeDTO(codeDTO CodeDTO) sms.VerificationRecord {
  55. return sms.VerificationRecord{
  56. Mobile: codeDTO.Mobile,
  57. Code: codeDTO.Code,
  58. ExpiredDuration: codeDTO.ExpireMinute,
  59. Status: sms.StatusPending,
  60. }
  61. }