You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.7 KiB

package supply
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/mitchellh/mapstructure"
"log"
"strconv"
"time"
)
var Api = &api{}
type api struct {
Config Config
Sku sku
Order order
Mq mq
}
type Config struct {
Url string
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 {
requestBody, _ := json.Marshal(&data)
now := time.Now().Unix()
sign := HmacSha256(Api.Config.AppSecret, fmt.Sprintf("%d%s", now, requestBody))
bytes, err := request(post, Api.Config.Url+action, string(requestBody), map[string]string{
"AppKey": Api.Config.AppKey,
"RequestId": uuid.New().String(),
"TimeStamp": strconv.Itoa(int(now)),
"Sign": sign,
})
if err != nil {
return err
}
log.Println(string(bytes))
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))
}