• 张立波's avatar
    log · 46585cfa
    张立波 提交于
    46585cfa
schl.go 2.8 KB
package schl

import (
	"context"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"github.com/gogf/gf/container/garray"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gregex"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
	"net/url"
	"sort"
	"strings"
	"time"
)

const Host = "https://schl-api.szbaoly.com"

type Config struct {
	ApiUrl    string
	AppKey    string
	AppSecret string
	ImgUrl    string
}

type CommonRes struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

type PubilcParams struct {
	AppID     string `json:"appid"`
	Nonce     string `json:"nonce"`
	Timestamp string `json:"timestamp"`
	Signature string `json:"signature"`
}

const pkgName = "schl"

func New(config *Config) *Config {
	return config
}

func (s *Config) Post(ctx context.Context, URL string, bodyMap g.Map) (result string, err error) {

	Start := gtime.TimestampMilli()
	pubilcParams := new(PubilcParams)
	pubilcParams.AppID = s.AppKey
	pubilcParams.Timestamp = gtime.TimestampStr()
	pubilcParams.Nonce = grand.S(16, false)
	s.Sign(pubilcParams)

	defer func() {
		ctx = context.WithValue(ctx, "URI", URL)
		if err != nil {
			g.Log().Ctx(ctx).Cat(pkgName).Cat("error").
				Infof("参数【%v】错误【%v】响应时间:【%v ms】", gjson.New(bodyMap).MustToJsonString(), err.Error(), gtime.TimestampMilli()-Start)
		} else {
			g.Log().Ctx(ctx).Cat(pkgName).
				Infof("参数【%v】响应【%v】响应时间:【%v ms】", gjson.New(bodyMap).MustToJsonString(), result, gtime.TimestampMilli()-Start)
		}
	}()
	var value = url.Values{}
	value.Add("appid", pubilcParams.AppID)
	value.Add("nonce", pubilcParams.Nonce)
	value.Add("timestamp", pubilcParams.Timestamp)
	value.Add("signature", pubilcParams.Signature)

	response, err := g.Client().
		Timeout(time.Second*3).
		ContentJson().
		Post(Host+URL+"?"+value.Encode(), bodyMap)
	defer func() {
		_ = response.Close()
	}()
	if nil != err {
		return
	}
	result, _ = gregex.ReplaceString(`\s`, "", response.ReadAllString())
	return
}

func (s *Config) Sign(pubilcParams *PubilcParams) {
	allMaps := make(map[string]string)
	var arr = garray.New().Append("appid", "timestamp", "nonce")
	for k, v := range gconv.MapStrStr(pubilcParams) {
		if arr.Contains(k) {
			allMaps[k] = v
		}
	}

	keys := make([]string, 0)
	for k := range allMaps {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	paramsString := ""
	for k, v := range keys {
		if k > 0 {
			paramsString += "&"
		}
		paramsString += v + "=" + allMaps[v]
	}

	paramsString += "&key=" + s.AppSecret

	hmacSha256String := hmacSha256(paramsString, s.AppSecret)

	pubilcParams.Signature = strings.ToUpper(hmacSha256String)
	return
}

func hmacSha256(data string, secret string) string {
	h := hmac.New(sha256.New, []byte(secret))
	h.Write([]byte(data))
	return hex.EncodeToString(h.Sum(nil))
}