package jdshopapi
import (
"encoding/json"
"fmt"
"net/http"
"regexp"
"strings"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/platformapi"
"git.rosy.net.cn/baseapi/utils"
)
var (
regexpOrderDetailTable = regexp.MustCompile(`
`)
regexpOrderDetailTd = regexp.MustCompile(`(.*?) | `)
regexpOrderDetailMobile = regexp.MustCompile(`(.*?)`)
regexpOrderDetailDay = regexp.MustCompile(`期望送货日期: | [\s\S]*?(.*?) | `)
regexpOrderDetailPay = regexp.MustCompile(`应支付金额: | [\s\S]*?[\s\S]*?¥(.*?[\s\S]*?) | `)
regexpOrderDetailMobileKey = regexp.MustCompile(`accesskey="(.*?)"`)
)
const (
JdsOrderDeliverTypeStore = 1274
JdsOrderDeleverTypeSelf = 332098
)
func (a *API) AccessStorePage(fullURL string, bizParams map[string]interface{}, isPost bool) (retVal map[string]interface{}, err error) {
if a.GetCookieCount() == 0 {
return nil, fmt.Errorf("需要设置Store Cookie才能使用此方法")
}
err = platformapi.AccessPlatformAPIWithRetry(a.client,
func() *http.Request {
var request *http.Request
if isPost {
request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(bizParams).Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else {
request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(fullURL, "", bizParams), nil)
}
a.FillRequestCookies(request)
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 strings.Contains(bodyStr, "登录") || strings.Contains(bodyStr, "访问的内容") {
return platformapi.ErrLevelRecoverableErr, fmt.Errorf("cookie可能过期了!")
}
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) AccessStorePage2(fullURL string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
if a.GetCookieCount() == 0 {
return nil, fmt.Errorf("需要设置Store Cookie才能使用此方法")
}
data, _ := json.Marshal(bizParams)
err = platformapi.AccessPlatformAPIWithRetry(a.client,
func() *http.Request {
request, _ := http.NewRequest(http.MethodPost, fullURL, strings.NewReader(string(data)))
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
a.FillRequestCookies(request)
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 strings.Contains(bodyStr, "登录") || strings.Contains(bodyStr, "访问的内容") {
return platformapi.ErrLevelRecoverableErr, fmt.Errorf("cookie可能过期了!")
}
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
}
type CreateShopCategoryParam struct {
HomeShow string `json:"homeShow"`
ID string `json:"id"`
Open string `json:"open"`
OrderNo string `json:"orderNo"`
ParentID string `json:"parentId"`
Title string `json:"title"`
Type string `json:"type"`
}
//京东商城创建或修改店内分类
//https://seller.shop.jd.com/vendershop/vendershop_shopCategory.action#
func (a *API) CreateShopCategory(createShopCategoryParam []*CreateShopCategoryParam) (status int64, err error) {
data, _ := json.MarshalIndent(createShopCategoryParam, "", "")
result, err := a.AccessStorePage("https://seller.shop.jd.com/vendershop/vendershop_doShopCategory.action", map[string]interface{}{
"categoryJson": string(data),
}, true)
if err == nil {
status = utils.Interface2Int64WithDefault(result["fakeData"], -1)
}
return status, err
}
//京东商城设置门店营业状态
//https://stores.shop.jd.com/stores/updateStoreStatus?storeId=24330156&storeStatus=6
func (a *API) UpdateStoreStatus(storeID, storeStatus int) (err error) {
_, err = a.AccessStorePage("https://stores.shop.jd.com/stores/updateStoreStatus", map[string]interface{}{
"storeId": storeID,
"storeStatus": storeStatus,
}, false)
return err
}
type NewInfoListResult struct {
ID int `json:"id"`
VenderID int `json:"venderId"`
CompanyID interface{} `json:"companyId"`
CompanyName interface{} `json:"companyName"`
StoreType interface{} `json:"storeType"`
Name string `json:"name"`
AddCode int `json:"addCode"`
AddCodeName interface{} `json:"addCodeName"`
AddName string `json:"addName"`
AddCode1 int `json:"addCode1"`
AddCode2 int `json:"addCode2"`
AddCode4 interface{} `json:"addCode4"`
BussinessBeginTime interface{} `json:"bussinessBeginTime"`
BussinessEndTime interface{} `json:"bussinessEndTime"`
AddNameExtend interface{} `json:"addNameExtend"`
Coordinate interface{} `json:"coordinate"`
CommodityNum int `json:"commodityNum"`
Status interface{} `json:"status"`
Created interface{} `json:"created"`
Modified interface{} `json:"modified"`
Phone interface{} `json:"phone"`
EncryptPhone interface{} `json:"encryptPhone"`
StoreGroupIds interface{} `json:"storeGroupIds"`
VirtualStoresIds interface{} `json:"virtualStoresIds"`
VirtualStoresInDB interface{} `json:"virtualStoresInDB"`
Address interface{} `json:"address"`
Account interface{} `json:"account"`
UserName interface{} `json:"userName"`
Pwd interface{} `json:"pwd"`
CrmPwd interface{} `json:"crmPwd"`
Type interface{} `json:"type"`
AccountIsAuth interface{} `json:"accountIsAuth"`
Slogan interface{} `json:"slogan"`
Mobilephone interface{} `json:"mobilephone"`
EncryptMobilephone interface{} `json:"encryptMobilephone"`
UnboundedBizType interface{} `json:"unboundedBizType"`
ExStoreID string `json:"exStoreId"`
ExStoreSource interface{} `json:"exStoreSource"`
MdImg interface{} `json:"mdImg"`
AccountName interface{} `json:"accountName"`
StoreStatus int `json:"storeStatus"`
BusinessTime interface{} `json:"businessTime"`
IsBindingPurse interface{} `json:"isBindingPurse"`
GroupName interface{} `json:"groupName"`
SplitID interface{} `json:"splitId"`
BusinessID interface{} `json:"businessId"`
BrandID interface{} `json:"brandId"`
ReturnType interface{} `json:"returnType"`
PhoneType interface{} `json:"phoneType"`
AfterPhone interface{} `json:"afterPhone"`
DeptID interface{} `json:"deptId"`
Remark interface{} `json:"remark"`
AuditStatus int `json:"auditStatus"`
CategoryID1 interface{} `json:"categoryId1"`
CategoryID2 interface{} `json:"categoryId2"`
CategoryName1 interface{} `json:"categoryName1"`
CategoryName2 interface{} `json:"categoryName2"`
ImgURL interface{} `json:"imgUrl"`
StoreStatusName string `json:"storeStatusName"`
AuditStatusName string `json:"auditStatusName"`
OperateStatus interface{} `json:"operateStatus"`
Pin interface{} `json:"pin"`
}
//京东商城查询门店营业状态
//https://stores.shop.jd.com/stores/newInfoList
func (a *API) NewInfoList(storeID int64) (newInfoListResult *NewInfoListResult, err error) {
var newInfoListResult2 []*NewInfoListResult
result, err := a.AccessStorePage2("https://stores.shop.jd.com/stores/newInfoList", map[string]interface{}{
"storeId": storeID,
"inCache": 0,
"index": 1,
"pageSize": 10,
"companyName": nil,
"exStoreId": nil,
"storeName": nil,
"storeStatus": nil,
})
if err == nil {
utils.Map2StructByJson(result["list"], &newInfoListResult2, false)
}
newInfoListResult = newInfoListResult2[0]
return newInfoListResult, err
}
type AllOrdersParam struct {
Current int `json:"current"`
PageSize int `json:"pageSize"`
SortName string `json:"sortName"`
OrderID string `json:"orderId"`
SkuName string `json:"skuName"`
OrderCreateDateRange []string `json:"orderCreateDateRange"`
OrderCompleteDateRange []interface{} `json:"orderCompleteDateRange"`
ReceiverName string `json:"receiverName"`
ReceiverTel string `json:"receiverTel"`
UserPin string `json:"userPin"`
SkuID string `json:"skuId"`
LogiNo string `json:"logiNo"`
PaymentType string `json:"paymentType"`
OrderType string `json:"orderType"`
OrderSource string `json:"orderSource"`
DeliveryType string `json:"deliveryType"`
StoreID string `json:"storeId"`
HuoHao string `json:"huoHao"`
OrderStatusArray []interface{} `json:"orderStatusArray"`
SelectedTabName string `json:"selectedTabName"`
}
type AllOrdersResult struct {
TotalCount int `json:"totalCount"`
Current int `json:"current"`
OrderList []struct {
XiaDanTime interface{} `json:"xiaDanTime"`
ModifiedTime interface{} `json:"modifiedTime"`
CustomsName interface{} `json:"customsName"`
MerchantName interface{} `json:"merchantName"`
CustomsModelName interface{} `json:"customsModelName"`
ProcessStatus interface{} `json:"processStatus"`
StorageAndShipStatus interface{} `json:"storageAndShipStatus"`
ProcessStatusMsg interface{} `json:"processStatusMsg"`
OrderID int64 `json:"orderId"`
SelectedTabName interface{} `json:"selectedTabName"`
VenderID int `json:"venderId"`
OrderCreateTime string `json:"orderCreateTime"`
PaymentConfirmTime string `json:"paymentConfirmTime"`
OrderCompleteTime interface{} `json:"orderCompleteTime"`
OrderItems []struct {
WareID interface{} `json:"wareId"`
SkuID int64 `json:"skuId"`
SkuName string `json:"skuName"`
HuoHao interface{} `json:"huoHao"`
JdPrice float64 `json:"jdPrice"`
SkuNum int `json:"skuNum"`
SkuImg interface{} `json:"skuImg"`
URL string `json:"url"`
ServiceName string `json:"serviceName"`
Imei interface{} `json:"imei"`
SequenceFlag bool `json:"sequenceFlag"`
SequenceInfoList interface{} `json:"sequenceInfoList"`
UpdateCount interface{} `json:"updateCount"`
CertificateFlag bool `json:"certificateFlag"`
CertificateInfoList interface{} `json:"certificateInfoList"`
MedicalInfoFlag bool `json:"medicalInfoFlag"`
MedicalInfoParamVos interface{} `json:"medicalInfoParamVos"`
UniqueCode interface{} `json:"uniqueCode"`
InspectReportID interface{} `json:"inspectReportId"`
} `json:"orderItems"`
PaymentTypeName string `json:"paymentTypeName"`
ShouldPay float64 `json:"shouldPay"`
Freight float64 `json:"freight"`
ServiceFee interface{} `json:"serviceFee"`
Commission float64 `json:"commission"`
CouponFlag bool `json:"couponFlag"`
UserPin string `json:"userPin"`
UserRemark string `json:"userRemark"`
ConsigneeInfo interface{} `json:"consigneeInfo"`
LogiFlag bool `json:"logiFlag"`
LogisticsInfos []interface{} `json:"logisticsInfos"`
StoreName string `json:"storeName"`
CodDT interface{} `json:"codDT"`
ScDT interface{} `json:"scDT"`
OrderStatusStrCN string `json:"orderStatusStrCN"`
OrderStatus int `json:"orderStatus"`
InvalidOrderFlag bool `json:"invalidOrderFlag"`
OrderType int `json:"orderType"`
CustomsModel interface{} `json:"customsModel"`
SalesPin interface{} `json:"salesPin"`
MdbStoreID interface{} `json:"mdbStoreId"`
SuspendType interface{} `json:"suspendType"`
SuspendReason interface{} `json:"suspendReason"`
SuspendReasonDesc interface{} `json:"suspendReasonDesc"`
SuspendDetailReasonFlag interface{} `json:"suspendDetailReasonFlag"`
StoreInfo interface{} `json:"storeInfo"`
IsDivShow bool `json:"isDivShow"`
IsMenDianOrder bool `json:"isMenDianOrder"`
IsMenDianBangOrder bool `json:"isMenDianBangOrder"`
IsMenDianZiTiOrder bool `json:"isMenDianZiTiOrder"`
IsPhoneOrder bool `json:"isPhoneOrder"`
IsReturnOrder bool `json:"isReturnOrder"`
IsPreSaleOrder bool `json:"isPreSaleOrder"`
IsVenderSplitOrder bool `json:"isVenderSplitOrder"`
IsAuctionOrder bool `json:"isAuctionOrder"`
IsLargeAmountOrder bool `json:"isLargeAmountOrder"`
IsMicroShopOrder bool `json:"isMicroShopOrder"`
IsRuralPromotionOrder bool `json:"isRuralPromotionOrder"`
IsHkMacaoOrder bool `json:"isHkMacaoOrder"`
IsTaiWanOrder bool `json:"isTaiWanOrder"`
IsOverseasOrder bool `json:"isOverseasOrder"`
IsDistributionOrder bool `json:"isDistributionOrder"`
IsJdDeliveryOrder bool `json:"isJdDeliveryOrder"`
IsEclpOrder bool `json:"isEclpOrder"`
IsYiPanHuoOrder bool `json:"isYiPanHuoOrder"`
IsJingZunDaOrder bool `json:"isJingZunDaOrder"`
IsBrandMall bool `json:"isBrandMall"`
IsPinGou bool `json:"isPinGou"`
IsYhd bool `json:"isYhd"`
IsXtl bool `json:"isXtl"`
IsSplitOrder bool `json:"isSplitOrder"`
IsCloudWarehouseOrder bool `json:"isCloudWarehouseOrder"`
IsTopLifeOrder bool `json:"isTopLifeOrder"`
IsTuanGou bool `json:"isTuanGou"`
IsDuoBaoDao bool `json:"isDuoBaoDao"`
IsJingPinShi bool `json:"isJingPinShi"`
BizLinkVo struct {
ShowModifyFee bool `json:"showModifyFee"`
ShowSingleOut bool `json:"showSingleOut"`
ShowModifyAddr bool `json:"showModifyAddr"`
ShowDelayDeliveryRemind bool `json:"showDelayDeliveryRemind"`
ShowSplitOrder bool `json:"showSplitOrder"`
ShowMoreLogisticsDelivery bool `json:"showMoreLogisticsDelivery"`
ShowMergeDelivery bool `json:"showMergeDelivery"`
ShowInfoCheck bool `json:"showInfoCheck"`
ShowLivingAuth bool `json:"showLivingAuth"`
ShowModifyWaybill bool `json:"showModifyWaybill"`
} `json:"bizLinkVo"`
IsOut bool `json:"isOut"`
IsMultiLogisticsOutShow bool `json:"isMultiLogisticsOutShow"`
PaimaiOrder int `json:"paimaiOrder"`
CannotModifyProvinceAndCity bool `json:"cannotModifyProvinceAndCity"`
CanWaitInnerShip bool `json:"canWaitInnerShip"`
ShowShangChuanHeTong bool `json:"showShangChuanHeTong"`
ShowManageCertificate bool `json:"showManageCertificate"`
OrderSeqFlag bool `json:"orderSeqFlag"`
CustomInfoFlag bool `json:"customInfoFlag"`
OrderDaYangFlag bool `json:"orderDaYangFlag"`
ShowMedicalInfo bool `json:"showMedicalInfo"`
Card3CFlag bool `json:"card3cFlag"`
ShowOrderPackage bool `json:"showOrderPackage"`
ShowWaybill bool `json:"showWaybill"`
IsGlobalZhiYouOrder bool `json:"isGlobalZhiYouOrder"`
IsGlobalBaoShuiOrder bool `json:"isGlobalBaoShuiOrder"`
ManageImeiFlag bool `json:"manageImeiFlag"`
SpecialViewOrder []interface{} `json:"specialViewOrder"`
} `json:"orderList"`
Cluster interface{} `json:"cluster"`
}
//尝试扒订单
//https://porder.shop.jd.com/order/orderlist/allOrders
func (a *API) AllOrders(allOrdersParam *AllOrdersParam) (allOrdersResult *AllOrdersResult, err error) {
result, err := a.AccessStorePage2("https://porder.shop.jd.com/order/orderlist", map[string]interface{}{
"current": allOrdersParam.Current,
"pageSize": allOrdersParam.PageSize,
"selectedTabName": "allOrders",
"sortName": "desc",
"orderCreateDateRange": allOrdersParam.OrderCreateDateRange,
// "storeId": allOrdersParam.StoreID,
"orderStatusArray": allOrdersParam.OrderStatusArray,
"orderId": allOrdersParam.OrderID,
})
if err == nil {
utils.Map2StructByJson(result, &allOrdersResult, false)
}
return allOrdersResult, err
}
type OrderDetailResult struct {
ConsigneeName string `json:"consigneeName"`
ConsigneeAddress string `json:"consigneeAddress"`
ConsigneeMobile string `json:"consigneeMobile"`
ExpectedDeliveredTime string `json:"expectedDeliveredTime"`
ActualPayPrice int64 `json:"actualPayPrice"`
MobileKey string `json:"mobileKey"`
}
//订单详情
//https://neworder.shop.jd.com/order/orderDetail?orderId=122367441996
func (a *API) OrderDetail(orderId string) (orderDetailResult *OrderDetailResult, err error) {
result, err := a.AccessStorePage("https://neworder.shop.jd.com/order/orderDetail", map[string]interface{}{
"orderId": orderId,
}, false)
if err == nil {
orderDetailResult = &OrderDetailResult{}
body := result["fakeData"].(string)
expectedDeliveredTime := regexpOrderDetailDay.FindStringSubmatch(body)
actualPayPrice := regexpOrderDetailPay.FindStringSubmatch(body)
consigneeTable := regexpOrderDetailTable.FindStringSubmatch(body)
mobileKey := regexpOrderDetailMobileKey.FindStringSubmatch(body)
if len(consigneeTable) > 0 {
consigneeTd := regexpOrderDetailTd.FindAllStringSubmatch(consigneeTable[1], -1)
consigneeMobiles := regexpOrderDetailMobile.FindStringSubmatch(consigneeTable[1])
if len(consigneeTd) > 0 {
orderDetailResult.ConsigneeName = consigneeTd[0][1]
orderDetailResult.ConsigneeAddress = consigneeTd[1][1]
}
if len(consigneeMobiles) > 0 {
orderDetailResult.ConsigneeMobile = consigneeMobiles[1]
}
}
if len(expectedDeliveredTime) > 0 {
// times := strings.Split(expectedDeliveredTime[1], ",")
// orderDetailResult.ExpectedDeliveredTime = times[0] + " " + times[1][:strings.Index(times[1], ":")] + ":00:00"
orderDetailResult.ExpectedDeliveredTime = expectedDeliveredTime[1][:strings.LastIndex(expectedDeliveredTime[1], "-")] + ":00"
}
if len(actualPayPrice) > 0 {
orderDetailResult.ActualPayPrice = utils.Float64TwoInt64(utils.Str2Float64(strings.TrimSpace(actualPayPrice[1])) * 100)
}
if len(mobileKey) > 0 {
orderDetailResult.MobileKey = mobileKey[1]
}
}
return orderDetailResult, err
}
//尝试获取订单的真实手机号
//https://https://neworder.shop.jd.com/order/json/phoneSensltiveInfo
func (a *API) PhoneSensltiveInfo(orderId, accessKey string) (fakeMobile string, err error) {
result, err := a.AccessStorePage("https://neworder.shop.jd.com/order/json/phoneSensltiveInfo", map[string]interface{}{
"orderId": orderId,
"accessKey": accessKey,
"accessType": "0",
"token": JdsMobileToken,
}, true)
if err == nil {
fakeMobile = result["model"].(map[string]interface{})["phone"].(string)
}
return fakeMobile, err
}
//订单的订单号转移
//https://porder.shop.jd.com/order/global/updateWaybill
func (a *API) UpdateWaybill(orderId, logiId, logiNo string) (err error) {
var waybiilList = []map[string]interface{}{}
param := map[string]interface{}{
"logiId": logiId,
"logiNos": []string{logiNo},
"overseas": false,
"logiNo": logiNo,
}
waybiilList = append(waybiilList, param)
_, err = a.AccessStorePage2("https://porder.shop.jd.com/order/global/updateWaybill", map[string]interface{}{
"orderId": orderId,
"globalOrder": false,
"waybillList": waybiilList,
})
return err
}