admin
2025-02-25 30d8e227e8d823b6c38c3b9c90ac2df03b63befe
fanli/src/main/java/com/yeshi/fanli/util/pinduoduo/PinDuoDuoApiUtil.java
@@ -1,383 +1,743 @@
package com.yeshi.fanli.util.pinduoduo;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.yeshi.utils.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.yeshi.fanli.dto.pdd.PDDGoodsDetail;
import com.yeshi.fanli.dto.pdd.PDDGoodsResult;
import com.yeshi.fanli.dto.pdd.PDDOrderResult;
import com.yeshi.fanli.dto.pdd.PDDSearchFilter;
import com.yeshi.fanli.entity.pdd.PDDOrder;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class PinDuoDuoApiUtil {
   public final static String PID_FANLI = "8590899_72067894";
   public final static String PID_SHARE = "8590899_72067895";
   public final static String PID_COUPON = "8590899_102657575";
   private final static String CLIENT_ID = "9f6ee5ebd3b94c2080c4d51c2427e9fa";
   private final static String CLIENT_SECRET = "95e1f1904385664bf4b87d4b34de12f9f31c505d";
   private static String getSign(Map<String, String> map) {
      List<String> keyList = new ArrayList<>();
      Iterator<String> keys = map.keySet().iterator();
      while (keys.hasNext()) {
         String key = keys.next();
         keyList.add(key);
      }
      Collections.sort(keyList);
      String org = "";
      for (String key : keyList) {
         org += key + map.get(key);
      }
      return StringUtil.Md5(CLIENT_SECRET + org + CLIENT_SECRET).toUpperCase();
   }
   private static String baseRequest(Map<String, String> map) {
      map.put("client_id", CLIENT_ID);
      map.put("timestamp", System.currentTimeMillis() / 1000 + "");
      map.put("sign", getSign(map));
      Iterator<String> keys = map.keySet().iterator();
      String url = "https://gw-api.pinduoduo.com/api/router?";
      while (keys.hasNext()) {
         String key = keys.next();
         try {
            url += key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&";
         } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
         }
      }
      if (url.endsWith("&"))
         url = url.substring(0, url.length() - 1);
      return HttpUtil.postSimple(url);
   }
   /**
    * 多多进宝商品查询
    * @param sf
    * @return
    */
   public static PDDGoodsResult searchGoods(PDDSearchFilter sf) {
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.ddk.goods.search");
      if (sf.getOptId() != null)
         map.put("opt_id", sf.getOptId() + "");
      if (sf.getPage() != null)
         map.put("page", sf.getPage() + "");
      if (sf.getPageSize() != null)
         map.put("page_size", sf.getPageSize() + "");
      if (sf.getSortType() != null)
         map.put("sort_type", sf.getSortType() + "");
      if (sf.getHasCoupon() != null)
         map.put("with_coupon", sf.getHasCoupon() + "");
      if (sf.getIsBrand() != null)
         map.put("is_brand_goods", sf.getIsBrand() + "");
      if (sf.getCatId() != null)
         map.put("cat_id", sf.getCatId() + "");
      if (sf.getKw() != null)
         map.put("keyword", sf.getKw());
      if (sf.getGoodsIdList() != null)
         map.put("goods_id_list", "[" + StringUtil.concat(sf.getGoodsIdList(), ",") + "]");
      map.put("pid", PID_FANLI);
      String result = baseRequest(map);
      JSONObject json = JSONObject.fromObject(result);
      JSONObject root = json.optJSONObject("goods_search_response");
      if (root == null) {
         return null;
      }
      JSONArray array = root.optJSONArray("goods_list");
      if (array == null) {
         return null;
      }
      Type type = new TypeToken<List<PDDGoodsDetail>>() {
      }.getType();
      Gson gson = new GsonBuilder().disableHtmlEscaping().create();
      List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
      int totalCount = root.optInt("total_count");
      return new PDDGoodsResult(totalCount, goodsList);
   }
   /**
    *  运营频道商品查询API
    * @param page
    * @param pageSize
    * @param channelType  频道类型;0, "1.9包邮", 1, "今日爆款", 2, "品牌清仓", 非必填 ,默认是1
    * @return
    */
   public static PDDGoodsResult searchByChannelType(Integer page, Integer pageSize, String channelType) {
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.ddk.goods.recommend.get");
      map.put("offset", (page == null?0:page) + "");
      map.put("offset", (pageSize == null?Constant.PAGE_SIZE:pageSize) + "");
      if (channelType != null)
         map.put("channel_type", channelType);
      map.put("pid", PID_FANLI);
      String result = baseRequest(map);
      JSONObject json = JSONObject.fromObject(result);
      JSONObject root = json.optJSONObject("goods_basic_detail_response");
      if (root == null) {
         return null;
      }
      JSONArray array = root.optJSONArray("list");
      if (array == null) {
         return null;
      }
      Type type = new TypeToken<List<PDDGoodsDetail>>() {
      }.getType();
      Gson gson = new GsonBuilder().disableHtmlEscaping().create();
      List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
      int totalCount = root.optInt("total");
      return new PDDGoodsResult(totalCount, goodsList);
   }
   public static void getGoodsClass() {
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.goods.cats.get");
      map.put("parent_cat_id", "0");
      String result = baseRequest(map);
      JSONObject json = JSONObject.fromObject(result);
      JSONObject root = json.optJSONObject("goods_cats_get_response");
      JSONArray array = root.optJSONArray("goods_cats_list");
   }
   public static void getThemes(Integer page, Integer pageSize) {
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.ddk.theme.list.get");
      map.put("page", page + "");
      map.put("page_size", pageSize  + "");
      String result = baseRequest(map);
      JSONObject json = JSONObject.fromObject(result);
      JSONObject root = json.optJSONObject("theme_list_get_response");
      JSONArray array = root.optJSONArray("theme_list");
      for (int i = 0; i < array.size(); i++) {
         System.out.println(array.optJSONObject(i).optString("id"));
         System.out.println(array.optJSONObject(i).optString("name"));
         System.out.println(array.optJSONObject(i).optString("image_url"));
         System.out.println(array.optJSONObject(i).optString("goods_num"));
         System.out.println("-------------------------------------------");
      }
      System.out.println(root.optLong("total"));
   }
   public static void getGoodsOpt() {
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.goods.opt.get");
      map.put("parent_opt_id", "0");
      String result = baseRequest(map);
      JSONObject json = JSONObject.fromObject(result);
      JSONObject root = json.optJSONObject("goods_opt_get_response");
      JSONArray array = root.optJSONArray("goods_opt_list");
   }
   /**
    * 多多客获取爆款排行商品接口
    * @param pid  推广位id    (非必填)
    * @param page 从多少位置开始请求;默认值 : 0     (非必填)
    * @param pageSize 请求数量;默认值 :20    (非必填)
    * @param sortType 1-实时热销榜;2-实时收益榜    (非必填)
    * @return
    */
   public static PDDGoodsResult getTopList(String pid, Integer page, Integer pageSize, Integer sortType) {
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.ddk.top.goods.list.query");
      map.put("offset", (page == null? 0: (page-1) * Constant.PAGE_SIZE) +"");
      map.put("limit", (pageSize == null? Constant.PAGE_SIZE : pageSize) +"");
      if (!StringUtil.isNullOrEmpty(pid))
         map.put("p_id", pid + "");
      if (sortType != null)
         map.put("sort_type", sortType + "");
      String result = baseRequest(map);
      JSONObject json = JSONObject.fromObject(result);
      JSONObject root = json.optJSONObject("top_goods_list_get_response");
      if (root == null) {
         return null;
      }
      JSONArray array = root.optJSONArray("list");
      if (array == null) {
         return null;
      }
      Type type = new TypeToken<List<PDDGoodsDetail>>() {}.getType();
      Gson gson = new GsonBuilder().disableHtmlEscaping().create();
      List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
      //int totalCount = root.optInt("total");
      int totalCount = 400; // 默认设置成400
      return new PDDGoodsResult(totalCount, goodsList);
   }
   /**
    * 商品转链
    *
    * @param goodsId
    * @param pid
    * @param customParams
    * @return
    */
   public static String convert(Long goodsId, String pid, String customParams) {
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.ddk.goods.promotion.url.generate");
      map.put("p_id", pid);
      map.put("multi_group", "true");
      map.put("generate_weapp_webview", "true");
//      map.put("generate_weiboapp_webview", "true");
      JSONArray array = new JSONArray();
      array.add(goodsId);
      map.put("goods_id_list", array.toString());
      if (!StringUtil.isNullOrEmpty(customParams)) {
         map.put("custom_parameters", customParams);
      }
      String result = baseRequest(map);
      JSONObject root = JSONObject.fromObject(result);
      JSONObject json = root.optJSONObject("goods_promotion_url_generate_response");
      if (json == null) {
         return null;
      }
      JSONArray resultArray = json.optJSONArray("goods_promotion_url_list");
      if (resultArray != null && resultArray.size() > 0)
         return resultArray.optJSONObject(0).optString("short_url");
      return null;
   }
   public static void createPid() {
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.ddk.goods.pid.generate");
      map.put("number", "2");
      JSONArray array = new JSONArray();
      array.add("返利PID");
      array.add("分享PID");
      map.put("p_id_name_list", array.toString());
      String result = baseRequest(map);
      System.out.println(result);
   }
   /**
    * 获取订单
    *
    * @param page
    *            -页码
    * @param pageSize-每页数量
    * @param startTime-开始时间
    * @param endTime-结束时间
    *            与开始时间不得大于24小时
    * @return
    */
   public static PDDOrderResult getOrders(int page, int pageSize, long startTime, long endTime) {
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.ddk.order.list.increment.get");
      map.put("start_update_time", startTime / 1000 + "");
      map.put("end_update_time", endTime / 1000 + "");
      map.put("page", page + "");
      map.put("page_size", pageSize + "");
      String result = baseRequest(map);
      JSONObject json = JSONObject.fromObject(result);
      JSONObject root = json.optJSONObject("order_list_get_response");
      if (root != null) {
         int totalCount = root.optInt("total_count");
         JSONArray array = root.optJSONArray("order_list");
         Type type = new TypeToken<List<PDDOrder>>() {
         }.getType();
         List<PDDOrder> orderList = new Gson().fromJson(array.toString(), type);
         return new PDDOrderResult(totalCount, orderList);
      }
      return null;
   }
   /**
    * 获取商品详情
    *
    * @param goodsId
    */
   public static PDDGoodsDetail getGoodsDetail(Long goodsId) {
      JSONArray array = new JSONArray();
      array.add(goodsId);
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.ddk.goods.detail");
      map.put("goods_id_list", array.toString());
      String result = baseRequest(map);
      JSONObject resultJson = JSONObject.fromObject(result);
      JSONObject root = resultJson.optJSONObject("goods_detail_response");
      if (root == null) {
         return null;
      }
      JSONArray resultArray = root.optJSONArray("goods_details");
      if (resultArray == null) {
         return null;
      }
      Type type = new TypeToken<List<PDDGoodsDetail>>() {
      }.getType();
      List<PDDGoodsDetail> goodsList = new Gson().fromJson(resultArray.toString(), type);
      if (goodsList != null && goodsList.size() > 0)
         return goodsList.get(0);
      return null;
   }
   /**
    * 获取商品详情
    *
    * @param goodsId
    */
   public static String createGenerate(Long goodsId) {
      JSONArray array = new JSONArray();
      array.add(goodsId);
      Map<String, String> map = new HashMap<>();
      map.put("type", "pdd.ddk.phrase.generate");
      map.put("goods_id_list", array.toString());
      map.put("p_id", PID_FANLI);
      String result = baseRequest(map);
      JSONObject resultJson = JSONObject.fromObject(result);
      System.out.println(result);
      JSONObject root = resultJson.optJSONObject("ddk_phrase_generate_response");
      if (root != null) {
         array = root.optJSONArray("promotion_phrase_list");
         JSONObject phraseObject = JSONObject.fromObject( array.get(0));
         return phraseObject.optString("phrase");
      }
      return null;
   }
}
package com.yeshi.fanli.util.pinduoduo;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.*;
import com.google.gson.JsonObject;
import com.yeshi.fanli.exception.pdd.PDDApiException;
import com.yeshi.fanli.vo.pdd.PDDConvertLinkResultVO;
import org.yeshi.utils.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.yeshi.fanli.dto.pdd.PDDGoodsDetail;
import com.yeshi.fanli.dto.pdd.PDDGoodsResult;
import com.yeshi.fanli.dto.pdd.PDDOrderResult;
import com.yeshi.fanli.dto.pdd.PDDPromotionUrl;
import com.yeshi.fanli.dto.pdd.PDDSearchFilter;
import com.yeshi.fanli.dto.pdd.PDDShopDetail;
import com.yeshi.fanli.dto.pdd.PDDShopResult;
import com.yeshi.fanli.entity.pdd.PDDOrder;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.StringUtil;
import org.yeshi.utils.TimeUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class PinDuoDuoApiUtil {
//    public final static String PID_FANLI = "8590899_72067894";
//    public final static String PID_SHARE = "8590899_72067895";
//    public final static String PID_COUPON = "8590899_102657575";
    public final static String PID_DEFAULT = "8590899_72067894";
    private final static String CLIENT_ID = "9f6ee5ebd3b94c2080c4d51c2427e9fa";
    private final static String CLIENT_SECRET = "95e1f1904385664bf4b87d4b34de12f9f31c505d";
    private static String getSign(Map<String, String> map) {
        List<String> keyList = new ArrayList<>();
        Iterator<String> keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            keyList.add(key);
        }
        Collections.sort(keyList);
        String org = "";
        for (String key : keyList) {
            org += key + map.get(key);
        }
        return StringUtil.Md5(CLIENT_SECRET + org + CLIENT_SECRET).toUpperCase();
    }
    private static String getFormatCustomParameters(String customParameters){
        customParameters=customParameters.replace("_","");
        JSONObject data=new JSONObject();
        data.put("uid",customParameters);
        String custom = data.toString();
        System.out.println("自定义参数:"+custom);
        return custom;
    }
    private static String baseRequest(Map<String, String> map) {
        map.put("client_id", CLIENT_ID);
        map.put("timestamp", System.currentTimeMillis() / 1000 + "");
        map.put("sign", getSign(map));
        Iterator<String> keys = map.keySet().iterator();
        String url = "https://gw-api.pinduoduo.com/api/router?";
        while (keys.hasNext()) {
            String key = keys.next();
            try {
                url += key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (url.endsWith("&"))
            url = url.substring(0, url.length() - 1);
        return HttpUtil.postSimple(url);
    }
    /**
     * 多多进宝商品查询
     *
     * @param sf
     * @return
     */
    public static PDDGoodsResult searchGoods(PDDSearchFilter sf, String customerParamters) throws PDDApiException {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.search");
        map.put("custom_parameters", getFormatCustomParameters(customerParamters));
        if (sf.getOptId() != null)
            map.put("opt_id", sf.getOptId() + "");
        if (sf.getPage() != null)
            map.put("page", sf.getPage() + "");
        if (sf.getPageSize() != null)
            map.put("page_size", sf.getPageSize() + "");
        if (sf.getSortType() != null)
            map.put("sort_type", sf.getSortType() + "");
        if (sf.getHasCoupon() != null)
            map.put("with_coupon", sf.getHasCoupon() + "");
        if (sf.getIsBrand() != null)
            map.put("is_brand_goods", sf.getIsBrand() + "");
        if (sf.getCatId() != null)
            map.put("cat_id", sf.getCatId() + "");
        if (sf.getKw() != null)
            map.put("keyword", sf.getKw());
        if (sf.getGoodsIdList() != null)
            map.put("goods_id_list", "[" + StringUtil.concat(sf.getGoodsIdList(), ",") + "]");
        if (sf.getMerchantType() != null)
            map.put("merchant_type", sf.getMerchantType() + "");
        if (sf.getRangeList() != null && sf.getRangeList().size() > 0) {
            map.put("range_list", gson.toJson(sf.getRangeList()).toString());
        }
        map.put("pid", PID_DEFAULT);
        String result = baseRequest(map);
        System.out.println(result);
        JSONObject json = JSONObject.fromObject(result);
        if (json.optJSONObject("error_response") != null) {
            int errorCode = json.optJSONObject("error_response").optInt("sub_code");
             throw new PDDApiException(errorCode, json.optJSONObject("error_response").optString("sub_msg"));
        }
        JSONObject root = json.optJSONObject("goods_search_response");
        if (root == null) {
            return null;
        }
        JSONArray array = root.optJSONArray("goods_list");
        if (array == null) {
            return null;
        }
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
        int totalCount = root.optInt("total_count");
        return new PDDGoodsResult(totalCount, goodsList);
    }
    public static List<PDDGoodsDetail> listGoodsDetail(List<Long> goodsIds) {
        PDDSearchFilter filter = new PDDSearchFilter();
        Long[] ids = new Long[goodsIds.size()];
        goodsIds.toArray(ids);
        filter.setGoodsIdList(ids);
        PDDGoodsResult result = null;
        try {
            result = searchGoods(filter, Constant.PDD_SEARCH_CUSTOMER_PARAMS);
        } catch (PDDApiException e) {
            e.printStackTrace();
        }
        if (result != null)
            return result.getGoodsList();
        return null;
    }
    /**
     * 运营频道商品查询API
     *
     * @param page
     * @param pageSize
     * @param channelType 频道类型;0, "1.9包邮", 1, "今日爆款", 2, "品牌清仓", 非必填 ,默认是1
     * @return
     */
    public static PDDGoodsResult searchByChannelType(Integer page, Integer pageSize, String channelType, Integer[] activityTags) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.recommend.get");
        map.put("offset", (page == null ? 0 : page) + "");
        map.put("offset", (pageSize == null ? Constant.PAGE_SIZE : pageSize) + "");
        if (channelType != null)
            map.put("channel_type", channelType);
        if (activityTags != null) {
            map.put("activity_tags", JSONArray.fromObject(Arrays.asList(activityTags)).toString());
        }
        map.put("pid", PID_DEFAULT);
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_basic_detail_response");
        if (root == null) {
            return null;
        }
        JSONArray array = root.optJSONArray("list");
        if (array == null) {
            return null;
        }
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
        int totalCount = root.optInt("total");
        return new PDDGoodsResult(totalCount, goodsList);
    }
    public static void getGoodsClass() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.goods.cats.get");
        map.put("parent_cat_id", "0");
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_cats_get_response");
        JSONArray array = root.optJSONArray("goods_cats_list");
    }
    public static void getThemes(Integer page, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.theme.list.get");
        map.put("page", page + "");
        map.put("page_size", pageSize + "");
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("theme_list_get_response");
        JSONArray array = root.optJSONArray("theme_list");
        for (int i = 0; i < array.size(); i++) {
            System.out.println(array.optJSONObject(i).optString("id"));
            System.out.println(array.optJSONObject(i).optString("name"));
            System.out.println(array.optJSONObject(i).optString("image_url"));
            System.out.println(array.optJSONObject(i).optString("goods_num"));
            System.out.println("-------------------------------------------");
        }
        System.out.println(root.optLong("total"));
    }
    public static void getGoodsOpt() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.goods.opt.get");
        map.put("parent_opt_id", "0");
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("goods_opt_get_response");
        JSONArray array = root.optJSONArray("goods_opt_list");
    }
    /**
     * 多多客获取爆款排行商品接口
     *
     * @param pid      推广位id (非必填)
     * @param page     从多少位置开始请求;默认值 : 0 (非必填)
     * @param pageSize 请求数量;默认值 :20 (非必填)
     * @param sortType 1-实时热销榜;2-实时收益榜 (非必填)
     * @return
     */
    public static PDDGoodsResult getTopList(String pid, Integer page, Integer pageSize, Integer sortType) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.top.goods.list.query");
        map.put("offset", (page == null ? 0 : (page - 1) * Constant.PAGE_SIZE) + "");
        map.put("limit", (pageSize == null ? Constant.PAGE_SIZE : pageSize) + "");
        if (!StringUtil.isNullOrEmpty(pid))
            map.put("p_id", pid + "");
        if (sortType != null)
            map.put("sort_type", sortType + "");
        String result = baseRequest(map);
        JSONObject json = JSONObject.fromObject(result);
        JSONObject root = json.optJSONObject("top_goods_list_get_response");
        if (root == null) {
            return null;
        }
        JSONArray array = root.optJSONArray("list");
        if (array == null) {
            return null;
        }
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        List<PDDGoodsDetail> goodsList = gson.fromJson(array.toString(), type);
        // int totalCount = root.optInt("total");
        int totalCount = 400; // 默认设置成400
        return new PDDGoodsResult(totalCount, goodsList);
    }
    /**
     * 商品转链
     *
     * @param goodsSign
     * @param pid
     * @param customParams
     * @return
     */
    public static PDDConvertLinkResultVO convert(String goodsSign, String pid, String customParams, boolean withAuthLink) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.promotion.url.generate");
        map.put("p_id", pid);
        map.put("multi_group", "true");
        map.put("generate_schema_url","true");
        map.put("generate_weapp_webview", "true");
        map.put("generate_we_app", "true");
        // map.put("generate_weiboapp_webview", "true");
        JSONArray array = new JSONArray();
        array.add(goodsSign);
        map.put("goods_sign_list", array.toString());
        if (!StringUtil.isNullOrEmpty(customParams)) {
            map.put("custom_parameters", getFormatCustomParameters(customParams));
        }
        //是否生成带授权的单品链接
        if (withAuthLink)
            map.put("generate_authority_url", true + "");
        String result = baseRequest(map);
        System.out.println(result);
        JSONObject root = JSONObject.fromObject(result);
        JSONObject json = root.optJSONObject("goods_promotion_url_generate_response");
        if (json == null) {
            return null;
        }
        JSONArray resultArray = json.optJSONArray("goods_promotion_url_list");
        if (resultArray != null && resultArray.size() > 0) {
            Type type = new TypeToken<PDDConvertLinkResultVO>() {
            }.getType();
            Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            return gson.fromJson(resultArray.optJSONObject(0).toString(), type);
        }
        return null;
    }
    /**
     * 活动转链 https://open.pinduoduo.com/application/document/api?id=pdd.ddk.resource.url.gen
     *
     * @param resourceType
     * @param url
     * @param pid
     * @param customParams
     * @return
     */
    public static PDDConvertLinkResultVO convertActivity(String resourceType, String url, String pid, String customParams) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.resource.url.gen");
        map.put("generate_schema_url","true");
        map.put("pid", pid);
        if (customParams != null) {
            map.put("custom_parameters", getFormatCustomParameters(customParams));
        }
        map.put("resource_type", resourceType);
        if (url != null) {
            map.put("url", url);
        }
        String result = baseRequest(map);
        JSONObject root = JSONObject.fromObject(result);
        JSONObject json = root.optJSONObject("resource_url_response");
        if (json == null) {
            return null;
        }
        JSONObject urlJSON = json.optJSONObject("single_url_list");
        PDDConvertLinkResultVO vo = null;
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        if (urlJSON != null) {
            vo = gson.fromJson(urlJSON.toString(), PDDConvertLinkResultVO.class);
        }
        JSONObject weAppInfo = json.optJSONObject("we_app_info");
        if (weAppInfo != null && vo != null) {
            PDDConvertLinkResultVO.WeAppInfoBean weAppInfoBean = gson.fromJson(weAppInfo.toString(), PDDConvertLinkResultVO.WeAppInfoBean.class);
            vo.setWe_app_info(weAppInfoBean);
        }
        return vo;
    }
    /**
     * 频道推广(https://open.pinduoduo.com/application/document/api?id=pdd.ddk.cms.prom.url.generate)
     *
     * @param channelType
     * @param pid
     * @param customParams
     * @return
     */
    public static PDDConvertLinkResultVO convertChannel(String channelType, String pid, String customParams) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.cms.prom.url.generate");
        map.put("p_id_list", "[\"" + pid + "\"]");
        if (customParams != null) {
            map.put("custom_parameters", getFormatCustomParameters(customParams));
        }
        map.put("channel_type", channelType);
        map.put("generate_mobile", true+"");
        map.put("generate_short_url", true+"");
        map.put("generate_we_app", true+"");
        String result = baseRequest(map);
        System.out.println(result);
        JSONObject root = JSONObject.fromObject(result);
        JSONObject json = root.optJSONObject("cms_promotion_url_generate_response");
        if (json == null) {
            return null;
        }
        JSONObject urlJSON = json.optJSONArray("url_list").optJSONObject(0);
        PDDConvertLinkResultVO vo = null;
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        if (urlJSON != null) {
            vo = gson.fromJson(urlJSON.toString(), PDDConvertLinkResultVO.class);
        }
        return vo;
    }
    /**
     * 微信小程序转链 @Title: convertWXMP @Description: @param goodsId @param
     * pid @param customParams @return PDDPromotionUrl 返回类型 @throws
     */
    public static String convertWXMP(String goodsId, String pid, String customParams) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.promotion.url.generate");
        map.put("p_id", pid);
        map.put("multi_group", "true");
        map.put("generate_we_app", "true");
        JSONArray array = new JSONArray();
        array.add(goodsId);
        map.put("goods_id_list", array.toString());
        if (!StringUtil.isNullOrEmpty(customParams)) {
            map.put("custom_parameters", getFormatCustomParameters(customParams));
        }
        String result = baseRequest(map);
        JSONObject root = JSONObject.fromObject(result);
        JSONObject json = root.optJSONObject("goods_promotion_url_generate_response");
        if (json == null) {
            return null;
        }
        JSONArray resultArray = json.optJSONArray("goods_promotion_url_list");
        if (resultArray != null && resultArray.size() > 0) {
            JSONObject weApp = resultArray.optJSONObject(0).optJSONObject("we_app_info");
            if (weApp != null)
                return weApp.optString("page_path");
        }
        return null;
    }
    /**
     * 商品转链
     *
     * @param goodsSign
     * @param pid
     * @param customParams
     * @return
     */
    public static String getPromotionUrl(String goodsSign, String pid, String customParams) {
        PDDConvertLinkResultVO promotion = convert(goodsSign, pid, customParams, false);
        if (promotion != null) {
            return promotion.getShort_url();
        }
        return null;
    }
    public static void createPid() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.pid.generate");
        map.put("number", "2");
        JSONArray array = new JSONArray();
        array.add("返利PID");
        array.add("分享PID");
        map.put("p_id_name_list", array.toString());
        String result = baseRequest(map);
        System.out.println(result);
    }
    /**
     * 获取订单
     *
     * @param page           -页码
     * @param pageSize-每页数量
     * @param startTime-开始时间
     * @param endTime-结束时间   与开始时间不得大于24小时
     * @return
     */
    public static PDDOrderResult getOrdersList(int page, int pageSize, long startTime, long endTime) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.order.list.increment.get");
        map.put("start_update_time", startTime / 1000 + "");
        map.put("end_update_time", endTime / 1000 + "");
        map.put("page", page + "");
        map.put("page_size", pageSize + "");
        String result = baseRequest(map);
        System.out.println(result);
        com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(result);
        com.alibaba.fastjson.JSONObject root = json.getJSONObject("order_list_get_response");
        if (root != null) {
            int totalCount = root.getInteger("total_count");
            com.alibaba.fastjson.JSONArray array = root.getJSONArray("order_list");
            Type type=new TypeToken<List<PDDOrder>>(){}.getType();
            List<PDDOrder> orderList = new Gson().fromJson( array.toJSONString(), type);
            // 处理custom_params
            for(PDDOrder order:orderList){
                String params=order.getCustomParameters();
                if(params.contains("{")) {
                    JSONObject jsonp = JSONObject.fromObject(params);
                    order.setCustomParameters(jsonp.optString("uid"));
                }
            }
            return new PDDOrderResult(totalCount, orderList);
        }
        return null;
    }
    public static PDDOrder getOrderDetail(String orderSn) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.order.detail.get");
        map.put("order_sn", orderSn);
        String result = baseRequest(map);
        com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(result);
        com.alibaba.fastjson.JSONObject root = json.getJSONObject("order_detail_response");
        if (root != null) {
            PDDOrder order = new Gson().fromJson(root.toString(), PDDOrder.class);
            String params=order.getCustomParameters();
            if(params.contains("{")) {
                JSONObject jsonp = JSONObject.fromObject(params);
                order.setCustomParameters(jsonp.optString("uid"));
            }
            return order;
        }
        return null;
    }
    /**
     * 获取商品详情
     *
     * @param goodsSign
     */
    public static PDDGoodsDetail getGoodsDetail(String goodsSign) {
        try {
            return getGoodsDetail(goodsSign, PID_DEFAULT, "437031");
        } catch (PDDApiException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static PDDGoodsDetail getGoodsDetail(String goodsSign, String pid, String customParameters) throws PDDApiException {
//        String goodsSign = goodsResult.getGoodsList().get(0).getGoodsSign();
        JSONArray array = new JSONArray();
        array.add(goodsSign);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.goods.detail");
        map.put("goods_sign", goodsSign);
        if (!StringUtil.isNullOrEmpty(pid)) {
            map.put("pid", pid);
        }
        if (!StringUtil.isNullOrEmpty(customParameters)) {
            map.put("custom_parameters", getFormatCustomParameters(customParameters));
        }
        String result = baseRequest(map);
        System.out.println(result);
        JSONObject resultJson = JSONObject.fromObject(result);
        JSONObject root = resultJson.optJSONObject("goods_detail_response");
        if (root == null) {
            return null;
        }
        JSONArray resultArray = root.optJSONArray("goods_details");
        if (resultArray == null) {
            return null;
        }
        Type type = new TypeToken<List<PDDGoodsDetail>>() {
        }.getType();
        List<PDDGoodsDetail> goodsList = new Gson().fromJson(resultArray.toString(), type);
        if (goodsList != null && goodsList.size() > 0)
            return goodsList.get(0);
        return null;
    }
    /**
     * 获取商品详情
     *
     * @param goodsId
     */
    public static String createGenerate(Long goodsId) {
        JSONArray array = new JSONArray();
        array.add(goodsId);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.phrase.generate");
        map.put("goods_id_list", array.toString());
        map.put("p_id", PID_DEFAULT);
        String result = baseRequest(map);
        JSONObject resultJson = JSONObject.fromObject(result);
        JSONObject root = resultJson.optJSONObject("ddk_phrase_generate_response");
        if (root != null) {
            array = root.optJSONArray("promotion_phrase_list");
            JSONObject phraseObject = JSONObject.fromObject(array.get(0));
            return phraseObject.optString("phrase");
        }
        return null;
    }
    public static Date getSystemTime() {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("type", "pdd.time.get");
            String result = baseRequest(map);
            String time = JSONObject.fromObject(result).optJSONObject("time_get_response").optString("time");
            return new Date(TimeUtil.convertToTimeTemp(time, "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
        }
        return null;
    }
    /**
     * @param page
     * @param catId
     * @return
     */
    public static PDDShopResult getShopList(Integer page, Long catId) {
        JSONArray arrayType = new JSONArray();
        arrayType.add(3);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.merchant.list.get");
        if (catId != null)
            map.put("cat_id", catId + "");
        if (page != null)
            map.put("page_number", page + "");
        if (page != null)
            map.put("page_number", page + "");
        map.put("merchant_type_list", arrayType.toString());
        String result = baseRequest(map);
        JSONObject resultJson = JSONObject.fromObject(result);
        JSONObject root = resultJson.optJSONObject("merchant_list_response");
        if (root != null) {
            int totalCount = root.optInt("total");
            JSONArray array = root.optJSONArray("mall_search_info_vo_list");
            Type type = new TypeToken<List<PDDShopDetail>>() {
            }.getType();
            List<PDDShopDetail> listShop = new Gson().fromJson(array.toString(), type);
            return new PDDShopResult(totalCount, listShop);
        }
        return null;
    }
    /**
     * 是否授权
     *
     * @param pid
     * @param customParameters
     * @return
     */
    public static boolean isAuth(String pid, String customParameters) {
//        customParameters=customParameters.replace("_","");
        System.out.println("是否授权:"+pid+"-"+customParameters);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.member.authority.query");
        map.put("pid", pid);
        map.put("custom_parameters", getFormatCustomParameters(customParameters));
        String result = baseRequest(map);
        JSONObject resultJson = JSONObject.fromObject(result);
        if (resultJson.optJSONObject("authority_query_response").optInt("bind") == 0) {
            return false;
        } else
            return true;
    }
    /**
     * 生成授权链接
     *
     * @param pid
     * @param customParameters
     * @return
     */
    public static PDDConvertLinkResultVO getAuthLink(String pid, String customParameters) {
//        customParameters=customParameters.replace("_","");
        System.out.println("获取授权链接:"+pid+"-"+customParameters);
        Map<String, String> map = new HashMap<>();
        map.put("type", "pdd.ddk.rp.prom.url.generate");
        map.put("channel_type", 10 + "");
        map.put("generate_we_app", true + "");
        map.put("custom_parameters",getFormatCustomParameters(customParameters));
        map.put("p_id_list", "[\"" + pid + "\"]");
        String result = baseRequest(map);
        System.out.println(result);
        JSONObject resultJson = JSONObject.fromObject(result);
        JSONArray array = resultJson.optJSONObject("rp_promotion_url_generate_response").optJSONArray("url_list");
        if (array != null && array.size() > 0) {
            Type type = new TypeToken<List<PDDConvertLinkResultVO>>() {
            }.getType();
            List<PDDConvertLinkResultVO> list = new Gson().fromJson(array.toString(), type);
            return list.get(0);
        }
        return null;
    }
    public static void main(String[] args) throws Exception{
//       PDDConvertLinkResultVO vo = getAuthLink("8590899_72067894", 437031+"");
//       boolean isAuthed = isAuth(PID_DEFAULT, 437031+"");
//       System.out.println("是否授权:"+isAuthed);
//
//       System.out.println(vo);
        PDDSearchFilter searchFilter=new PDDSearchFilter();
        searchFilter.setKw("鞋");
        searchFilter.setPage(1);
        searchFilter.setPageSize(20);
        PinDuoDuoApiUtil.searchGoods(searchFilter,Constant.PDD_SEARCH_CUSTOMER_PARAMS);
//       PDDGoodsDetail goods = PinDuoDuoApiUtil.getGoodsDetail(364476396740L);
    //    PDDConvertLinkResultVO vo = convertChannel("0", PID_DEFAULT, null);
     //   System.out.println(vo);
//        PDDConvertLinkResultVO goodsc =  PinDuoDuoApiUtil.convert(goods.getGoodsSign(), PID_DEFAULT + "", "437031", false);
//        System.out.println("");
    }
}