admin
2025-02-25 30d8e227e8d823b6c38c3b9c90ac2df03b63befe
fanli/src/main/java/com/yeshi/fanli/util/suning/SuningApiUtil.java
@@ -1,251 +1,428 @@
package com.yeshi.fanli.util.suning;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yeshi.fanli.dto.suning.SuningGoodsInfo;
import com.yeshi.fanli.dto.suning.SuningOrderQueryResultDTO;
import com.yeshi.fanli.dto.suning.SuningQueryModel;
import com.yeshi.fanli.entity.suning.SuningOrderInfo;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TimeUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class SuningApiUtil {
   public final static String APP_SECRET = "a217bc7018fd8ca112bb60f09057d996";
   public final static String APP_KEY = "6fca015e83eff7ef150bebcad418ea32";
   public final static String PID_SHARE = "666527";
   public final static String PID_BUY = "666526";
   private static String post(String url, String entity, Map<String, String> headers) {
      String charset = "utf-8";
      HttpClient client = new HttpClient();
      PostMethod method = new PostMethod(url);
      method.addRequestHeader("Content-Type", "text/html;charset=" + charset);
      method.setRequestHeader("Content-Type", "text/html;charset=" + charset);
      method.setRequestBody(entity);
      for (Iterator<String> its = headers.keySet().iterator(); its.hasNext();) {
         String key = its.next();
         method.addRequestHeader(key, headers.get(key));
      }
      try {
         client.executeMethod(method);
         return method.getResponseBodyAsString();
      } catch (HttpException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
      return "";
   }
   private static String getSign(Map<String, String> baseParams, String resParams) {
      StringBuffer sb = new StringBuffer();
      try {
         sb.append(APP_SECRET);
         sb.append(baseParams.get("appMethod"));
         sb.append(baseParams.get("appRequestTime"));
         sb.append(baseParams.get("appKey"));
         sb.append(baseParams.get("versionNo"));
      } catch (Exception e) {
      }
      try {
         sb.append(StringUtil.getBase64String(resParams));
      } catch (Exception e) {
         e.printStackTrace();
      }
      return StringUtil.Md5(sb.toString());
   }
   private static String baseRequest(String method, JSONObject params) {
      Map<String, String> baseParams = new HashMap<>();
      baseParams.put("appMethod", method);
      baseParams.put("appRequestTime", TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
      baseParams.put("format", "json");
      baseParams.put("appKey", APP_KEY);
      baseParams.put("versionNo", "v1.2");
      String sign = getSign(baseParams, params.toString());
      baseParams.put("signInfo", sign);
      String result = post("https://open.suning.com/api/http/sopRequest/" + method, params.toString(), baseParams);
      System.out.println(result);
      return result;
   }
   private static String baseRequest(String method, String key, JSONObject params) {
      JSONObject keyJSON = new JSONObject();
      for (Iterator<String> its = params.keySet().iterator(); its.hasNext();) {
         String k = its.next();
         keyJSON.put(k, params.get(k));
      }
      JSONObject content = new JSONObject();
      content.put(key, keyJSON);
      JSONObject body = new JSONObject();
      body.put("sn_body", content);
      JSONObject request = new JSONObject();
      request.put("sn_request", body);
      return baseRequest(method, request);
   }
   /**
    * 查询商品
    * @Title: searchGoods
    * @Description:
    * @param model
    * @return
    * List<SuningGoodsInfo> 返回类型
    * @throws
    */
   public static List<SuningGoodsInfo> searchGoods(SuningQueryModel model) {
      model.setPicWidth(320);
      model.setPicHeight(320);
      String key = "querySearchcommoditynew";
      String json = new Gson().toJson(model);
      String result = baseRequest("suning.netalliance.searchcommoditynew.query", key, JSONObject.fromObject(json));
      JSONObject resultJSON = JSONObject.fromObject(result);
      JSONArray array = resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body").optJSONObject(key)
            .optJSONArray("commodityList");
      if (array != null) {
         Type type = new TypeToken<ArrayList<SuningGoodsInfo>>() {
         }.getType();
         List<SuningGoodsInfo> goodsList = new Gson().fromJson(array.toString(), type);
         return goodsList;
      }
      return null;
   }
   public static SuningGoodsInfo getGoodsDetail(String goodsCode, String supplierCode) {
      JSONObject model = new JSONObject();
      model.put("commodityStr", goodsCode + "-" + supplierCode);
      model.put("picWidth", 600);
      model.put("picHeight", 600);
      String key = "queryCommoditydetail";
      String result = baseRequest("suning.netalliance.commoditydetail.query", key, model);
      System.out.println(result);
      JSONObject resultJSON = JSONObject.fromObject(result);
      JSONArray array = resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body").optJSONArray(key);
      if (array != null && array.size() > 0) {
         return new Gson().fromJson(array.optJSONObject(0).toString(), SuningGoodsInfo.class);
      }
      return null;
   }
   public static String convertLink(String productUrl, String quanUrl, String pid, String subUser) {
      JSONObject model = new JSONObject();
      if (productUrl != null)
         model.put("productUrl", productUrl);
      if (!StringUtil.isNullOrEmpty(quanUrl))
         model.put("quanUrl", quanUrl);
      if (pid != null)
         model.put("promotionId", pid);
      if (subUser != null)
         model.put("subUser", subUser);
      String key = "getExtensionlink";
      String result = baseRequest("suning.netalliance.extensionlink.get", key, model);
      System.out.println(result);
      JSONObject resultJSON = JSONObject.fromObject(result);
      JSONObject json = resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body").optJSONObject(key);
      String link = json.optString("shortLink");
      return link;
   }
   /**
    * 0
    * @Title: getOrderList
    * @Description:
    * @param startTime
    * @param endTime
    * @param page
    * @param orderLineStatus
    * @return
    * SuningOrderQueryResultDTO 返回类型
    * @throws
    */
   public static SuningOrderQueryResultDTO getOrderList(Date startTime, Date endTime, int page, int orderLineStatus) {
      JSONObject model = new JSONObject();
      model.put("startTime", TimeUtil.getGernalTime(startTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
      model.put("endTime", TimeUtil.getGernalTime(endTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
      model.put("pageSize", 20);
      model.put("pageNo", page);
      model.put("orderLineStatus", orderLineStatus);
      String key = "queryOrder";
      String result = baseRequest("suning.netalliance.order.query", key, model);
      JSONObject resultJSON = JSONObject.fromObject(result);
      resultJSON = resultJSON.optJSONObject("sn_responseContent");
      JSONArray array = resultJSON.optJSONObject("sn_body").optJSONArray(key);
      Gson gson = new Gson();
      Type type = new TypeToken<ArrayList<SuningOrderInfo>>() {
      }.getType();
      if (array != null) {
         List<SuningOrderInfo> orderList = new ArrayList<>();
         for (int i = 0; i < array.size(); i++) {
            JSONObject data = array.optJSONObject(i);
            JSONArray itemArray = data.optJSONArray("orderDetail");
            List<SuningOrderInfo> tempList = gson.fromJson(itemArray.toString(), type);
            for (SuningOrderInfo info : tempList) {
               info.setOrderCode(data.optString("orderCode"));
               orderList.add(info);
            }
         }
         return new SuningOrderQueryResultDTO(resultJSON.optJSONObject("sn_head").optInt("totalSize"), orderList);
      }
      return null;
   }
   /**
    * 常规转链
    * @Title: convertCommonLink
    * @Description:
    * @param url
    * @param pid
    * @param subUser
    * @return
    * String 返回类型
    * @throws
    */
   public static String convertCommonLink(String url, String pid, String subUser) {
      JSONObject model = new JSONObject();
      model.put("adBookId", pid);
      model.put("visitUrl", url);
      model.put("subUser", subUser);
      String key = "queryCustompromotionurl";
      String result = baseRequest("suning.netalliance.custompromotionurl.query", key, model);
      JSONObject resultJSON = JSONObject.fromObject(result);
      resultJSON = resultJSON.optJSONObject("sn_responseContent");
      String shortUrl = resultJSON.optJSONObject("sn_body").optJSONObject("queryCustompromotionurl").optString("shortUrl");
      return URLDecoder.decode(shortUrl);
   }
}
package com.yeshi.fanli.util.suning;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.yeshi.fanli.vo.suning.SuningConvertLinkResult;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yeshi.fanli.dto.suning.SuningGoodsInfo;
import com.yeshi.fanli.dto.suning.SuningGoodsInfoRecommend;
import com.yeshi.fanli.dto.suning.SuningOrderQueryResultDTO;
import com.yeshi.fanli.dto.suning.SuningQueryModel;
import com.yeshi.fanli.entity.suning.SuningOrderInfo;
import com.yeshi.fanli.util.StringUtil;
import org.yeshi.utils.TimeUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class SuningApiUtil {
    public final static String APP_SECRET = "a217bc7018fd8ca112bb60f09057d996";
    public final static String APP_KEY = "6fca015e83eff7ef150bebcad418ea32";
//    public final static String PID_SHARE = "666527";
//    public final static String PID_BUY = "666526";
//    public final static String PID_COUPON = "666528";
    public final static String PID_DEFAULT = "666526";
    private static String post(String url, String entity, Map<String, String> headers) {
        String charset = "utf-8";
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.addRequestHeader("Content-Type", "text/html;charset=" + charset);
        method.setRequestHeader("Content-Type", "text/html;charset=" + charset);
        method.setRequestBody(entity);
        for (Iterator<String> its = headers.keySet().iterator(); its.hasNext(); ) {
            String key = its.next();
            method.addRequestHeader(key, headers.get(key));
        }
        try {
            client.executeMethod(method);
            return method.getResponseBodyAsString();
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    private static String getSign(Map<String, String> baseParams, String resParams) {
        StringBuffer sb = new StringBuffer();
        try {
            sb.append(APP_SECRET);
            sb.append(baseParams.get("appMethod"));
            sb.append(baseParams.get("appRequestTime"));
            sb.append(baseParams.get("appKey"));
            sb.append(baseParams.get("versionNo"));
        } catch (Exception e) {
        }
        try {
            sb.append(StringUtil.getBase64String(resParams));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return StringUtil.Md5(sb.toString());
    }
    private static String baseRequest(String method, JSONObject params) {
        Map<String, String> baseParams = new HashMap<>();
        baseParams.put("appMethod", method);
        baseParams.put("appRequestTime", TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
        baseParams.put("format", "json");
        baseParams.put("appKey", APP_KEY);
        baseParams.put("versionNo", "v1.2");
        String sign = getSign(baseParams, params.toString());
        baseParams.put("signInfo", sign);
        String result = post("https://open.suning.com/api/http/sopRequest/" + method, params.toString(), baseParams);
        System.out.println(result);
        return result;
    }
    private static String baseRequest(String method, String key, JSONObject params) {
        JSONObject keyJSON = new JSONObject();
        for (Iterator<String> its = params.keySet().iterator(); its.hasNext(); ) {
            String k = its.next();
            keyJSON.put(k, params.get(k));
        }
        JSONObject content = new JSONObject();
        content.put(key, keyJSON);
        JSONObject body = new JSONObject();
        body.put("sn_body", content);
        JSONObject request = new JSONObject();
        request.put("sn_request", body);
        return baseRequest(method, request);
    }
    /**
     * 查询商品
     *
     * @param model
     * @return List<SuningGoodsInfo> 返回类型
     * @throws
     * @Title: searchGoods
     * @Description:
     */
    public static List<SuningGoodsInfo> searchGoods(SuningQueryModel model) {
        model.setPicWidth(320);
        model.setPicHeight(320);
        String key = "querySearchcommoditynew";
        String json = new Gson().toJson(model);
        // String result =
        // baseRequest("suning.netalliance.searchcommoditynew.query", key,
        // JSONObject.fromObject(json));
        String result = baseRequest("suning.netalliance.searchcommoditynew.query", key, JSONObject.fromObject(json));
        JSONObject resultJSON = JSONObject.fromObject(result);
        JSONArray array = resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body").optJSONObject(key)
                .optJSONArray("commodityList");
        if (array != null) {
            Type type = new TypeToken<ArrayList<SuningGoodsInfo>>() {
            }.getType();
            List<SuningGoodsInfo> goodsList = new Gson().fromJson(array.toString(), type);
            return goodsList;
        }
        return null;
    }
    /**
     * 查询商品
     *
     * @param model
     * @return List<SuningGoodsInfo> 返回类型
     * @throws
     * @Title: searchGoods
     * @Description:
     */
    public static List<SuningGoodsInfo> searchGoodsOld(SuningQueryModel model) {
        model.setPicWidth(320);
        model.setPicHeight(320);
        String key = "querySearchcommodity";
        String json = new Gson().toJson(model);
        String result = baseRequest("suning.netalliance.searchcommodity.query", key, JSONObject.fromObject(json));
        JSONObject resultJSON = JSONObject.fromObject(result);
        JSONObject responseContent = resultJSON.optJSONObject("sn_responseContent");
        if (responseContent != null) {
            JSONObject snBody = responseContent.optJSONObject("sn_body");
            if (snBody != null) {
                JSONArray array = snBody.optJSONArray(key);
                if (array != null) {
                    Type type = new TypeToken<ArrayList<SuningGoodsInfo>>() {
                    }.getType();
                    List<SuningGoodsInfo> goodsList = new Gson().fromJson(array.toString(), type);
                    return goodsList;
                }
            }
        }
        return null;
    }
    public static SuningGoodsInfo getGoodsDetail(String goodsCode, String supplierCode) {
        JSONObject model = new JSONObject();
        model.put("commodityStr", goodsCode + "-" + SuningUtil.getFullSupplierCode(supplierCode));
        model.put("picWidth", 600);
        model.put("picHeight", 600);
        model.put("couponMark", 1);
        String key = "queryCommoditydetail";
        String result = baseRequest("suning.netalliance.commoditydetail.query", key, model);
        System.out.println(result);
        JSONObject resultJSON = JSONObject.fromObject(result);
        if (resultJSON.optJSONObject("sn_responseContent") == null)
            return null;
        if (resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body") == null)
            return null;
        JSONArray array = resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body").optJSONArray(key);
        if (array != null && array.size() > 0) {
            return new Gson().fromJson(array.optJSONObject(0).toString(), SuningGoodsInfo.class);
        }
        return null;
    }
    /**
     * 查询关联商品
     *
     * @param model
     * @return List<SuningGoodsInfo> 返回类型
     * @throws
     * @Title: searchGoods
     * @Description:
     */
    public static List<SuningGoodsInfoRecommend> getRecommendGoods(String goodsCode, String supplierCode) {
        JSONObject model = new JSONObject();
        model.put("commodityCode", goodsCode);
        model.put("supplierCode", supplierCode);
        model.put("picWidth", 320);
        model.put("picHeight", 320);
        String key = "getMorerecommend";
        String json = new Gson().toJson(model);
        String result = baseRequest("suning.netalliance.morerecommend.get", key, JSONObject.fromObject(json));
        JSONObject resultJSON = JSONObject.fromObject(result);
        JSONArray array = resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body").optJSONObject(key)
                .optJSONArray("commodityList");
        if (array != null) {
            Type type = new TypeToken<ArrayList<SuningGoodsInfoRecommend>>() {
            }.getType();
            List<SuningGoodsInfoRecommend> goodsList = new Gson().fromJson(array.toString(), type);
            return goodsList;
        }
        return null;
    }
    public static List<SuningGoodsInfo> getGoodsDetailList(List<String> list) {
        String sts = "";
        for (String st : list) {
            sts += st + "_";
        }
        if (sts.endsWith("_"))
            sts = sts.substring(0, sts.length() - 1);
        JSONObject model = new JSONObject();
        model.put("commodityStr", sts);
        model.put("picWidth", 300);
        model.put("picHeight", 300);
        model.put("couponMark", 1);
        List<SuningGoodsInfo> goodsList = new ArrayList<>();
        String key = "queryCommoditydetail";
        String result = baseRequest("suning.netalliance.commoditydetail.query", key, model);
        System.out.println(result);
        JSONObject resultJSON = JSONObject.fromObject(result);
        JSONArray array = resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body").optJSONArray(key);
        if (array != null && array.size() > 0) {
            for (int i = 0; i < array.size(); i++) {
                goodsList.add(new Gson().fromJson(array.optJSONObject(i).toString(), SuningGoodsInfo.class));
            }
        }
        return goodsList;
    }
    public static String convertLink(String productUrl, String quanUrl, String pid, String subUser) {
        JSONObject model = new JSONObject();
        if (productUrl != null)
            model.put("productUrl", productUrl);
        if (!StringUtil.isNullOrEmpty(quanUrl))
            model.put("quanUrl", quanUrl);
        if (pid != null)
            model.put("promotionId", pid);
        if (subUser != null)
            model.put("subUser", subUser);
        String key = "getExtensionlink";
        String result = baseRequest("suning.netalliance.extensionlink.get", key, model);
        System.out.println(result);
        JSONObject resultJSON = JSONObject.fromObject(result);
        JSONObject json = resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body").optJSONObject(key);
        String link = json.optString("shortLink");
        return link;
    }
    public static SuningConvertLinkResult convertLinkNew(String commCode, String mertCode, String pid, String subUser) {
        JSONObject model = new JSONObject();
        if (commCode != null)
            model.put("commCode", commCode);
        if (!StringUtil.isNullOrEmpty(mertCode))
            model.put("mertCode", mertCode);
        if (pid != null)
            model.put("adBookId", pid);
        if (subUser != null)
            model.put("subUser", subUser);
        String key = "queryStorepromotionurl";
        String result = baseRequest("suning.netalliance.storepromotionurl.query", key, model);
        System.out.println(result);
        JSONObject resultJSON = JSONObject.fromObject(result);
        JSONObject json = resultJSON.optJSONObject("sn_responseContent").optJSONObject("sn_body").optJSONObject(key);
        return new Gson().fromJson(json.toString(), SuningConvertLinkResult.class);
    }
    /**
     * 0
     *
     * @param startTime
     * @param endTime
     * @param page
     * @param orderLineStatus (0:全部状态;1:等待付款;2:支付完成;3:退款;4:订单已取消;5:确认收货)
     * @return SuningOrderQueryResultDTO 返回类型
     * @throws
     * @Title: getOrderList
     * @Description:
     */
    public static SuningOrderQueryResultDTO getOrderList(Date startTime, Date endTime, int page, int orderLineStatus) {
        JSONObject model = new JSONObject();
        model.put("startTime", TimeUtil.getGernalTime(startTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
        model.put("endTime", TimeUtil.getGernalTime(endTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
        model.put("pageSize", 20);
        model.put("pageNo", page);
        model.put("orderLineStatus", orderLineStatus);
        String key = "queryOrder";
        String result = baseRequest("suning.netalliance.order.query", key, model);
        JSONObject resultJSON = JSONObject.fromObject(result);
        resultJSON = resultJSON.optJSONObject("sn_responseContent");
        JSONObject snBody = resultJSON.optJSONObject("sn_body");
        if (snBody == null)
            return null;
        JSONArray array = snBody.optJSONArray(key);
        if (array == null)
            return null;
        Gson gson = new Gson();
        Type type = new TypeToken<ArrayList<SuningOrderInfo>>() {
        }.getType();
        if (array != null) {
            List<SuningOrderInfo> orderList = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject data = array.optJSONObject(i);
                JSONArray itemArray = data.optJSONArray("orderDetail");
                List<SuningOrderInfo> tempList = gson.fromJson(itemArray.toString(), type);
                for (SuningOrderInfo info : tempList) {
                    info.setOrderCode(data.optString("orderCode"));
                    orderList.add(info);
                }
            }
            return new SuningOrderQueryResultDTO(resultJSON.optJSONObject("sn_head").optInt("totalSize"), orderList);
        }
        return null;
    }
    /**
     * 常规转链
     *
     * @param url
     * @param pid
     * @param subUser
     * @return String 返回类型
     * @throws
     * @Title: convertCommonLink
     * @Description:
     */
    public static String convertCommonLink(String url, String pid, String subUser) {
        JSONObject model = new JSONObject();
        model.put("adBookId", pid);
        model.put("visitUrl", url);
        model.put("subUser", subUser);
        String key = "queryCustompromotionurl";
        String result = baseRequest("suning.netalliance.custompromotionurl.query", key, model);
        System.out.println(result);
        JSONObject resultJSON = JSONObject.fromObject(result);
        resultJSON = resultJSON.optJSONObject("sn_responseContent");
        String shortUrl = resultJSON.optJSONObject("sn_body").optJSONObject("queryCustompromotionurl")
                .optString("shortUrl");
        return URLDecoder.decode(shortUrl);
    }
    /**
     * 商品精选接口
     *
     * @param eliteId
     * @param page
     * @return List<SuningGoodsInfo> 返回类型
     * @throws
     * @Title: getSelectRecommendGoods
     * @Description:
     */
    public static List<SuningGoodsInfo> getSelectRecommendGoods(int eliteId, int page) {
        JSONObject model = new JSONObject();
        model.put("eliteId", eliteId);
        model.put("pageIndex", page);
        // model.put("picWidth", 320);
        // model.put("picHeight", 320);
        model.put("size", 10);
        model.put("couponMark", 1);
        String key = "querySelectrecommendcommodity";
        String result = baseRequest("suning.netalliance.selectrecommendcommodity.query", key, model);
        System.out.println(result);
        JSONObject resultJSON = JSONObject.fromObject(result);
        resultJSON = resultJSON.optJSONObject("sn_responseContent");
        JSONArray array = resultJSON.optJSONObject("sn_body").optJSONObject(key).optJSONArray("commodityList");
        if (array != null) {
            Type type = new TypeToken<ArrayList<SuningGoodsInfo>>() {
            }.getType();
            List<SuningGoodsInfo> goodsList = new Gson().fromJson(array.toString(), type);
            return goodsList;
        }
        return null;
    }
}