create_code.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package utils
  2. import (
  3. "Ic_ouath/app/e"
  4. "Ic_ouath/global"
  5. "context"
  6. "fmt"
  7. "go.uber.org/zap"
  8. "math/rand"
  9. "time"
  10. )
  11. func CreatCode() string {
  12. const chars = "0123456789"
  13. result := make([]byte, 6)
  14. rand.Seed(time.Now().UnixNano())
  15. for i := range result {
  16. index := rand.Intn(len(chars))
  17. result[i] = chars[index]
  18. }
  19. return string(result)
  20. }
  21. func SendModel(phone string) e.Rescode {
  22. ctx := context.Background()
  23. ss := NewSMS(global.SubMailSetting.Appid, global.SubMailSetting.Signature)
  24. result, err := global.Rdb.Exists(ctx, phone).Result()
  25. if result == 1 {
  26. fmt.Println("验证码已经发送", zap.Error(err))
  27. return e.HasSend
  28. }
  29. if err != nil {
  30. fmt.Println("redis查询出现异常", zap.Error(err))
  31. return e.TheSystemIsAbnormal
  32. }
  33. code := CreatCode()
  34. content := fmt.Sprintf("【冷链智控系统】您的短信验证码:%s,请在5分钟内输入", code)
  35. res, err := ss.Send(phone, content)
  36. if err != nil || res.Status != SUCCESS {
  37. fmt.Println("发送短信验证码出现异常", zap.Any("res", res), zap.Error(err))
  38. return e.AnExceptionOccursWhenSendingAnSMSVerificationCode
  39. } else {
  40. //验证码装入redis并且设置过期时间
  41. err = global.Rdb.Set(ctx, phone, code, 300*time.Second).Err()
  42. return e.SUCCESS
  43. }
  44. }