Files
baseapi/platformapi/jdshopapi/jdshopapi.go
2020-05-18 18:14:56 +08:00

169 lines
5.4 KiB
Go

package jdshopapi
import (
"crypto/md5"
"fmt"
"net/http"
"sort"
"strings"
"time"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/platformapi"
"git.rosy.net.cn/baseapi/utils"
)
const (
prodURL = "https://api.jd.com/routerjson"
sigKey = "sign"
JdsImgURL = "//img10.360buyimg.com/imgzone/"
JdsImgDescURL = `<img src=" //img10.360buyimg.com/imgzone/jfs/t1/111969/32/6692/171733/5ebbb9daE5bedb5b2/38350dca19e2b9d2.jpg" style="width: auto; height: auto; max-width: 100%;">`
JdsStoreImg = "http://image.jxc4.com/image/b90ae8585e8cf2f3871f6e8318bde1dc.tem.png"
JdsStoreCategoryName = "pop-mendian-Selfdelivery"
JdsStoreStatusRest = 6
JdsStoreStatusOnline = 1
JdsStoreStatusDisable = 2
CreateCatType = "3"
UpdateCatType = "1"
VenderID = 10374877
TransportID = 2158480
JxBrandId = 559853
JdShopMaxStock = 9999
JdsPromiseID = 13725637
)
var (
SensitiveWordMap = []string{
"[畅销]",
"【畅销】",
}
)
type API struct {
platformapi.APICookie
accessToken string
appKey string
appSecret string
client *http.Client
config *platformapi.APIConfig
}
type UniteResp struct {
Num int `json:"num"`
IsSuccess bool `json:"is_success"`
ErrorCode string `json:"error_code"`
ErrorMsgCn string `json:"error_msg_cn"`
ErrorMsg string `json:"error_msg"`
}
func New(accessToken, appKey, appSecret string, config ...*platformapi.APIConfig) *API {
curConfig := platformapi.DefAPIConfig
if len(config) > 0 {
curConfig = *config[0]
}
return &API{
accessToken: accessToken,
appKey: appKey,
appSecret: appSecret,
client: &http.Client{Timeout: curConfig.ClientTimeout},
config: &curConfig,
}
}
func (a *API) signParam(params map[string]interface{}) (sig string) {
var valueList []string
for k, v := range params {
if k != sigKey {
if str := fmt.Sprint(v); str != "" {
valueList = append(valueList, fmt.Sprintf("%s%s", k, str))
}
}
}
sort.Sort(sort.StringSlice(valueList))
valueList = append(valueList, fmt.Sprintf("%s", a.appSecret))
var valueList2 = make([]string, len(valueList)+1)
at := copy(valueList2, valueList[:0])
at += copy(valueList2[at:], []string{a.appSecret})
copy(valueList2[at:], valueList[0:])
sig = strings.Join(valueList2, "")
binSig := md5.Sum([]byte(sig))
sig = fmt.Sprintf("%X", binSig)
return sig
}
func (a *API) AccessAPI(action string, url string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
params := make(map[string]interface{})
params["access_token"] = a.accessToken
params["app_key"] = a.appKey
params["timestamp"] = utils.Time2Str(time.Now())
params["method"] = action
params["v"] = "2.0"
params = utils.MergeMaps(params, bizParams)
signStr := a.signParam(params)
params["sign"] = signStr
fullURL := utils.GenerateGetURL(url, "", nil)
err = platformapi.AccessPlatformAPIWithRetry(a.client,
func() *http.Request {
request, _ := http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(params).Encode()))
request.Header.Set("charset", "UTF-8")
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return request
},
a.config,
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")
}
if err == nil {
if jsonResult1["error_response"] != nil {
errLevel = platformapi.ErrLevelGeneralFail
err = utils.NewErrorCode(jsonResult1["error_response"].(map[string]interface{})["zh_desc"].(string), jsonResult1["error_response"].(map[string]interface{})["code"].(string))
baseapi.SugarLogger.Debugf("jdeclp AccessAPI failed, jsonResult1:%s", utils.Format4Output(jsonResult1, true))
}
retVal = jsonResult1
}
return errLevel, err
})
return retVal, err
}
func (a *API) AccessAPI2(action string, pURL string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
params := make(map[string]interface{})
params["access_token"] = a.accessToken
params["app_key"] = a.appKey
params["timestamp"] = utils.Time2Str(time.Now())
params["method"] = action
params["v"] = "2.0"
params = utils.MergeMaps(params, bizParams)
signStr := a.signParam(params)
params["sign"] = signStr
fullURL := utils.GenerateGetURL(pURL, "", nil)
err = platformapi.AccessPlatformAPIWithRetry(a.client,
func() *http.Request {
request, _ := http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(params).Encode()))
request.Header.Set("charset", "UTF-8")
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return request
},
a.config,
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")
}
if err == nil {
if jsonResult1["error_response"] != nil {
errLevel = platformapi.ErrLevelGeneralFail
err = utils.NewErrorCode(jsonResult1["error_response"].(map[string]interface{})["en_desc"].(string), jsonResult1["error_response"].(map[string]interface{})["code"].(string))
baseapi.SugarLogger.Debugf("jdeclp AccessAPI failed, jsonResult1:%s", utils.Format4Output(jsonResult1, true))
}
retVal = jsonResult1
}
return errLevel, err
})
return retVal, err
}