74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
package tiktok
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"git.rosy.net.cn/baseapi/platformapi"
|
|
"git.rosy.net.cn/baseapi/utils"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func (a *API) GetAppID() string {
|
|
return a.clientKey
|
|
}
|
|
|
|
func (a *API) GetSecret() string {
|
|
return a.clientSecret
|
|
}
|
|
|
|
func New(clientSecret, clientKey string, config ...*platformapi.APIConfig) *API {
|
|
curConfig := platformapi.DefAPIConfig
|
|
if len(config) > 0 {
|
|
curConfig = *config[0]
|
|
}
|
|
return &API{
|
|
clientSecret: clientSecret,
|
|
clientKey: clientKey,
|
|
client: &http.Client{Timeout: curConfig.ClientTimeout},
|
|
config: &curConfig,
|
|
}
|
|
}
|
|
|
|
func (a *API) AccessAPI(baseUrl, actionApi, method string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
|
|
// 序列化
|
|
data, err := json.Marshal(bizParams)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 全路径请求参数
|
|
fullURL := utils.GenerateGetURL(baseUrl, actionApi, nil)
|
|
|
|
// 发送请求
|
|
sendUrl := func() *http.Request {
|
|
var request *http.Request
|
|
if http.MethodPost == method {
|
|
request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(string(data)))
|
|
} else {
|
|
request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(baseUrl, actionApi, bizParams), nil)
|
|
}
|
|
switch actionApi {
|
|
case TiktokTokenUrl:
|
|
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
case TiktokRefreshTokenUrl:
|
|
request.Header.Set("Content-Type", "multipart/form-data")
|
|
}
|
|
|
|
return request
|
|
}
|
|
|
|
// 数据解析
|
|
dataMarshal := func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
|
|
if jsonResult1 == nil {
|
|
return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
|
|
}
|
|
|
|
retVal = jsonResult1
|
|
return errLevel, err
|
|
}
|
|
|
|
err = platformapi.AccessPlatformAPIWithRetry(a.client, sendUrl, a.config, dataMarshal)
|
|
return retVal, err
|
|
}
|