67 lines
2.1 KiB
Go
67 lines
2.1 KiB
Go
package t3_union
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"math/rand"
|
||
"sort"
|
||
"strings"
|
||
"time"
|
||
|
||
"repository.lenntc.com/lenntc/third-platform-sdk/util"
|
||
)
|
||
|
||
type Sign struct {
|
||
AppKey string // 应用key
|
||
AppSecret string // 应用秘钥
|
||
}
|
||
|
||
func newSign(appKey, appSecret string) *Sign {
|
||
return &Sign{
|
||
AppKey: appKey,
|
||
AppSecret: appSecret,
|
||
}
|
||
}
|
||
|
||
func (s *Sign) BuildHeader(methodType string, uri string, data map[string]any) map[string]string {
|
||
// 随机数
|
||
tn := time.Now()
|
||
src := rand.NewSource(tn.Unix())
|
||
randNum := rand.New(src).Int31n(10000)
|
||
nonce := util.Md5String(fmt.Sprintf("%d_nonce_%d", tn.UnixMicro(), randNum))
|
||
headers := map[string]string{
|
||
XT3Nonce: nonce, // 请求标识,10分钟内保证唯一性
|
||
XT3Timestamp: fmt.Sprintf("%d", time.Now().UnixMilli()), // 请求发起时间戳(毫秒),有效时1分钟
|
||
XT3Version: "V1", // 版本(固定值传"V1")
|
||
XT3Key: s.AppKey, // 使用前联系分配账号(APP Key)
|
||
XT3SignatureMethod: "MD5", // 固定值传 "MD5"
|
||
}
|
||
|
||
headers[XT3Signature] = s.GetSign(methodType, uri, headers, data) // 在获得签名后赋值
|
||
headers[XT3SignatureHeaders] = "x-t3-nonce,x-t3-timestamp,x-t3-version,x-t3-key,x-t3-signature-method" // 固定传值
|
||
|
||
return headers
|
||
}
|
||
|
||
func (s *Sign) GetSign(methodType string, uri string, headers map[string]string, data map[string]any) string {
|
||
// key排序
|
||
arr := sort.StringSlice{}
|
||
for k := range headers {
|
||
if k != XT3Signature && k != XT3SignatureHeaders {
|
||
arr = append(arr, k)
|
||
}
|
||
}
|
||
arr.Sort()
|
||
// 参数拼接
|
||
var build strings.Builder
|
||
build.WriteString(fmt.Sprintf("%s%s", methodType, uri))
|
||
for _, k := range arr {
|
||
build.WriteString(fmt.Sprintf("%s:%v", k, headers[k]))
|
||
}
|
||
// 请求参数body转json string后用MD5进行加密
|
||
dataByte, _ := json.Marshal(data)
|
||
build.WriteString(util.Md5String(string(dataByte)))
|
||
build.WriteString(s.AppSecret)
|
||
return util.Md5String(build.String())
|
||
}
|