admin
2020-09-24 ca1ad791b7b7b04e57db6bd4fb93f0c1066a9f99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package com.yeshi.fanli.util.taobao;
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import com.yeshi.fanli.dto.order.OrderQuery;
import com.yeshi.fanli.dto.taobao.TaoBaoOrderResultDTO;
import com.yeshi.fanli.dto.taobao.WeiQuanOrderResult;
import com.yeshi.fanli.entity.taobao.TaoBaoOrder;
import com.yeshi.fanli.entity.taobao.TaoBaoOrderGoods;
import com.yeshi.fanli.entity.taobao.TaoBaoPunishOrder;
import com.yeshi.fanli.entity.taobao.TaoBaoWeiQuanOrder;
import com.yeshi.common.entity.taobao.TaoKeAppInfo;
import com.yeshi.fanli.exception.taobao.TaoKeApiException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TaoBaoConstant;
import org.yeshi.utils.TimeUtil;
 
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
 
//淘宝客API接口
public class TaoKeOrderApiUtil {
 
    public static int TK_STATUS_ALL = 1;
    public static int TK_STATUS_SETTLEMENT = 3;
    public static int TK_STATUS_PAY = 12;
    public static int TK_STATUS_SUCCESS = 14;
    public static int TK_STATUS_INVALID = 13;
 
    private static TaoBaoPunishOrder parsePunishOrder(JSONObject data) {
        TaoBaoPunishOrder order = new TaoBaoPunishOrder();
        order.setPunishStatus(data.optString("punish_status"));
        order.setRelationId(data.optString("relation_id"));
        order.setSettleMonth(data.optString("settle_month"));
        order.setSpecialId(data.optString("special_id"));
        order.setTbTradeId(data.optString("tb_trade_id"));
        order.setTbTradeParentId(data.optString("tb_trade_parent_id"));
        order.setTkAdzoneId(data.optString("tk_adzone_id"));
        order.setTkPubId(data.optString("tk_pub_id"));
        order.setTkSiteId(data.optString("tk_site_id"));
        order.setTkTradeCreateTime(data.optString("tk_trade_create_time"));
        order.setViolationType(data.optString("violation_type"));
        return order;
    }
 
    public static List<TaoBaoPunishOrder> getPunishOrderList(Long startTime, Long endTime) {
        List<TaoBaoPunishOrder> resultList = new ArrayList<>();
        TaoKeAppInfo app = new TaoKeAppInfo();
        app.setAppKey(TaoBaoConstant.TAOBAO_AUTH_APPKEY);
        app.setAppSecret(TaoBaoConstant.TAOBAO_AUTH_APPSECRET);
        Map<String, String> map = new HashMap<>();
        map.put("method", "taobao.tbk.dg.punish.order.get");
        JSONObject data = new JSONObject();
        data.put("page_no", 1);
        data.put("page_size", 100);
        int sub = (int) ((endTime - startTime) / 1000);
        int span = 1800;
        int count = sub % span == 0 ? sub / span : sub / span + 1;
        for (int i = 0; i < count; i++) {
            int totalSpanOrderCount = 0;
            List<TaoBaoPunishOrder> spanOrderList = new ArrayList<>();
            long startT = startTime + i * span * 1000;
            data.put("start_time", TimeUtil.getGernalTime(startT, "yyyy-MM-dd HH:mm:ss"));
            data.put("span", 1800 + "");
            map.put("af_order_option", data.toString());
            try {
                JSONObject json = TaoKeBaseUtil.baseRequest(map, app);
                JSONObject dataJson = json.optJSONObject("tbk_dg_punish_order_get_response").optJSONObject("result")
                        .optJSONObject("data");
                JSONArray array = dataJson.optJSONObject("results").optJSONArray("result");
                if (array != null)
                    for (int n = 0; n < array.size(); n++) {
                        spanOrderList.add(parsePunishOrder(array.optJSONObject(n)));
                    }
                totalSpanOrderCount = dataJson.optInt("total_count");
                int page = 2;
                while (totalSpanOrderCount > spanOrderList.size())// 存在下一页
                {
                    data.put("page_no", page++);
                    map.put("af_order_option", data.toString());
                    json = TaoKeBaseUtil.baseRequest(map, app);
                    dataJson = json.optJSONObject("tbk_dg_punish_order_get_response").optJSONObject("data");
                    array = dataJson.optJSONArray("results");
                    if (array != null)
                        for (int n = 0; n < array.size(); n++) {
                            spanOrderList.add(parsePunishOrder(array.optJSONObject(n)));
                        }
                    totalSpanOrderCount = dataJson.optInt("total_count");
                }
                resultList.addAll(spanOrderList);
                System.out.println(json);
            } catch (TaoKeApiException e) {
                e.printStackTrace();
            }
        }
        return resultList;
    }
 
    private static TaoBaoOrderResultDTO parseTaoBaoOrderNew(String response) {
 
        TaoBaoOrderResultDTO dto = new TaoBaoOrderResultDTO(false, false, null, new ArrayList<>());
 
        List<TaoBaoOrder> orderList = new ArrayList<>();
        JSONArray array = null;
        JSONObject data = JSONObject.fromObject(response);
        try {
            JSONObject rootData = data.optJSONObject("tbk_order_details_get_response").optJSONObject("data");
            array = rootData.optJSONObject("results").optJSONArray("publisher_order_dto");
            dto.setHasPre(rootData.optBoolean("has_pre"));
            dto.setPositionIndex(rootData.optString("position_index"));
            dto.setHasNext(rootData.optBoolean("has_next"));
        } catch (Exception e) {
            return dto;
        }
 
        if (array != null)
            for (int i = 0; i < array.size(); i++) {
 
                JSONObject item = array.optJSONObject(i);
                try {
                    TaoBaoOrder taoBaoOrder = new TaoBaoOrder();
                    taoBaoOrder.setAdPositionId(item.optString("adzone_id"));
                    taoBaoOrder.setAdPositionName(item.optString("adzone_name"));
                    taoBaoOrder.setAuctionId(item.optLong("item_id"));
                    taoBaoOrder.setClassName(item.optString("item_category_name"));
                    taoBaoOrder.setClickTime(item.optString("click_time"));
                    taoBaoOrder.setPayTime(item.optString("tb_paid_time"));
                    taoBaoOrder.setCount(item.optInt("item_num"));
                    taoBaoOrder.setCreateTime(item.optString("tk_create_time"));
                    if (!StringUtil.isNullOrEmpty(item.optString("total_commission_fee")))
                        taoBaoOrder.seteIncome(new BigDecimal(item.optString("total_commission_fee")));
                    else
                        taoBaoOrder.seteIncome(new BigDecimal(0));
 
                    if (!StringUtil.isNullOrEmpty(item.optString("pub_share_pre_fee")))
                        taoBaoOrder.setEstimate(new BigDecimal(item.optString("pub_share_pre_fee")));
                    else
                        taoBaoOrder.setEstimate(new BigDecimal(0));
                    taoBaoOrder.setiRatio(new BigDecimal(item.optString("income_rate")));
                    taoBaoOrder.setLatestUpdateTime(null);
                    taoBaoOrder.setManagerWangWang(null);
                    taoBaoOrder.setOrderBy(null);
                    taoBaoOrder.setOrderId(item.optString("trade_parent_id"));
                    if (item.optInt("tk_status") == 12)
                        taoBaoOrder.setOrderState("订单付款");
                    else if (item.optInt("tk_status") == 3)
                        taoBaoOrder.setOrderState("订单结算");
                    else if (item.optInt("tk_status") == 13)
                        taoBaoOrder.setOrderState("订单失效");
                    else if (item.optInt("tk_status") == 14)
                        taoBaoOrder.setOrderState("订单成功");
 
                    taoBaoOrder.setOrderType(item.optString("order_type"));
                    if (!StringUtil.isNullOrEmpty(item.optString("alipay_total_price")))
                        taoBaoOrder.setPayment(new BigDecimal(item.optString("alipay_total_price")));
                    else
                        taoBaoOrder.setPayment(new BigDecimal(0));
                    if (StringUtil.isNullOrEmpty(item.optString("item_price")))
                        taoBaoOrder.setPrice(new BigDecimal(0));
                    else
                        taoBaoOrder.setPrice(new BigDecimal(item.optString("item_price")));
                    if (!StringUtil.isNullOrEmpty(item.optString("pay_price")))
                        taoBaoOrder.setSettlement(new BigDecimal(item.optString("pay_price")));
                    else
                        taoBaoOrder.setSettlement(taoBaoOrder.getPayment());
                    taoBaoOrder.setSettlementTime(item.optString("tk_earning_time"));
                    taoBaoOrder.setShop(item.optString("seller_shop_title"));
                    taoBaoOrder.setSourceMediaId(item.optString("site_id"));
                    taoBaoOrder.setSourceMediaName(item.optString("site_name"));
                    taoBaoOrder.setsRatio(null);
                    if (!StringUtil.isNullOrEmpty(item.optString("subsidy_fee")))// 补贴金额
                        taoBaoOrder.setSubsidy(new BigDecimal(item.optString("subsidy_fee")));
                    if (!StringUtil.isNullOrEmpty(item.optString("subsidy_rate")))
                        taoBaoOrder.setSubsidyRatio(new BigDecimal(item.optString("subsidy_rate")));
                    taoBaoOrder.setSubsidyType(item.optString("subsidy_type"));
                    taoBaoOrder.setTechnologySupportPercent(null);
                    taoBaoOrder.setThirdService(null);
                    taoBaoOrder.setTitle(item.optString("item_title"));
                    if (!StringUtil.isNullOrEmpty(item.optString("total_commission_fee")))
                        taoBaoOrder.setTkMoney(new BigDecimal(item.optString("total_commission_fee")));
                    else
                        taoBaoOrder.setTkMoney(new BigDecimal(0));
                    if (!StringUtil.isNullOrEmpty(item.optString("commission_rate")))
                        taoBaoOrder.setTkRate(new BigDecimal(item.optString("commission_rate")));
                    else if (!StringUtil.isNullOrEmpty(item.optString("total_commission_rate")))
                        taoBaoOrder.setTkRate(new BigDecimal(item.optString("total_commission_rate")));
                    taoBaoOrder.setTransactionPlatform(item.optString("terminal_type"));
                    taoBaoOrder.setRelationId(item.optString("relation_id"));
                    taoBaoOrder.setSpecialId(item.optString("special_id"));
                    taoBaoOrder.setTradeId(item.optString("trade_id"));
                    // 解析商品信息
                    TaoBaoOrderGoods goods = new TaoBaoOrderGoods();
                    goods.setCategoryName(item.optString("item_category_name"));
                    goods.setCreateTime(new Date());
                    goods.setGoodsId(item.optLong("item_id"));
                    goods.setImg(item.optString("item_img"));
                    goods.setLink(item.optString("item_link"));
                    goods.setPrice(item.optString("item_price"));
                    goods.setTitle(item.optString("item_title"));
                    goods.setTradeId(item.optString("trade_id"));
                    if (goods.getImg() != null && !goods.getImg().startsWith("http")) {
                        goods.setImg("http:" + goods.getImg());
                    }
 
                    taoBaoOrder.setGoods(goods);
                    orderList.add(taoBaoOrder);
                } catch (Exception e) {
                    try {
                        LogHelper.errorDetailInfo(e, "订单号信息:" + item.toString(), "订单解析出错");
                    } catch (Exception e1) {
                    }
                }
            }
        dto.setOrderList(orderList);
        return dto;
    }
 
    public static WeiQuanOrderResult getTaoBaoRelationWeiQuanOrderList(Date startTime, int searchType, int page,
            boolean third) {
 
        return getRelationAndSpecialWeiQuanOrderList(startTime, searchType, page, third, 1);
    }
 
    public static WeiQuanOrderResult getTaoBaoSpecialWeiQuanOrderList(Date startTime, int searchType, int page,
            boolean third) {
 
        return getRelationAndSpecialWeiQuanOrderList(startTime, searchType, page, third, 2);
    }
 
    private static WeiQuanOrderResult getRelationAndSpecialWeiQuanOrderList(Date startTime, int searchType, int page,
            boolean third, int bizType) {
        WeiQuanOrderResult finalResult = new WeiQuanOrderResult();
 
        List<TaoBaoWeiQuanOrder> list = new ArrayList<>();
        finalResult.orderList = list;
        Map<String, String> map = new HashMap<>();
        map.put("method", "taobao.tbk.relation.refund");
 
        JSONObject option = new JSONObject();
        option.put("search_type", searchType);
        option.put("refund_type", third ? 2 : 1);
        option.put("start_time", TimeUtil.getGernalTime(startTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
        option.put("page_no", page);
        option.put("page_size", 100);
        option.put("biz_type", bizType);
        map.put("search_option", option.toString());
 
        TaoKeAppInfo app = new TaoKeAppInfo();
        app.setAppKey(TaoBaoConstant.TAOBAO_AUTH_APPKEY);
        app.setAppSecret(TaoBaoConstant.TAOBAO_AUTH_APPSECRET);
        try {
            JSONObject json = TaoKeBaseUtil.baseRequest(map, app);
            JSONObject results = json.optJSONObject("tbk_relation_refund_response").optJSONObject("result")
                    .optJSONObject("data").optJSONObject("results");
            if (results == null)
                return finalResult;
 
            int count = results.optInt("total_count");
            finalResult.totalCount = count;
            JSONArray array = results.optJSONArray("result");
            if (array != null)
                for (int i = 0; i < array.size(); i++) {
                    JSONObject item = array.optJSONObject(i);
                    TaoBaoWeiQuanOrder order = new TaoBaoWeiQuanOrder();
                    order.setGoodsName(item.optString("tb_auction_title"));
                    BigDecimal fanMoney = new BigDecimal(0);
                    if (!StringUtil.isNullOrEmpty(item.optString("tk_subsidy_fee_refund3rd_pub"))) {
                        fanMoney = fanMoney.add(new BigDecimal(item.optString("tk_subsidy_fee_refund3rd_pub")));
                    }
                    if (!StringUtil.isNullOrEmpty(item.optString("tk_commission_fee_refund3rd_pub"))) {
                        fanMoney = fanMoney.add(new BigDecimal(item.optString("tk_commission_fee_refund3rd_pub")));
                    }
                    if (!StringUtil.isNullOrEmpty(item.optString("tk_subsidy_fee_refund_pub"))) {
                        fanMoney = fanMoney.add(new BigDecimal(item.optString("tk_subsidy_fee_refund_pub")));
                    }
                    if (!StringUtil.isNullOrEmpty(item.optString("tk_commission_fee_refund_pub"))) {
                        fanMoney = fanMoney.add(new BigDecimal(item.optString("tk_commission_fee_refund_pub")));
                    }
 
                    if (fanMoney.compareTo(new BigDecimal(0)) == 0)
                        fanMoney = null;
 
                    order.setFanMoney(fanMoney);
                    order.setJieSuanTime(new Date(
                            TimeUtil.convertToTimeTemp(item.optString("earning_time"), "yyyy-MM-dd HH:mm:ss")));
                    if (!StringUtil.isNullOrEmpty(item.optString("refund_fee")))
                        order.setMoney(new BigDecimal(item.optString("refund_fee")));
                    order.setOrderId(item.optString("tb_trade_parent_id"));
                    order.setOrderItemId(item.optString("tb_trade_id"));
                    int state = item.optInt("refund_status");
                    if (state == 4)
                        order.setState("维权创建");
                    else if (state == 2)
                        order.setState("维权成功");
                    else if (state == 3)
                        order.setState("维权失败");
 
                    if (!StringUtil.isNullOrEmpty(item.optString("tk_refund_suit_time")))
                        order.setWeiQuanFinishTime(new Date(TimeUtil
                                .convertToTimeTemp(item.optString("tk_refund_suit_time"), "yyyy-MM-dd HH:mm:ss")));
                    order.setWeiQuanTime(new Date(
                            TimeUtil.convertToTimeTemp(item.optString("tk_refund_time"), "yyyy-MM-dd HH:mm:ss")));
                    list.add(order);
                }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return finalResult;
    }
 
    /**
     * 新版本淘宝订单
     */
 
    /**
     * 获取淘宝会员运营订单
     * 
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<TaoBaoOrder> getTaoBaoSpecialOrderList(long startTime, long endTime, int queryType) {
        return getTaoBaoOrderList(startTime, endTime, queryType, 3);
    }
 
    /**
     * 淘宝渠道订单
     * 
     * @param startTime
     * @param endTime
     * @param queryType
     * @return
     */
    public static List<TaoBaoOrder> getTaoBaoRelationOrderList(long startTime, long endTime, int queryType) {
        return getTaoBaoOrderList(startTime, endTime, queryType, 2);
    }
 
    public static List<TaoBaoOrder> getTaoBaoCommonOrderList(long startTime, long endTime, int queryType) {
        return getTaoBaoOrderList(startTime, endTime, queryType, 1);
    }
 
    public static List<TaoBaoOrder> getTaoBaoOrderList(long startTime, long endTime, int queryType, int orderScene) {
        List<TaoBaoOrder> orderList = new ArrayList<>();
        // 跨度20分钟
        long span = (1000 * 60 * 20L);
        long jianGe = endTime - startTime;
        long page = jianGe % span == 0 ? jianGe / span : jianGe / span + 1;
        if (page == 0)
            page = 1;
        for (int i = 1; i <= page; i++) {
            long start = startTime + (i - 1) * span;
            long end = start + span;
            if (end > endTime)
                end = endTime;
            TaoBaoOrderResultDTO dto = queryNewOrder(TimeUtil.getGernalTime(start, "yyyy-MM-dd HH:mm:ss"),
                    TimeUtil.getGernalTime(end, "yyyy-MM-dd HH:mm:ss"), null, queryType, orderScene);
            if (dto != null)
                orderList.addAll(dto.getOrderList());
            while (dto!=null&&dto.isHasNext()) {
                dto = queryNewOrder(TimeUtil.getGernalTime(start, "yyyy-MM-dd HH:mm:ss"),
                        TimeUtil.getGernalTime(end, "yyyy-MM-dd HH:mm:ss"), dto.getPositionIndex(), queryType,
                        orderScene);
                if (dto != null)
                    orderList.addAll(dto.getOrderList());
            }
        }
        return orderList;
    }
 
    /**
     * 淘宝订单查询
     * 
     * @param startTime
     * @param endTime
     * @param positionIndex
     * @param queryType
     *            1:按照订单淘客创建时间查询,2:按照订单淘客付款时间查询,3:按照订单淘客结算时间查询
     * @param orderScene
     * @return
     */
    private static TaoBaoOrderResultDTO queryNewOrder(String startTime, String endTime, String positionIndex,
            int queryType, int orderScene) {
        Map<String, String> params = new HashMap<>();
        params.put("query_type", queryType + "");
        params.put("page_size", "100");
        params.put("start_time", startTime);
        params.put("end_time", endTime);
        params.put("page_no", "1");
        params.put("order_scene", orderScene + "");
        if (!StringUtil.isNullOrEmpty(positionIndex))
            params.put("position_index", positionIndex + "");
        params.put("method", "taobao.tbk.order.details.get");
        TaoKeAppInfo app = new TaoKeAppInfo();
        app.setAppKey(TaoBaoConstant.TAOBAO_AUTH_APPKEY);
        app.setAppSecret(TaoBaoConstant.TAOBAO_AUTH_APPSECRET);
        try {
            JSONObject json = TaoKeBaseUtil.baseRequest(params, app);
            if (Constant.IS_TEST)
                System.out.println(json);
            return parseTaoBaoOrderNew(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    @Deprecated
    public static List<TaoBaoOrder> queryTaoBaoOrder(OrderQuery orderQuery, String appKey, String appSecret) {
 
        Map<String, String> map = new HashMap<>();
        map.put("method", "taobao.tbk.order.get");
        map.put("fields",
                "tb_trade_parent_id,tb_trade_id,num_iid,item_title,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk_status,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,relation_id,tb_trade_parent_id,tb_trade_id,num_iid,item_title,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,special_id,click_time,relation_id,special_id");
        if (orderQuery.startTime != null)
            map.put("start_time", orderQuery.startTime);
        if (orderQuery.span != null)
            map.put("span", orderQuery.span + "");
        map.put("page_no", orderQuery.pageNo + "");
        map.put("page_size", orderQuery.pageSize + "");
 
        if (orderQuery.tkStatus != null)
            map.put("tk_status", orderQuery.tkStatus + "");
        if (orderQuery.orderQueryType != null)
            map.put("order_query_type", orderQuery.orderQueryType);
        if (orderQuery.orderScene != null)
            map.put("order_scene", orderQuery.orderScene + "");
 
        if (orderQuery.orderCountType != null)
            map.put("order_count_type", orderQuery.orderCountType + "");
 
        TaoKeAppInfo app = new TaoKeAppInfo();
        app.setAppKey(appKey);
        app.setAppSecret(appSecret);
        try {
            JSONObject json = TaoKeBaseUtil.baseRequest(map, app);
            System.out.println(json);
        } catch (TaoKeApiException e) {
            e.printStackTrace();
        }
 
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
 
        return null;
    }
}