首页 > 代码库 > 口袋通对接工具类

口袋通对接工具类

  1 package com.frame.util;  2   3 import java.io.BufferedReader;  4 import java.io.InputStreamReader;  5 import java.io.UnsupportedEncodingException;  6 import java.net.URL;  7 import java.net.URLConnection;  8 import java.net.URLEncoder;  9 import java.util.Date; 10 import java.util.HashMap; 11 import java.util.Iterator; 12 import java.util.Map; 13 import java.util.Set; 14 import java.util.TreeMap; 15 import java.util.regex.Matcher; 16 import java.util.regex.Pattern; 17  18 import net.sf.json.JSONArray; 19 import net.sf.json.JSONObject; 20  21 import org.apache.commons.codec.digest.DigestUtils; 22  23 /** 24  *  25  * @Description: 口袋通对接工具类 26  * @author 27  * @date  28  */ 29 public class KouDaiTongUtil { 30     public static final String KDT_URL="http://open.koudaitong.com/api/entry"; 31     public static final String APP_ID=""; 32     public static final String SECRET=""; 33     public static final String FORMAT="json"; //响应格式 34     public static final String SIGN_METHOD="md5"; //参数的加密方法 35     public static final String V="1.0";//API协议版本 36     /** 37      * 通用构造API请求参数 38      * @param appId 在口袋通后台获取 39      * @param format 可选,指定响应格式。默认json,目前支持格式为json 40      * @param method 调用API的接口名称,参照口袋通 41      * @param signMethod 可选,参数的加密方法选择。默认为md5 42      * @param timestamp 时间戳 方法内部会处理成格式为yyyy-mm-dd HH:mm:ss 43      * @param v API协议版本,可选值:1.0 44      * @param paramMap(调用api的参数,key为参数名称,需要和调用口袋通方法参数名称相同,否则调用不成功) 45      * @return 46      * @throws UnsupportedEncodingException 47      */ 48     public static String constructParam(String appId,String secret,String format,String method,String signMethod,Date timestamp,String v,Map<String,Object> paramMap) throws UnsupportedEncodingException { 49         String timestampStr=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp); 50         //遵循API对参数进行升序排列 51         Map<String,Object> map=new TreeMap<String,Object>(); 52         //加密参数(升序排列) 53         map.put("app_id", appId); 54         map.put("format", format); 55         map.put("method", method); 56         map.put("sign_method", signMethod); 57         map.put("timestamp", timestampStr); 58         map.put("v", v); 59         //应用参数 60         map.putAll(paramMap); 61         StringBuffer systemStr=new StringBuffer(); 62         //头加secret 63         systemStr.append(SECRET); 64         Set<Map.Entry<String, Object>> set=map.entrySet(); 65         for(Iterator<Map.Entry<String, Object>> it= set.iterator();it.hasNext();){ 66             Map.Entry<String, Object> entry=it.next(); 67             systemStr.append(entry.getKey()+entry.getValue()); 68         } 69         //尾加secret 70         systemStr.append(SECRET);  71         //拼接应用参数     72         Set<Map.Entry<String, Object>> paramSet=paramMap.entrySet(); 73         StringBuffer appStr=new StringBuffer(); 74         for(Iterator<Map.Entry<String, Object>> it=paramSet.iterator();it.hasNext();){ 75             appStr.append("&"); 76             Map.Entry<String, Object> entry=it.next(); 77             if(containWhiteSpace((String)entry.getValue().toString())){ 78                 appStr.append(entry.getKey()+"="+URLEncoder.encode((String)entry.getValue(),"utf-8")); 79             }else{ 80                 appStr.append(entry.getKey()+"="+entry.getValue());     81             } 82         } 83         //32位md5加密 84         String sign=DigestUtils.md5Hex(systemStr.toString()); 85         String param="sign="+sign+"&timestamp="+URLEncoder.encode(timestampStr,"utf-8")+"&v="+v+"&app_id="+APP_ID+"&method="+method+"&sign_method="+signMethod+"&format="+format+appStr; 86         System.out.println("URL:"+KDT_URL+"?"+param); 87         return param; 88     } 89      90      91     /** 92      *  93      * @param 判断是否包含空字符串 94      * @return 95      */ 96     public static boolean containWhiteSpace(String input){ 97         Pattern pattern = Pattern.compile("\\s"); 98         Matcher matcher = pattern.matcher(input); 99         boolean flag = matcher.find();100         return flag;101     }102     /**103      * 发送get请求104      * @param url105      * @param param106      * @return107      */108     public static String sendGet(String url,String param) {109         String result = "";110         BufferedReader in = null;111         try {112              String urlNameString = url + "?" + param;113              URL realUrl = new URL(urlNameString);114              URLConnection connection = realUrl.openConnection();    115              connection.connect();116              in = new BufferedReader(new InputStreamReader(117                     connection.getInputStream()));118              String line;119              while ((line = in.readLine()) != null) {120                 result += line;121              }122         } catch (Exception e) {123             System.out.println("发送GET请求出现异常!" + e);124             e.printStackTrace();125         }126         finally {127             try {128                 if (in != null) {129                     in.close();130                 }131             } catch (Exception e2) {132                 e2.printStackTrace();133             }134         }135         return result;136     }137     /**138      * 口袋同通用请求方法返回json字符串139      * @param method 调用API的接口名称来源KdtMethodListEnum140      * @param paramMap(调用api的参数,key为参数名称,需要和调用口袋通方法参数名称相同,否则调用不成功)141      * @return142      * @throws UnsupportedEncodingException143      */144     public static Map<String,Object> sendRequest(String method,Map<String,Object> paramMap) throws UnsupportedEncodingException{145         Map<String,Object> resultMap=new HashMap<String,Object>(); 146         String param = constructParam(APP_ID,SECRET, FORMAT, method, SIGN_METHOD, new Date(System.currentTimeMillis() + 8*60 * 60 * 1000), V,paramMap);///////////////////////////////////////////////////147           String reponse= sendGet(KDT_URL,param);148           JSONObject jsonObject=JSONObject.fromObject(reponse);149           //请求发生错误150         if(jsonObject.containsKey("error_response")){151             int errorCode=Integer.parseInt(JSONObject.fromObject(jsonObject.get("error_response")).get("code").toString());152             String msg=JSONObject.fromObject(jsonObject.get("error_response")).get("msg").toString();153             resultMap.put("status", "FAILED");154             resultMap.put("message","请求失败,"+msg+",错误码:"+errorCode);155         }else{156             resultMap.put("status", "SUCCESS");        157             resultMap.put("result", reponse);158         }159           return resultMap;160     }161     162     /**163      * 获取交易订单(如果参数都不传就会下拉所有订单)164      * @param status 订单状态165      * @param startCreated 订单创建起始时间166      * @param endCreated 订单创建结束时间167      * @param startPayDate 支付起始时间168      * @param endPayDate  支付结束时间169      * @return map170      * @throws UnsupportedEncodingException171      */172     public static Map<String,Object> getOrderListByCondition(String status,String startCreated,String endCreated,String startPayDate,String endPayDate) throws UnsupportedEncodingException{173         String method="kdt.trades.sold.get"; //查询卖家已卖出的交易列表        174         Map<String,Object> paramMap=new HashMap<String,Object>();175         if(status!=null){176             paramMap.put("status", status);177         }178         if(startCreated!=null){179             paramMap.put("start_created", startCreated);180         }181         if(endCreated!=null){182             paramMap.put("end_created", endCreated);183         }184         if(startPayDate!=null){185             paramMap.put("start_pay", startPayDate);186         }187         if(endPayDate!=null){188             paramMap.put("end_pay", endPayDate);189         }190           Map<String,Object> map=KouDaiTongUtil.sendRequest(method,paramMap);191           return map;192     }193      public static String getValue(Map map, String key) {194             Object obj = map.get(key);195             if (obj == null) {196               return "";197             }198             return String.valueOf(obj);199           }200     public static void main(String[] args) throws UnsupportedEncodingException{201         System.out.println(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis() + 8*60 * 60 * 1000)));202         Map<String,Object> map=KouDaiTongUtil.getOrderListByCondition(null,"2014-07-01 00:00:00", null, null, null);203         String ss=getValue(map,"result");204         System.out.println("*************"+ss);205         JSONObject jsonObject=JSONObject.fromObject(ss);206         //System.out.println(jsonObject);207         JSONObject  response=jsonObject.getJSONObject("response");208         JSONArray  data=http://www.mamicode.com/response.getJSONArray("trades");209         System.out.println(data.size());210         String save_sql=" begin ";211         for(int i=0;i<data.size();i++){212             JSONObject info=data.getJSONObject(i);213             String num=info.getString("num");214             String num_iid=info.getString("num_iid");215             String price=info.getString("price");216             String pic_path=info.getString("pic_path");217             String pic_thumb_path=info.getString("pic_thumb_path");218             String title=info.getString("title");219             String status=info.getString("status");220             String shipping_type=info.getString("shipping_type");221             String post_fee=info.getString("post_fee");222             String total_fee=info.getString("total_fee");223             String discount_fee=info.getString("discount_fee");224             String payment=info.getString("payment");225             String created=info.getString("created");226             String pay_time=info.getString("pay_time");227             String pay_type=info.getString("pay_type");228             String consign_time=info.getString("consign_time");229             String buyer_area=info.getString("buyer_area");230             String tid=info.getString("tid");231             String weixin_user_id=info.getString("weixin_user_id");232             String buyer_nick=info.getString("buyer_nick");233             String buyer_message=info.getString("buyer_message");234             String seller_flag=info.getString("seller_flag");235             String trade_memo=info.getString("trade_memo");236             String receiver_city=info.getString("receiver_city");237             String receiver_district=info.getString("receiver_district");238             String receiver_name=info.getString("receiver_name");239             String receiver_state=info.getString("receiver_state");240             String receiver_address=info.getString("receiver_address");241             String receiver_zip=info.getString("receiver_zip");242             String receiver_mobile=info.getString("receiver_mobile");243             String feedback=info.getString("feedback");244             String outer_tid=info.getString("outer_tid");245             save_sql+=" insert into KDT_TRADES values(‘"+tid+"‘,‘"+num+"‘,‘"+num_iid+"‘,‘"+price+"‘,‘"+pic_path+"‘,‘"+pic_thumb_path+"‘,‘"+title+"‘,‘"+weixin_user_id+"‘,‘"+buyer_nick+"‘,‘"+buyer_message+"‘,‘"+seller_flag+"‘,‘"+trade_memo+"‘,‘"+receiver_city+"‘,‘"+receiver_district+"‘,‘"+receiver_name+"‘,‘"+receiver_state+"‘,‘"+receiver_address+"‘,‘"+receiver_zip+"‘,‘"+receiver_mobile+"‘,‘"+feedback+"‘,‘"+outer_tid+"‘,‘"+status+"‘,‘"+shipping_type+"‘,‘"+post_fee+"‘,‘"+total_fee+"‘,‘"+discount_fee+"‘,‘"+payment+"‘,‘"+created+"‘,‘"+pay_time+"‘,‘"+pay_type+"‘,‘"+consign_time+"‘,‘"+buyer_area+"‘); ";246             //int updateForSql = AccessDB.updateForSql(save_sql);247             JSONArray orders=info.getJSONArray("orders");248             for(int j=0;j<orders.size();j++){//目前的所有交易只有 1 个子订单249                 JSONObject order_info=orders.getJSONObject(j);250                 String _trades_id=tid;251                 String _outer_sku_id=order_info.getString("outer_sku_id");252                 String _title=order_info.getString("title");253                 String _seller_nick=order_info.getString("seller_nick");254                 String _price=order_info.getString("price");255                 String _total_fee=order_info.getString("total_fee");256                 String _payment=order_info.getString("payment");257                 String _sku_properties_name=order_info.getString("sku_properties_name");258                 String _pic_path=order_info.getString("pic_path");259                 String _pic_thumb_path=order_info.getString("pic_thumb_path");260                 String _buyer_messages=order_info.getString("buyer_messages");261                 String _num_iid=order_info.getString("num_iid");262                 String _num=order_info.getString("num");263                 String _sku_id=order_info.getString("sku_id");264                 //String _discount_fee=order_info.getString("discount_fee");265                 save_sql+=" insert into KDT_ORDERS values(‘"+_trades_id+"‘,‘"+_num_iid+"‘,‘"+_sku_id+"‘,‘"+_num+"‘,‘"+_outer_sku_id+"‘,‘"+_title+"‘,‘"+_seller_nick+"‘,‘"+_price+"‘,‘"+_total_fee+"‘,‘0‘,‘"+payment+"‘,‘"+_sku_properties_name+"‘,‘"+_pic_path+"‘,‘"+_pic_thumb_path+"‘,‘"+_buyer_messages+"‘); ";266                 //int updateForSql1 = AccessDB.updateForSql(save_sql);267 //                System.out.println("_title"+_title);268 //                System.out.println("_trades_id"+_trades_id);269             }270             271             //System.out.println(orders);272 //            System.out.println("weixin_user_id:"+weixin_user_id);273 //            System.out.println("title:"+title);274         }275         save_sql+=" end; ";276         System.out.println("save_sql:"+save_sql);277         //int updateForSql = AccessDB.updateForSql(save_sql);278         System.out.println("OK");279         280 //        JSONArray  orders=data.optJSONArray("orders");281 //        System.out.println(orders);282 //        JSONArray data=http://www.mamicode.com/response.getJSONArray("data");283 //        JSONObject info=data.getJSONObject(0);284 //        String province=info.getString("province");285 //        String city=info.getString("city");286 //        String district=info.getString("district");287 //        String address=info.getString("address");288 //         System.out.println(province+city+district+address);289         290         291     }292     293     294 }