dwd.go 2.5 KB
package dwd

import (
	"context"
	"github.com/gogf/gf/container/garray"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"time"
)

type Config struct {
	AppKey    string
	AppSecret string
	API       string
	DB        int
}

var server *Config

const PkgName = "dwd"
const CacheKey = "dwd:token"

func New(req *Config) {
	server = req
	if server.DB == 0 {
		server.DB = 10
	}
	return
}

func sign(req interface{}) *string {
	var res string
	param := gconv.MapStrStr(req)

	var keys = garray.NewStrArray()
	for key := range param {
		keys.Append(key)
	}

	for _, key := range keys.Sort().Slice() {
		res += key
		res += param[key]
	}

	res = gmd5.MustEncryptString(server.AppKey + res + server.AppSecret)

	return &res
}

type CommonReq struct {
	Action      string `json:"action"`
	Appid       string `json:"appid"`
	Timestamp   int64  `json:"timestamp"`
	AccessToken string `json:"access_token"`
	Biz         string `json:"biz"`
}

type CommonRes struct {
	Errno     int    `json:"errno"`
	Errmsg    string `json:"errmsg"`
	Data      string `json:"data"`
	RequestId string `json:"request_id"`
	Timestamp int    `json:"timestamp"`
	Signature string `json:"signature"`
}

func post(ctx context.Context, method string, req interface{}) (res *CommonRes, err error) {

	Start := gtime.TimestampMilli()
	AccessToken, err := Token.Access(ctx)
	if err != nil {
		return
	}
	var params = CommonReq{
		Action:      method,
		Appid:       server.AppKey,
		Timestamp:   gtime.Timestamp(),
		AccessToken: AccessToken,
		Biz:         gjson.New(req).MustToJsonString(),
	}

	var request = gjson.New(params)
	_ = request.Set("signature", sign(params))
	Request := g.Client().ContentType("application/x-www-form-urlencoded; charset=utf-8")
	Request.Timeout(3 * time.Second)
	var str string
	resp, err := Request.Post(server.API, request.Map())
	defer func() {
		_ = resp.Close()
		ctx = context.WithValue(ctx, "Method", "POST")
		ctx = context.WithValue(ctx, "URI", method)
		if err != nil {
			g.Log().Ctx(ctx).Cat(PkgName).Cat("error").Infof("参数【%v】错误【%v】响应时间【%v】", request.MustToJsonString(), err.Error(), gtime.TimestampMilli()-Start)
		} else {
			g.Log().Ctx(ctx).Cat(PkgName).Infof("参数【%v】响应【%v】响应时间【%v】", request.MustToJsonString(), str, gtime.TimestampMilli()-Start)
		}
	}()
	str = resp.ReadAllString()
	_ = gjson.New(str).Scan(&res)
	return
}