package oa import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "io" "net/http" "strconv" "strings" "time" "github.com/go-kratos/kratos/v3/errors" "kra/internal/biz/business" "kra/internal/config" ) type activationGateway struct { config *config.Store client *http.Client } func NewActivationGateway(store *config.Store) business.ActivationGateway { return &activationGateway{config: store, client: &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} } func (g *activationGateway) Apply(ctx context.Context, a business.ActivationApplication) error { cfg := g.config.Snapshot() if cfg == nil || cfg.BusinessOA == nil || cfg.BusinessOA.URL == "" || cfg.BusinessOA.Key == "" { return business.ErrActivationSource } body, err := json.Marshal(struct { UserID string `json:"userId"` PoolID string `json:"poolId"` BusierID string `json:"busierId"` SourceDB string `json:"sourceDb"` }{strconv.FormatUint(uint64(a.UserID), 10), strconv.FormatUint(a.PoolID, 10), strconv.FormatUint(a.BusierID, 10), a.SourceDB}) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(cfg.BusinessOA.URL, "/")+"/internal/business/activation/apply", bytes.NewReader(body)) if err != nil { return business.ErrActivationSource } stamp := strconv.FormatInt(time.Now().Unix(), 10) mac := hmac.New(sha256.New, []byte(cfg.BusinessOA.Key)) mac.Write([]byte(req.Method + "\n" + req.URL.EscapedPath() + "\n" + stamp + "\n")) mac.Write(body) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Business-Timestamp", stamp) req.Header.Set("X-Business-Signature", hex.EncodeToString(mac.Sum(nil))) res, err := g.client.Do(req) if err != nil { return business.ErrActivationSource } defer res.Body.Close() if res.StatusCode != http.StatusOK { return business.ErrActivationSource } var result struct { Code *int `json:"code"` Message string `json:"msg"` } if err := json.NewDecoder(io.LimitReader(res.Body, 65536)).Decode(&result); err != nil || result.Code == nil { return business.ErrActivationSource } if *result.Code != 0 { return errors.BadRequest("SW_ACTIVATION_APPLY", result.Message) } return nil }