package tik_tok import ( "bytes" zhios_third_party_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/utils" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "github.com/syyongx/php2go" "sort" "strings" "time" ) func Send(appkey, appSecret, method string, params map[string]interface{}, acctoken string) (string, error) { methodPath := strings.ReplaceAll(method, ".", "/") url := "https://openapi-fxg.jinritemai.com/" + methodPath paramJson := GetSortJson(params) paramJson = strings.ReplaceAll(paramJson, "\n", "") param := map[string]string{ "app_key": appkey, "method": method, "param_json": paramJson, "timestamp": zhios_third_party_utils.Int64ToStr(time.Now().Unix()), "v": "2", } sign := GetSign(appSecret, param) if acctoken != "" { param["access_token"] = acctoken } param["sign"] = sign param["sign_method"] = "hmac-sha256" for k, v := range param { if strings.Contains(url, "?") { url += "&" + k + "=" + php2go.URLEncode(v) } else { url += "?" + k + "=" + php2go.URLEncode(v) } } data, err := zhios_third_party_utils.CurlPost(url, paramJson, nil) return string(data), err } func GetSign(appSecret string, param map[string]string) string { str := "" keys := KsortToStr(param) for _, k := range keys { str += k + param[k] } signStr := appSecret + str + appSecret h := hmac.New(sha256.New, []byte(appSecret)) _, _ = h.Write([]byte(signStr)) return hex.EncodeToString(h.Sum(nil)) } func Ksort(params map[string]interface{}) []string { keys := make([]string, len(params)) i := 0 for k, _ := range params { keys[i] = k i++ } sort.Strings(keys) return keys } func KsortToStr(params map[string]string) []string { keys := make([]string, len(params)) i := 0 for k, _ := range params { keys[i] = k i++ } sort.Strings(keys) return keys } //func GetSortJson(params map[string]interface{}) string { // // 排序 // keys := Ksort(params) // for _, k := range keys { // fmt.Println(k) // } // // byteBuf := bytes.NewBuffer([]byte{}) // encoder := json.NewEncoder(byteBuf) // // 特殊字符不转义 // encoder.SetEscapeHTML(false) // err := encoder.Encode(params) // if err != nil { // panic(err) // } // data := byteBuf.String() // return data //} // Marshal 序列化参数 func GetSortJson(o interface{}) string { // 序列化一次 raw, _ := json.Marshal(o) // 反序列化为map m := make(map[string]interface{}) reader := bytes.NewReader(raw) decode := json.NewDecoder(reader) decode.UseNumber() _ = decode.Decode(&m) // 重新做一次序列化,并禁用Html Escape buffer := bytes.NewBufferString("") encoder := json.NewEncoder(buffer) encoder.SetEscapeHTML(false) _ = encoder.Encode(m) marshal := strings.TrimSpace(buffer.String()) // Trim掉末尾的换行符 return marshal }