sms_service.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package sms
  2. import (
  3. "eta/eta_mini_ht_api/common/component/cache"
  4. logger "eta/eta_mini_ht_api/common/component/log"
  5. "eta/eta_mini_ht_api/common/utils/redis"
  6. "eta/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. return
  44. }
  45. //设置redis
  46. err = rd().SetString(redis.GenerateSmsKey(codeDTO.Mobile), codeDTO.Code, codeDTO.ExpireMinute*secondToMinute)
  47. if err != nil {
  48. logger.Error("redis验证记录操作失败:", err)
  49. return
  50. }
  51. return
  52. }
  53. func convertCodeDTO(codeDTO CodeDTO) sms.VerificationRecord {
  54. return sms.VerificationRecord{
  55. Mobile: codeDTO.Mobile,
  56. Code: codeDTO.Code,
  57. ExpiredDuration: codeDTO.ExpireMinute,
  58. Status: sms.StatusPending,
  59. }
  60. }