- AccessPlatformAPIWithRetry的回调handleResponse添加response参数

- 饿百从网页取门店健康信息
This commit is contained in:
gazebo
2019-06-11 16:39:52 +08:00
parent cae38a9a4c
commit eb009df26d
18 changed files with 261 additions and 32 deletions

View File

@@ -137,7 +137,7 @@ func (a *API) AccessAPI(apiStr string, params map[string]interface{}) (retVal Re
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
status := jsonResult1["status"].(string)
if status == StatusCodeSuccess {
retVal = jsonResult1

View File

@@ -118,7 +118,7 @@ func (a *API) AccessAPI(action string, params interface{}) (retVal *ResponseResu
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (result string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (result string, err error) {
code := int(utils.MustInterface2Int64(jsonResult1["code"]))
retVal = &ResponseResult{
Code: code,

View File

@@ -147,7 +147,7 @@ func (a *API) AccessAPI(action string, params map[string]interface{}, bodyMap ma
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (result string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (result string, err error) {
errCode := int(utils.MustInterface2Int64(jsonResult1["errcode"]))
if errCode == ResponseCodeSuccess {
retVal = jsonResult1

View File

@@ -111,7 +111,7 @@ func (a *API) AccessAPI(cmd string, body map[string]interface{}) (retVal *Respon
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (result string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (result string, err error) {
Body := jsonResult1["body"].(map[string]interface{})
retVal = &ResponseResult{
ErrNo: int(utils.MustInterface2Int64(Body["errno"])),

View File

@@ -3,6 +3,7 @@ package ebaiapi
import (
"fmt"
"net/http"
"strings"
"time"
"git.rosy.net.cn/baseapi"
@@ -11,7 +12,8 @@ import (
)
const (
storeURL = "https://be.ele.me"
storeURL = "https://be.ele.me"
swithShopURL = "crm/manager/switchshop"
)
const (
@@ -31,6 +33,131 @@ const (
CommentContentNoContent = 0
)
type PageShopUserInfo struct {
CategoryID string `json:"category_id"`
CityID string `json:"city_id"`
CityName string `json:"city_name"`
DeliveryParty string `json:"delivery_party"`
EleID string `json:"ele_id"`
EleSoaToken string `json:"ele_soa_token"`
IsAPI int `json:"is_api"`
IsStore interface{} `json:"is_store"`
MerchantID string `json:"merchant_id"`
MerchantName string `json:"merchant_name"`
Role struct {
Ename string `json:"ename"`
Name string `json:"name"`
ShopRoleID int64 `json:"shop_role_id"`
} `json:"role"`
SalesID string `json:"sales_id"`
SalesName string `json:"sales_name"`
ServicePackage struct {
BaiduSign int `json:"baiduSign"`
EleSign int `json:"eleSign"`
} `json:"service_package"`
ShopInfo struct {
AreaID string `json:"area_id"`
BaiduBusinessState string `json:"baidu_business_state"`
BaiduOnlineStatus string `json:"baidu_online_status"`
BaiduTakeoutLogo string `json:"baidu_takeout_logo"`
CategoryID string `json:"category_id"`
CategoryIds string `json:"category_ids"`
CategoryName string `json:"category_name"`
County string `json:"county"`
CreateType string `json:"create_type"`
CreatedAt string `json:"created_at"`
CrmOncallType int `json:"crm_oncall_type"`
EffectiveAt string `json:"effective_at"`
EleBusinessState string `json:"ele_business_state"`
EleDeliveryParty string `json:"ele_delivery_party"`
EleID string `json:"ele_id"`
EleOnlineStatus string `json:"ele_online_status"`
EleShopLogo interface{} `json:"ele_shop_logo"`
IsSignZhongbao string `json:"is_sign_zhongbao"`
OnlineStatus string `json:"online_status"`
Phone string `json:"phone"`
ServStatus string `json:"serv_status"`
ShopTransactionOpen int `json:"shop_transaction_open"`
SourceName string `json:"source_name"`
SupplierID string `json:"supplier_id"`
TakeoutBoxPrice string `json:"takeout_box_price"`
TakeoutDispatchTime []struct {
End string `json:"end"`
Start string `json:"start"`
} `json:"takeout_dispatch_time"`
TakeoutOncallType string `json:"takeout_oncall_type"`
TakeoutOpenTime []struct {
End string `json:"end"`
Start string `json:"start"`
} `json:"takeout_open_time"`
TakeoutServicePhone string `json:"takeout_service_phone"`
TakeoutShopLogo string `json:"takeout_shop_logo"`
TransferStatus string `json:"transfer_status"`
} `json:"shop_info"`
ShopRole int `json:"shop_role"`
ShopUserID string `json:"shop_user_id"`
SwitchFromSupplier int `json:"switch_from_supplier"`
UserName string `json:"user_name"`
UserPhone string `json:"user_phone"`
YellowPrompt struct {
Capacity int `json:"capacity"`
Complete int `json:"complete"`
Display bool `json:"display"`
Msg string `json:"msg"`
MsgCount int `json:"msg_count"`
MsgList []interface{} `json:"msg_list"`
Online int `json:"online"`
PcURL string `json:"pc_url"`
TransferStatus string `json:"transfer_status"`
Type int `json:"type"`
URL string `json:"url"`
} `json:"yellow_prompt"`
}
type PageShopHealthInfo struct {
MerchantID string `json:"merchant_id"`
MerchantName string `json:"merchant_name"`
BadOrderRate string `json:"bad_order_rate"`
Category2 string `json:"category_2"`
Data string `json:"data"`
EndTime string `json:"endTime"`
HasPhotoRate string `json:"has_photo_rate"`
Hours string `json:"hours"`
ID string `json:"id"`
IsButie string `json:"is_butie"`
IsCp string `json:"is_cp"`
IsDeliverFee string `json:"is_deliver_fee"`
IsGood string `json:"is_good"`
IsHealthy string `json:"is_healthy"`
IsJiedan string `json:"is_jiedan"`
IsManjian string `json:"is_manjian"`
IsQisong string `json:"is_qisong"`
IsShopNew string `json:"is_shop_new"`
IsSku string `json:"is_sku"`
IsYinye string `json:"is_yinye"`
IsYoutu string `json:"is_youtu"`
IsZs string `json:"is_zs"`
MinDeliveryFee string `json:"min_delivery_fee"`
MinDeliveryPrice string `json:"min_delivery_price"`
RestaurantSubsidy string `json:"restaurant_subsidy"`
ShopCategory string `json:"shop_category"`
ShopID string `json:"shop_id"`
SkuNum string `json:"sku_num"`
StartTime string `json:"startTime"`
TargetButie string `json:"target_butie"`
TargetCp string `json:"target_cp"`
TargetDeliverFee string `json:"target_deliver_fee"`
TargetJiedan string `json:"target_jiedan"`
TargetQisong string `json:"target_qisong"`
TargetSku string `json:"target_sku"`
TargetYinye string `json:"target_yinye"`
TargetYoutu string `json:"target_youtu"`
UnvalidOrderNum string `json:"unvalid_order_num"`
UpdateTime string `json:"update_time"`
Week string `json:"week"`
}
func (a *API) SetStoreCookie(key, value string) {
a.locker.Lock()
defer a.locker.Unlock()
@@ -43,7 +170,7 @@ func (a *API) GetStoreCookie(key string) string {
return a.storeCookies[key]
}
func (a *API) AccessStorePage(subURL string) (retVal map[string]interface{}, err error) {
func (a *API) AccessStorePage2(subURL string, params map[string]interface{}, cookies map[string]string) (retVal map[string]interface{}, err error) {
a.locker.RLock()
storeCookieLen := len(a.storeCookies)
a.locker.RUnlock()
@@ -52,11 +179,15 @@ func (a *API) AccessStorePage(subURL string) (retVal map[string]interface{}, err
}
err = platformapi.AccessPlatformAPIWithRetry(a.client,
func() *http.Request {
var request *http.Request
fullURL := utils.GenerateGetURL(storeURL, subURL, nil)
// baseapi.SugarLogger.Debug(fullURL)
request, _ := http.NewRequest(http.MethodGet, fullURL, nil)
if err != nil {
return nil
if params == nil {
// baseapi.SugarLogger.Debug(fullURL)
request, _ = http.NewRequest(http.MethodGet, fullURL, nil)
} else {
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")
}
a.locker.RLock()
for k, v := range a.storeCookies {
@@ -65,15 +196,30 @@ func (a *API) AccessStorePage(subURL string) (retVal map[string]interface{}, err
Value: v,
})
}
for k, v := range cookies {
request.AddCookie(&http.Cookie{
Name: k,
Value: v,
})
}
a.locker.RUnlock()
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
retVal = jsonResult1
code := int(utils.MustInterface2Int64(jsonResult1["errno"]))
if code == ResponseCodeSuccess {
retVal = jsonResult1["data"].(map[string]interface{})
if subURL == swithShopURL {
for _, v := range response.Cookies() {
if v.Name == "SWITCH_SHOP" {
retVal = utils.Struct2FlatMap(v)
break
}
}
} else {
retVal, _ = jsonResult1["data"].(map[string]interface{})
}
return platformapi.ErrLevelSuccess, nil
}
newErr := utils.NewErrorIntCode(jsonResult1["errmsg"].(string), code)
@@ -86,6 +232,10 @@ func (a *API) AccessStorePage(subURL string) (retVal map[string]interface{}, err
return retVal, err
}
func (a *API) AccessStorePage(subURL string, params map[string]interface{}) (retVal map[string]interface{}, err error) {
return a.AccessStorePage2(subURL, params, nil)
}
func (a *API) GetRealMobile4Order(orderId string) (mobile string, err error) {
retVal, err := a.GetStoreOrderInfo(orderId)
if err == nil {
@@ -95,7 +245,7 @@ func (a *API) GetRealMobile4Order(orderId string) (mobile string, err error) {
}
func (a *API) GetStoreOrderInfo(orderId string) (storeOrderInfo map[string]interface{}, err error) {
retVal, err := a.AccessStorePage(fmt.Sprintf("crm/orderlist?keyword=%s", orderId))
retVal, err := a.AccessStorePage(fmt.Sprintf("crm/orderlist?keyword=%s", orderId), nil)
// baseapi.SugarLogger.Debug(utils.Format4Output(retVal, false))
if err == nil {
resultList := retVal["order_list"].([]interface{})
@@ -122,7 +272,7 @@ func (a *API) GetStoreOrderInfoList(fromTime, toTime string, shopID string, orde
}
fixedURL := fmt.Sprintf(urlTemplate, params...)
for {
retVal, err2 := a.AccessStorePage(fixedURL + "&page=" + utils.Int2Str(pageNo))
retVal, err2 := a.AccessStorePage(fixedURL+"&page="+utils.Int2Str(pageNo), nil)
// baseapi.SugarLogger.Debug(utils.Format4Output(retVal, false))
if err = err2; err == nil {
resultList := retVal["order_list"].([]interface{})
@@ -172,7 +322,7 @@ func (a *API) getCommentList(isElm bool, fromTime, toTime time.Time, shopID, sup
}
fixedURL := fmt.Sprintf(urlTemplate, params...)
for {
retVal, err2 := a.AccessStorePage(fixedURL + "&page_num=" + utils.Int2Str(pageNo))
retVal, err2 := a.AccessStorePage(fixedURL+"&page_num="+utils.Int2Str(pageNo), nil)
if err = err2; err == nil {
for _, comment := range retVal["comment_list"].([]interface{}) {
commentMap := comment.(map[string]interface{})
@@ -212,7 +362,7 @@ func (a *API) PageGetSkuList(baiduShopID int64) (skuList []map[string]interface{
}
fixedURL := fmt.Sprintf(urlTemplate, params...)
for {
retVal, err2 := a.AccessStorePage(fixedURL + "&curpage=" + utils.Int2Str(pageNo))
retVal, err2 := a.AccessStorePage(fixedURL+"&curpage="+utils.Int2Str(pageNo), nil)
if err = err2; err == nil {
for _, sku := range retVal["sku_list"].([]interface{}) {
skuList = append(skuList, sku.(map[string]interface{}))
@@ -235,7 +385,7 @@ func (a *API) PageGetCustomSkuList(baiduShopID int64, customCatID int64) (skuLis
customCatID,
}
fixedURL := fmt.Sprintf(urlTemplate, params...)
retVal, err := a.AccessStorePage(fixedURL)
retVal, err := a.AccessStorePage(fixedURL, nil)
if err == nil {
return utils.Slice2MapSlice(retVal["sku_list"].([]interface{})), nil
}
@@ -248,9 +398,64 @@ func (a *API) PageGetCustomCatList(baiduShopID int64) (catList []map[string]inte
baiduShopID,
}
fixedURL := fmt.Sprintf(urlTemplate, params...)
retVal, err := a.AccessStorePage(fixedURL)
retVal, err := a.AccessStorePage(fixedURL, nil)
if err == nil {
return utils.Slice2MapSlice(retVal["cat_list"].([]interface{})), nil
}
return nil, err
}
func (a *API) SwitchShop(baiduShopID int64) (switchShopCookie string, err error) {
result, err := a.AccessStorePage("crm/manager/switchshop", map[string]interface{}{
"switch_shop_id": baiduShopID,
})
if err == nil {
switchShopCookie = utils.Interface2String(result["Value"])
}
return switchShopCookie, err
}
func (a *API) GetShopUserInfo2(switchShopCookie string) (shopUserInfo *PageShopUserInfo, err error) {
shopInfo, err := a.AccessStorePage2("crm/account/getshopuserinfo", nil, map[string]string{
"SWITCH_SHOP": switchShopCookie,
})
if err == nil {
err = utils.Map2StructByJson(shopInfo, &shopUserInfo, true)
}
return shopUserInfo, err
}
func (a *API) GetShopUserInfo(baiduShopID int64) (shopUserInfo *PageShopUserInfo, err error) {
switchShopCookie, err := a.SwitchShop(baiduShopID)
if err != nil {
return nil, err
}
return a.GetShopUserInfo2(switchShopCookie)
}
func (a *API) GetShopHealthByDetail2(switchShopCookie string) (shopHealthDetail *PageShopHealthInfo, err error) {
shopInfo, err := a.GetShopUserInfo2(switchShopCookie)
if err != nil {
return nil, err
}
result, err := a.AccessStorePage2("crm/getshophealthydetail", map[string]interface{}{
"shop_id": shopInfo.EleID,
}, map[string]string{
"SWITCH_SHOP": switchShopCookie,
})
if err == nil {
if err = utils.Map2StructByJson(result, &shopHealthDetail, true); err == nil {
shopHealthDetail.MerchantID = shopInfo.MerchantID
shopHealthDetail.MerchantName = shopInfo.MerchantName
}
}
return shopHealthDetail, err
}
func (a *API) GetShopHealthByDetail(baiduShopID int64) (shopHealthDetail *PageShopHealthInfo, err error) {
switchShopCookie, err := a.SwitchShop(baiduShopID)
if err != nil {
return nil, err
}
return a.GetShopHealthByDetail2(switchShopCookie)
}

View File

@@ -81,3 +81,27 @@ func TestPageGetCustomCatList(t *testing.T) {
baseapi.SugarLogger.Debug(utils.Format4Output(catList, false))
}
}
func TestSwitchShop(t *testing.T) {
cookie, err := api.SwitchShop(2233065941)
if err != nil {
t.Fatal(err)
}
t.Log(cookie)
}
func TestGetShopUserInfo(t *testing.T) {
result, err := api.GetShopUserInfo(32267034127)
if err != nil {
t.Fatal(err)
}
t.Log(utils.Format4Output(result, false))
}
func TestGetShopHealthByDetail(t *testing.T) {
result, err := api.GetShopHealthByDetail(32267034127)
if err != nil {
t.Fatal(err)
}
t.Log(utils.Format4Output(result, false))
}

View File

@@ -159,7 +159,7 @@ func (a *API) AccessAPI(action string, params map[string]interface{}) (retVal *R
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (result string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (result string, err error) {
resultError, _ := jsonResult1["error"].(map[string]interface{})
retVal = &ResponseResult{
ID: jsonResult1["id"].(string),
@@ -216,7 +216,7 @@ func (a *API) AcccessAPI2(baseURL string, params map[string]interface{}, method
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (result string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (result string, err error) {
retVal = jsonResult1
return platformapi.ErrLevelSuccess, nil
})

View File

@@ -121,7 +121,7 @@ func (a *API) AccessAPI(apiName string, apiParams map[string]interface{}) (retVa
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
code := int(utils.Interface2Int64WithDefault(jsonResult1["ret"], ResponseCodeSuccess))
if code == ResponseCodeSuccess {
retVal = jsonResult1["data"]

View File

@@ -184,7 +184,7 @@ func (a *API) AccessAPI(apiStr string, jdParams map[string]interface{}) (retVal
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
code := jsonResult1["code"].(string)
if code == ResponseCodeSuccess {
retVal = jsonResult1

View File

@@ -55,7 +55,7 @@ func (a *API) AccessStorePage(fullURL string) (retVal map[string]interface{}, er
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
retVal = jsonResult1
code := jsonResult1["code"].(string)
if code == ResponseCodeSuccess {

View File

@@ -215,7 +215,7 @@ func (a *API) AccessAPI(action string, params map[string]interface{}) (retVal *R
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (result string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (result string, err error) {
code := int(utils.MustInterface2Int64(jsonResult1["code"]))
retVal = &ResponseResult{
Code: code,

View File

@@ -146,7 +146,7 @@ func (a *API) AccessAPI2(cmd string, isGet bool, bizParams map[string]interface{
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
if errObj, ok := jsonResult1["error"]; ok {
baseapi.SugarLogger.Debugf("mtwm AccessAPI failed, jsonResult1:%s", utils.Format4Output(jsonResult1, true))
errorInfo := errObj.(map[string]interface{})

View File

@@ -89,7 +89,7 @@ func getClonedData(requestURL *url.URL, r *bytes.Buffer) string {
return retVal
}
func AccessPlatformAPIWithRetry(client *http.Client, handleRequest func() *http.Request, config *APIConfig, handleResponse func(bodyMap map[string]interface{}) (string, error)) error {
func AccessPlatformAPIWithRetry(client *http.Client, handleRequest func() *http.Request, config *APIConfig, handleResponse func(response *http.Response, bodyMap map[string]interface{}) (string, error)) error {
exceedLimitRetryCount := 0
recoverableErrorRetryCount := 0
for {
@@ -155,7 +155,7 @@ func AccessPlatformAPIWithRetry(client *http.Client, handleRequest func() *http.
if err != nil {
errLevel = ErrLevelRecoverableErr // 读取数据错误,或数据格式错误认为是偶发情况,重试
} else {
errLevel, err = handleResponse(bodyMap)
errLevel, err = handleResponse(response, bodyMap)
}
if err == nil {
return nil

View File

@@ -162,7 +162,7 @@ func (a *API) AccessAPI(apiStr string, apiParams map[string]interface{}) (retVal
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
// baseapi.SugarLogger.Debug(utils.Format4Output(jsonResult1, false))
code := ResponseCodeSuccess
errMsg := ""

View File

@@ -100,7 +100,7 @@ func (a *API) AccessAPI(action string, params map[string]interface{}, body strin
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (result string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (result string, err error) {
var errInfo *ErrorInfo
// 微信的返回值,在错误与正常情况下,结构是完全不一样的
if errCode, ok := jsonResult1["errcode"]; ok {

View File

@@ -80,7 +80,7 @@ func (a *API) AccessAPI(apiName string, apiParams map[string]interface{}) (retVa
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
code := int(utils.Interface2Int64WithDefault(jsonResult1["errno"], ResponseCodeSuccess))
if code == ResponseCodeSuccess {
retVal = jsonResult1

View File

@@ -91,7 +91,7 @@ func (a *API) AccessAPI(apiName string, apiParams map[string]interface{}) (retVa
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
code := utils.Interface2String(jsonResult1["error"])
if code == ResponseCodeSuccess {
retVal, _ = jsonResult1["body"].(map[string]interface{})

View File

@@ -88,7 +88,7 @@ func (a *API) AccessAPI(apiName string, apiParams map[string]interface{}, isGet
return request
},
a.config,
func(jsonResult1 map[string]interface{}) (errLevel string, err error) {
func(response *http.Response, jsonResult1 map[string]interface{}) (errLevel string, err error) {
code := int(utils.MustInterface2Int64(jsonResult1["errNum"]))
if code == ResponseCodeSuccess {
retVal, _ = jsonResult1["retData"].(map[string]interface{})