package service import ( // "apig-sdk/go/core" "bytes" "context" "errors" "fmt" "io/ioutil" "math/rand" "net/http" "time" "youngee_b_api/consts" "youngee_b_api/core" "youngee_b_api/db" "youngee_b_api/model/system_model" "youngee_b_api/redis" "github.com/sirupsen/logrus" ) var SendCode *sendCode func SendCodeInit(config *system_model.Session) { sendCode := new(sendCode) sendCode.sessionTTL = time.Duration(config.TTL) * time.Minute SendCode = sendCode } type sendCode struct { sessionTTL time.Duration } func (s *sendCode) GetCode(ctx context.Context) string { rnd := rand.New(rand.NewSource(time.Now().UnixNano())) vcode := fmt.Sprintf("%06v", rnd.Int31n(1000000)) return vcode } func (s *sendCode) SetSession(ctx context.Context, phone string, vcode string) error { err := redis.Set(ctx, s.getRedisKey(phone), vcode, s.sessionTTL) if err != nil { return err } return nil } func (s *sendCode) getRedisKey(key string) string { return fmt.Sprintf("%s%s", consts.SessionRedisPrefix, key) } func (s *sendCode) GetEmailByPhone(ctx context.Context, phone string) (string, error) { user, err := db.GetUserByPhone(ctx, phone) fmt.Println("send_code", user, err) if err != nil { return "", err } else if user == nil { // 账号不存在 logrus.Debugf("[SendCode] sendcode fail,phone:%+v", phone) return "账号不存在", errors.New("sendcode fail") } return user.Email, nil } func (s *sendCode) SendCode(ctx context.Context, phone string, vcode string) error { signer := core.Signer{ Key: "9a9a78319abd43348b43ec59d23b44bb", Secret: "ed588c47c681417fabe13c612dcfb046", } templateId := "JM1000345" url := fmt.Sprintf("https://smssend.apistore.huaweicloud.com/sms/send?receive=" + phone + "&templateId=" + templateId + "&values=" + vcode) fmt.Printf("url: %+v\n", url) r, _ := http.NewRequest("POST", url, ioutil.NopCloser(bytes.NewBuffer([]byte("foo=bar")))) r.Header.Add("x-stage", "RELEASE") signer.Sign(r) fmt.Printf("request: %+v\n", r) resp, err := http.DefaultClient.Do(r) fmt.Printf("resp: %+v\n", resp) if err != nil { return err } else { body, _ := ioutil.ReadAll(resp.Body) fmt.Printf("resp: %+v\n", body) } return nil }