admin
2020-04-13 dd5b15229cb15459fa7c31ccea77dac28cbfafbd
fanli/src/main/java/com/yeshi/fanli/util/jd/JDApiUtil.java
@@ -6,6 +6,7 @@
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
@@ -14,7 +15,6 @@
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.yeshi.utils.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
@@ -26,8 +26,11 @@
import com.yeshi.fanli.dto.jd.JDPingouInfo;
import com.yeshi.fanli.dto.jd.JDSearchResult;
import com.yeshi.fanli.dto.jd.JDShopInfo;
import com.yeshi.fanli.entity.bus.clazz.GoodsClass;
import com.yeshi.fanli.entity.jd.JDGoods;
import com.yeshi.fanli.entity.jd.JDOrder;
import com.yeshi.fanli.entity.jd.JDOrderItem;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.tag.PageEntity;
import com.yeshi.fanli.util.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.StringUtil;
@@ -37,44 +40,19 @@
import net.sf.json.JSONObject;
public class JDApiUtil {
   public static String APP_ID = "1774659094";
   public static String APP_KEY = "7ba8e06b7d6fde3d6bd5db4b0026ecd7";
   public static String SECRET_KEY = "fb49bc6ecac5458ba5394fc2969d7c56";
   public static String APP_ID = "1864778416";
   public static String APP_KEY = "388f5133d13a5ea290aa5c44f3ebcc00";
   public static String SECRET_KEY = "e22367fc866746d98b50d47b4c521781";
   private static String SERVER_URL = "https://router.jd.com/api";
   public static long POSITION_FANLI = 1834339426L;
   public static long POSITION_SHARE = 1834289924L;
   public static long POSITION_COUPON = 1859510742L;
   public static long POSITION_FANLI = 1869704794L;
   public static long POSITION_SHARE = 1869542990L;
   public static long POSITION_COUPON = 1869704796L;
   // 订单查询类型
   public static int ORDER_TYPE_CREATETIME = 1;// 下单时间
   public static int ORDER_TYPE_FINISHTIME = 2;// 完成时间
   public static int ORDER_TYPE_UPDATETIME = 3;// 更新时间
   private static String post(String url, Map<String, String> params) {
      String baseUrl = url;
      List<String> paramsList = new ArrayList<>();
      if (params != null)
         for (Iterator<String> its = params.keySet().iterator(); its.hasNext();) {
            String key = its.next();
            try {
               paramsList.add(key + "=" + URLEncoder.encode(params.get(key), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
            }
         }
      baseUrl += "?" + StringUtil.concat(paramsList, "&");
      HttpClient client = new HttpClient();
      PostMethod pm = new PostMethod(baseUrl);
      try {
         client.executeMethod(pm);
         String result = pm.getResponseBodyAsString();
         return new String(result.getBytes("ISO-8859-1"), "UTF-8");
      } catch (Exception e) {
         e.printStackTrace();
      }
      return null;
   }
   private static String post2(String url, Map<String, String> params) {
      String baseUrl = url;
@@ -116,22 +94,6 @@
      return StringUtil.Md5(SECRET_KEY + str + SECRET_KEY).toUpperCase();
   }
   private static String baseRequest(String method, String accessToken, JSONObject params) {
      Map<String, String> baseMap = new HashMap<String, String>();
      baseMap.put("param_json", params.toString());
      baseMap.put("app_key", APP_KEY);
      baseMap.put("method", method);
      if (accessToken != null)
         baseMap.put("access_token", accessToken);
      baseMap.put("timestamp", TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
      baseMap.put("format", "json");
      baseMap.put("v", "1.0");
      baseMap.put("sign_method", "md5");
      baseMap.put("sign", getSign(baseMap));
      String result = post(SERVER_URL, baseMap);
      return result;
   }
   private static String baseRequest2(String method, String accessToken, JSONObject params) {
      Map<String, String> baseMap = new HashMap<String, String>();
      baseMap.put("param_json", params.toString());
@@ -153,7 +115,7 @@
    * 
    * @return
    */
   public static String convertLink(String materialId, String couponUrl, String positionId, String ext1) {
   public static String convertLink1(String materialId, String couponUrl, String positionId, String ext1) {
      JSONObject json = new JSONObject();
      json.put("materialId", materialId);
      json.put("siteId", APP_ID);
@@ -168,10 +130,11 @@
      JSONObject root = new JSONObject();
      root.put("promotionCodeReq", json);
      String result = baseRequest("jd.union.open.promotion.common.get", null, root);
      String result = baseRequest2("jd.union.open.promotion.common.get", null, root);
      JSONObject resultJson = JSONObject.fromObject(result);
      result = resultJson.optJSONObject("jd_union_open_promotion_common_get_response").optString("result");
      System.out.println(result);
      if (result == null) {
         return null;
      }
@@ -180,21 +143,43 @@
      return resultJson.optJSONObject("data").optString("clickURL");
   }
   /**
    * 转链接-短连接
    *
    * @param materialId
    * @param couponUrl
    * @param positionId
    * @param ext1
    * @return
    */
   public static String convertShortLink(String materialId, String couponUrl, String positionId, String ext1) {
      String url = convertLink(materialId, couponUrl, positionId, ext1);
      if (!StringUtil.isNullOrEmpty(url)) {
         url = HttpUtil.getShortLink(url);
   public static String convertLinkWithSubUnionId(String materialId, String couponUrl, String positionId,
         String subUnionId) {
      String log = "京东转链出错:";
      try {
         JSONObject json = new JSONObject();
         json.put("materialId", materialId);
         json.put("siteId", APP_ID);
         json.put("positionId", positionId);
         if (!StringUtil.isNullOrEmpty(couponUrl))
            json.put("couponUrl", couponUrl);
         if (!StringUtil.isNullOrEmpty(subUnionId))
            json.put("subUnionId", subUnionId);
         // 1:长链, 2 :短链 ,3: 长链+短链
         json.put("chainType", 3);
         JSONObject root = new JSONObject();
         root.put("promotionCodeReq", json);
         String result = baseRequest2("jd.union.open.promotion.bysubunionid.get", null, root);
         log += json.toString() + "####" + result;
         JSONObject resultJson = JSONObject.fromObject(result);
         result = resultJson.optJSONObject("jd_union_open_promotion_bysubunionid_get_response").optString("result");
         System.out.println(result);
         if (result == null) {
            return null;
         }
         resultJson = JSONObject.fromObject(result);
         return resultJson.optJSONObject("data").optString("shortURL");
      } catch (Exception e) {
         LogHelper.error(log);
      }
      return url;
      return null;
   }
   public static JDGoods queryGoodsDetail(Long skuId) {
@@ -211,6 +196,33 @@
            return list.get(0);
      }
      return null;
   }
   public static List<JDGoods> queryGoodsDetail(List<Long> skuIdList) {
      JDFilter filter = new JDFilter();
      filter.setPageIndex(1);
      filter.setPageSize(20);
      filter.setListId(skuIdList);
      JDSearchResult searchResult = queryByKey(filter);
      if (searchResult != null) {
         List<JDGoods> list = searchResult.getGoodsList();
         if (list != null && list.size() > 0)
            return list;
      }
      return null;
   }
   /**
    * 通过商品搜索接口批量获取详情
    *
    * @param skuIds
    * @return
    */
   public static List<JDGoods> listGoodsDetail(List<Long> skuIds) {
      JDFilter filter = new JDFilter();
      filter.setListId(skuIds);
      JDSearchResult result = queryByKey(filter);
      return result.getGoodsList();
   }
   /**
@@ -318,6 +330,24 @@
      return searchResult;
   }
   /**
    * 解析京东的券信息
    *
    * @param json
    * @return
    */
   private static JDCouponInfo parseJDCouponInfo(JSONObject json) {
      JDCouponInfo couponInfo = new Gson().fromJson(json.toString(), JDCouponInfo.class);
      return couponInfo;
   }
   /**
    * 解析京东商品信息
    *
    * @param json
    * @return
    */
   private static JDGoods parseJDGoods(JSONObject json) {
      JDGoods goods = new JDGoods();
@@ -408,45 +438,37 @@
         JSONObject couponJson = JSONObject.fromObject(coupon);
         JSONArray couponArray = couponJson.optJSONArray("couponList");
         if (couponArray != null) {
            BigDecimal discount_temp = null;
            JDCouponInfo couponInfo = null;
            List<JDCouponInfo> couponInfoList = new ArrayList<>();
            for (int i = 0; i < couponArray.size(); i++) {
               boolean add = false;
               JSONObject jdcoupon = couponArray.optJSONObject(i);
               BigDecimal quota = new BigDecimal(jdcoupon.optString("quota"));
               BigDecimal sub = MoneyBigDecimalUtil.sub(price, quota);
               if (sub.compareTo(new BigDecimal(0)) < 0) {
                  continue; // 商品价格小于优惠券价格限制
               }
               // 券面额
               BigDecimal discount = new BigDecimal(jdcoupon.optString("discount"));
               if (discount_temp == null) {
                  add = true;
                  discount_temp = discount;
               } else if (discount_temp.compareTo(discount) > 0) { // 券面额大
                  add = true;
               }
               if (add) {
                  if (couponInfo == null) {
                     couponInfo = new JDCouponInfo();
                  }
                  couponInfo.setBindType(jdcoupon.optInt("bindType"));
                  couponInfo.setDiscount(new BigDecimal(jdcoupon.optString("discount")));
                  couponInfo.setQuota(new BigDecimal(jdcoupon.optString("quota")));
                  couponInfo.setPlatformType(jdcoupon.optInt("platformType"));
                  couponInfo.setGetEndTime(jdcoupon.optLong("getEndTime"));
                  couponInfo.setGetStartTime(jdcoupon.optLong("getStartTime"));
                  couponInfo.setUseEndTime(jdcoupon.optLong("useEndTime"));
                  couponInfo.setUseStartTime(jdcoupon.optLong("useStartTime"));
                  couponInfo.setLink(jdcoupon.optString("link"));
               }
               JDCouponInfo couponInfo = parseJDCouponInfo(couponArray.optJSONObject(i));
               if (couponInfo != null)
                  couponInfoList.add(couponInfo);
            }
            goods.setCouponInfo(couponInfo);
            // 根据消费条件排序
            Comparator<JDCouponInfo> cm = new Comparator<JDCouponInfo>() {
               @Override
               public int compare(JDCouponInfo o1, JDCouponInfo o2) {
                  return o1.getQuota().compareTo(o2.getQuota());
               }
            };
            Collections.sort(couponInfoList, cm);
            // if (couponInfoList.size() > 0) {
            // // 设置券信息为最接近的一个
            // for (int i = couponInfoList.size() - 1; i >= 0; i--) {
            // if
            // (couponInfoList.get(i).getQuota().compareTo(goods.getPrice())
            // <= 0) {
            // goods.setCouponInfo(couponInfoList.get(i));
            // break;
            // }
            // }
            // if (goods.getCouponInfo() == null)
            // goods.setCouponInfo(couponInfoList.get(0));
            // }
            //
            goods.setCouponInfoList(couponInfoList);
         }
      }
@@ -463,7 +485,7 @@
      List<JDGoods> list = new ArrayList<>();
      JSONObject json = new JSONObject();
      json.put("skuIds", StringUtil.concat(skuIdList, ","));
      String result = baseRequest("jd.union.open.goods.promotiongoodsinfo.query", null, json);
      String result = baseRequest2("jd.union.open.goods.promotiongoodsinfo.query", null, json);
      JSONObject resultJson = JSONObject.fromObject(result);
      resultJson = resultJson.optJSONObject("jd_union_open_goods_promotiongoodsinfo_query_response");
      if (resultJson.optInt("code") == 0) {
@@ -511,14 +533,16 @@
      if (!StringUtil.isNullOrEmpty(isFreeShipping)) {
         goods.setIsFreeShipping(Integer.parseInt(isFreeShipping));
      }
      String inOrderCount = json.optString("inOrderCount");
      if (!StringUtil.isNullOrEmpty(isFreeShipping)) {
         goods.setInOrderCount30Days(Long.parseLong(inOrderCount));
      }
      goods.setCouponInfo(null);
      goods.setGoodCommentsShare(null);
      List<String> imageList = new ArrayList<>();
      imageList.add(json.optString("imgUrl"));
      goods.setPicUrl(json.optString("imgUrl"));
      goods.setImageList(imageList);
      goods.setInOrderCount30Days(0L);
      goods.setIsHot(null);
      goods.setMaterialUrl(json.optString("materialUrl"));
      goods.setOwner(null);
@@ -549,6 +573,7 @@
      jsonDTO.put("goodsReq", json);
      String result = baseRequest2("jd.union.open.goods.jingfen.query", null, jsonDTO);
      LogHelper.test(result);
      System.out.println(result);
      JSONObject resultJson = JSONObject.fromObject(result);
      resultJson = resultJson.optJSONObject("jd_union_open_goods_jingfen_query_response");
@@ -577,12 +602,12 @@
      return searchResult;
   }
   public static JDSearchResult getGoodsClass() {
   public static List<GoodsClass> getGoodsClass(int parentId, int grade) {
      JDSearchResult searchResult = new JDSearchResult();
      List<JDGoods> list = new ArrayList<>();
      List<GoodsClass> list = new ArrayList<>();
      JSONObject json = new JSONObject();
      json.put("parentId", 0);
      json.put("grade", 0);
      json.put("parentId", parentId);
      json.put("grade", grade);
      JSONObject jsonDTO = new JSONObject();
      jsonDTO.put("req", json);
@@ -590,7 +615,7 @@
      String result = baseRequest2("jd.union.open.category.goods.get", null, jsonDTO);
      System.out.println(result);
      JSONObject resultJson = JSONObject.fromObject(result);
      resultJson = resultJson.optJSONObject("jd_union_open_goods_jingfen_query_response");
      resultJson = resultJson.optJSONObject("jd_union_open_category_goods_get_response");
      if (resultJson.optInt("code") == 0) {
         result = resultJson.optString("result");
         resultJson = JSONObject.fromObject(result);
@@ -599,9 +624,11 @@
            JSONArray array = resultJson.optJSONArray("data");
            if (array != null) {
               for (int i = 0; i < array.size(); i++) {
                  JDGoods goods = parseJDGoods(array.optJSONObject(i));
                  if (goods != null)
                     list.add(goods);
                  GoodsClass gc = new GoodsClass();
                  JSONObject item = array.optJSONObject(i);
                  gc.setName(item.optString("name"));
                  gc.setId(item.optLong("id"));
                  list.add(gc);
               }
            }
         }
@@ -609,11 +636,9 @@
         long totalCount = resultJson.optLong("totalCount");
         PageEntity pageEntity = new PageEntity();
         pageEntity.setTotalCount(totalCount);
         searchResult.setPageEntity(pageEntity);
      }
      searchResult.setGoodsList(list);
      return searchResult;
      return list;
   }
   public static JDGoods getGoodsDetail(Long skuId) {
@@ -645,30 +670,46 @@
      json.put("orderReq", orderReq);
      String result = baseRequest2("jd.union.open.order.query", null, json);
      try {
         System.out.println(new String(result.getBytes("GBK"), "UTF-8"));
         System.out.println(new String(result.getBytes("ISO-8859-1"), "UTF-8"));
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
      System.out.println(result);
      JSONObject root = JSONObject.fromObject(result).optJSONObject("jd_union_open_order_query_response");
      if (root.optInt("code") == 0) {
         boolean hasMore = root.optBoolean("hasMore");
         root = JSONObject.fromObject(root.optString("result"));
         if (root.optInt("code") == 200) {
         if (root.optInt("code") == 200 && root.optJSONArray("data") != null) {
            String date = root.optJSONArray("data").toString();
            Type typeToken = new TypeToken<List<JDOrder>>() {
            }.getType();
            List<JDOrder> orderList = new Gson().fromJson(date, typeToken);
            if (orderList != null)
               for (JDOrder order : orderList) {
                  Map<Long, List<JDOrderItem>> map = new HashMap<>();
                  for (int i = 0; i < order.getOrderItemList().size(); i++) {
                     JDOrderItem orderItem = order.getOrderItemList().get(i);
                     if (map.get(orderItem.getSkuId()) == null)
                        map.put(orderItem.getSkuId(), new ArrayList<>());
                     map.get(orderItem.getSkuId()).add(orderItem);
                     order.getOrderItemList().get(i)
                           .setTradeId(order.getOrderId() + "-" + order.getOrderItemList().get(i).getSkuId());
                     order.getOrderItemList().get(i).setOrderId(order.getOrderId());
                     order.getOrderItemList().get(i).setOrderBy(i + 1);
                  }
                  // 查询商品ID相同的子订单
                  for (Iterator<Long> its = map.keySet().iterator(); its.hasNext();) {
                     Long skuId = its.next();
                     if (map.get(skuId).size() > 1) {
                        int skuOrderBy = 1;
                        for (int i = 0; i < order.getOrderItemList().size(); i++) {
                           JDOrderItem orderItem = order.getOrderItemList().get(i);
                           if (orderItem.getSkuId().longValue() == skuId) {
                              order.getOrderItemList().get(i).setTradeId(order.getOrderId() + "-"
                                    + order.getOrderItemList().get(i).getSkuId() + "-" + skuOrderBy++);
                           }
                        }
                     }
                  }
               }
            return new JDOrderResult(hasMore, orderList);
         }
@@ -676,4 +717,14 @@
      return null;
   }
   public static void test() {
      JSONObject json = new JSONObject();
      json.put("materialId", "https://item.jd.com/32376790478.html");
      json.put("ext1", "437032");
      JSONObject root = new JSONObject();
      root.put("promotionCodeReq", json);
      String result = baseRequest2("jd.union.open.promotion.bysubunionid.get", null, root);
      System.out.println(result);
   }
}