From df987cd93e7f72371d84b1acedb00413ddac28cf Mon Sep 17 00:00:00 2001 From: gazebo Date: Wed, 10 Apr 2019 13:52:17 +0800 Subject: [PATCH] - zhongwuapi --- platformapi/ebaiapi/ebaiapi.go | 9 ++ platformapi/zhongwuapi/zhongwuapi.go | 143 ++++++++++++++++++++++ platformapi/zhongwuapi/zhongwuapi_test.go | 35 ++++++ utils/typeconv.go | 7 ++ 4 files changed, 194 insertions(+) create mode 100644 platformapi/zhongwuapi/zhongwuapi.go create mode 100644 platformapi/zhongwuapi/zhongwuapi_test.go diff --git a/platformapi/ebaiapi/ebaiapi.go b/platformapi/ebaiapi/ebaiapi.go index cc7a047b..18b17e13 100644 --- a/platformapi/ebaiapi/ebaiapi.go +++ b/platformapi/ebaiapi/ebaiapi.go @@ -84,6 +84,15 @@ func (a *API) signParams(params url.Values) string { return fmt.Sprintf("%X", md5.Sum([]byte(finalStr))) } +func (a *API) getShopID(body map[string]interface{}) (shopID string) { + if body[KeyShopID] != nil { + return body[KeyShopID].(string) + } else if body[KeyBaiduShopID] != nil { + return fmt.Sprint(body[KeyBaiduShopID]) + } + return "" +} + func (a *API) AccessAPI(cmd string, body map[string]interface{}) (retVal *ResponseResult, err error) { baseapi.SugarLogger.Debugf("ebai AccessAPI cmd:%s", cmd) // a.speedLimiter.AccessAPI(allAPI) diff --git a/platformapi/zhongwuapi/zhongwuapi.go b/platformapi/zhongwuapi/zhongwuapi.go new file mode 100644 index 00000000..6d071b85 --- /dev/null +++ b/platformapi/zhongwuapi/zhongwuapi.go @@ -0,0 +1,143 @@ +package zhongwuapi + +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 = "http://api.zhongwuyun.com" + + signKey = "sign" + timestampKey = "timestamp" +) + +const ( + ResponseCodeSuccess = 0 // 操作成功 +) + +const ( + PrinterStatusOffline = 0 + PrinterStatusOnline = 1 + PrinterStatusLackPaper = 2 +) + +var ( + exceedLimitCodes = map[int]int{} + canRetryCodes = map[int]int{} +) + +type API struct { + appID int + appSecret string + client *http.Client + config *platformapi.APIConfig +} + +func New(appID int, appSecret string, config ...*platformapi.APIConfig) *API { + curConfig := platformapi.DefAPIConfig + if len(config) > 0 { + curConfig = *config[0] + } + return &API{ + appID: appID, + appSecret: appSecret, + client: &http.Client{Timeout: curConfig.ClientTimeout}, + config: &curConfig, + } +} + +func (a *API) signParams(apiParams map[string]interface{}) string { + keys := utils.MapKeys(apiParams) + sort.Sort(sort.StringSlice(keys)) + valueList := make([]string, len(keys)+1) + for index, key := range keys { + valueList[index] = fmt.Sprintf("%s%v", key, apiParams[key]) + } + valueList[len(keys)] = a.appSecret + return fmt.Sprintf("%x", md5.Sum([]byte(strings.Join(valueList, "")))) +} + +func (a *API) AccessAPI(apiName string, apiParams map[string]interface{}, isGet bool) (retVal map[string]interface{}, err error) { + params := utils.MergeMaps(map[string]interface{}{ + "appid": a.appID, + }, apiParams) + + err = platformapi.AccessPlatformAPIWithRetry(a.client, + func() (request *http.Request) { + params[timestampKey] = time.Now().Unix() + params[signKey] = a.signParams(params) + if isGet { + fullURL := utils.GenerateGetURL(prodURL, apiName, params) + // baseapi.SugarLogger.Debug(fullURL) + request, _ = http.NewRequest(http.MethodGet, fullURL, nil) + } else { + request, _ = http.NewRequest(http.MethodPost, utils.GenerateGetURL(prodURL, apiName, nil), strings.NewReader(utils.Map2URLValues(params).Encode())) + request.Header.Set("charset", "UTF-8") + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + // request.Close = true //todo 为了性能考虑还是不要关闭 + return request + }, + a.config, + func(jsonResult1 map[string]interface{}) (errLevel string, err error) { + code := int(utils.MustInterface2Int64(jsonResult1["errNum"])) + if code == ResponseCodeSuccess { + retVal, _ = jsonResult1["retData"].(map[string]interface{}) + return platformapi.ErrLevelSuccess, nil + } + newErr := utils.NewErrorIntCode(jsonResult1["errMsg"].(string), code) + if _, ok := exceedLimitCodes[code]; ok { + return platformapi.ErrLevelExceedLimit, newErr + } else if _, ok := canRetryCodes[code]; ok { + return platformapi.ErrLevelRecoverableErr, newErr + } else { + baseapi.SugarLogger.Debugf("zhongwu AccessAPI failed, jsonResult1:%s", utils.Format4Output(jsonResult1, true)) + return platformapi.ErrLevelCodeIsNotOK, newErr + } + }) + return retVal, err +} + +func (a *API) PrintMsg(deviceID, deviceSecret, printData string) (dataID string, status int, err error) { + retData, err := a.AccessAPI("", map[string]interface{}{ + "deviceid": deviceID, + "devicesecret": deviceSecret, + "printdata": printData, + }, false) + if err == nil { + return utils.Interface2String(retData["id"]), int(utils.Str2Int64(utils.Interface2String(retData["status"]))), nil + } + return "", 0, err +} + +func (a *API) GetPrinterStatus(deviceID, deviceSecret string) (status int, err error) { + retData, err := a.AccessAPI("status", map[string]interface{}{ + "deviceid": deviceID, + "devicesecret": deviceSecret, + }, true) + if err == nil { + return int(utils.Str2Int64(utils.Interface2String(retData["status"]))), nil + } + return 0, err +} + +func (a *API) GetPrintStatus(deviceID, deviceSecret, dataID string) (isPrinted bool, err error) { + retData, err := a.AccessAPI("printstatus", map[string]interface{}{ + "deviceid": deviceID, + "devicesecret": deviceSecret, + "dataid": dataID, + }, true) + if err == nil { + return int(utils.Str2Int64(utils.Interface2String(retData["status"]))) == 1, nil + } + return false, err +} diff --git a/platformapi/zhongwuapi/zhongwuapi_test.go b/platformapi/zhongwuapi/zhongwuapi_test.go new file mode 100644 index 00000000..87d2fee3 --- /dev/null +++ b/platformapi/zhongwuapi/zhongwuapi_test.go @@ -0,0 +1,35 @@ +package zhongwuapi + +import ( + "testing" + + "git.rosy.net.cn/baseapi" + + "go.uber.org/zap" +) + +var ( + api *API + sugarLogger *zap.SugaredLogger +) + +func init() { + logger, _ := zap.NewDevelopment() + sugarLogger = logger.Sugar() + baseapi.Init(sugarLogger) + + api = New(8000192, "29435497822f52f3cf659c65da548a79") +} + +func handleError(t *testing.T, err error) { + if err != nil { + sugarLogger.Debug(err) + t.Fatal(err.Error()) + } +} + +func TestPrintMsg(t *testing.T) { + id, status, err := api.PrintMsg("deviceid", "devicesecret", "printdata") + handleError(t, err) + baseapi.SugarLogger.Debug(id, status) +} diff --git a/utils/typeconv.go b/utils/typeconv.go index 1016616b..2e064fb7 100644 --- a/utils/typeconv.go +++ b/utils/typeconv.go @@ -393,6 +393,13 @@ func MapKV2List(mapData map[string]interface{}) []map[string]interface{} { return retVal } +func MapKeys(mapData map[string]interface{}) (keys []string) { + for k := range mapData { + keys = append(keys, k) + } + return keys +} + func Format4Output(obj interface{}, isSingleLine bool) (retVal string) { retVal, ok := obj.(string) if !ok {