package supply import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "github.com/google/uuid" "github.com/mitchellh/mapstructure" "time" ) var Api = &api{} type api struct { Config Config Sku sku Order order Mq mq } type Config struct { Url string ChannelId uint AppKey string AppSecret string } // InitSupply @Title 初始化配置 func InitSupply(config Config) { Api.Config = config } type public struct { ChannelId uint `json:"channelId"` TraceId string `json:"traceId"` Timestamp int64 `json:"timestamp"` } type execBody struct { Body interface{} `json:"body"` Public public `json:"public"` } type resp struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{} `json:"data"` } // @Title 调用接口 func exec(action string, data interface{}, result interface{}) error { body := execBody{ Body: data, Public: public{ ChannelId: Api.Config.ChannelId, TraceId: uuid.New().String(), Timestamp: time.Now().Unix(), }, } requestBody, _ := json.Marshal(&body) sign := HmacSha256(Api.Config.AppSecret, fmt.Sprintf("%s%d", requestBody, len(requestBody))) bytes, err := request(post, Api.Config.Url+action, string(requestBody), map[string]string{ "AppKey": Api.Config.AppKey, "Sign": sign, }) if err != nil { return err } res := resp{} json.Unmarshal(bytes, &res) if res.Code == 200 { err = mapstructure.WeakDecode(res.Data, &result) return nil } else { return errors.New(res.Msg) } } // HmacSha256 @Title hmac-sha256签名 func HmacSha256(key, content string) string { h := hmac.New(sha256.New, []byte(key)) h.Write([]byte(content)) return hex.EncodeToString(h.Sum(nil)) }