send_code.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package service
  2. import (
  3. // "apig-sdk/go/core"
  4. "bytes"
  5. "context"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "math/rand"
  10. "net/http"
  11. "time"
  12. "youngee_b_api/consts"
  13. "youngee_b_api/core"
  14. "youngee_b_api/db"
  15. "youngee_b_api/model/system_model"
  16. "youngee_b_api/redis"
  17. "github.com/sirupsen/logrus"
  18. )
  19. var SendCode *sendCode
  20. func SendCodeInit(config *system_model.Session) {
  21. sendCode := new(sendCode)
  22. sendCode.sessionTTL = time.Duration(config.TTL) * time.Minute
  23. SendCode = sendCode
  24. }
  25. type sendCode struct {
  26. sessionTTL time.Duration
  27. }
  28. func (s *sendCode) GetCode(ctx context.Context) string {
  29. rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
  30. vcode := fmt.Sprintf("%06v", rnd.Int31n(1000000))
  31. return vcode
  32. }
  33. func (s *sendCode) SetSession(ctx context.Context, phone string, vcode string) error {
  34. err := redis.Set(ctx, s.getRedisKey(phone), vcode, s.sessionTTL)
  35. if err != nil {
  36. return err
  37. }
  38. return nil
  39. }
  40. func (s *sendCode) getRedisKey(key string) string {
  41. return fmt.Sprintf("%s%s", consts.SessionRedisPrefix, key)
  42. }
  43. func (s *sendCode) GetEmailByPhone(ctx context.Context, phone string) (string, error) {
  44. user, err := db.GetUserByPhone(ctx, phone)
  45. fmt.Println("send_code", user, err)
  46. if err != nil {
  47. return "", err
  48. } else if user == nil {
  49. // 账号不存在
  50. logrus.Debugf("[SendCode] sendcode fail,phone:%+v", phone)
  51. return "账号不存在", errors.New("sendcode fail")
  52. }
  53. return user.Email, nil
  54. }
  55. func (s *sendCode) SendCode(ctx context.Context, phone string, vcode string) error {
  56. signer := core.Signer{
  57. Key: "9a9a78319abd43348b43ec59d23b44bb",
  58. Secret: "ed588c47c681417fabe13c612dcfb046",
  59. }
  60. templateId := "JM1000345"
  61. url := fmt.Sprintf("https://smssend.apistore.huaweicloud.com/sms/send?receive=" + phone + "&templateId=" + templateId + "&values=" + vcode)
  62. fmt.Printf("url: %+v\n", url)
  63. r, _ := http.NewRequest("POST", url,
  64. ioutil.NopCloser(bytes.NewBuffer([]byte("foo=bar"))))
  65. r.Header.Add("x-stage", "RELEASE")
  66. signer.Sign(r)
  67. fmt.Printf("request: %+v\n", r)
  68. resp, err := http.DefaultClient.Do(r)
  69. fmt.Printf("resp: %+v\n", resp)
  70. if err != nil {
  71. return err
  72. } else {
  73. body, _ := ioutil.ReadAll(resp.Body)
  74. fmt.Printf("resp: %+v\n", body)
  75. }
  76. return nil
  77. }