From b30e1a48f2bc5f65a0efd2e69e090fed2d7a627c Mon Sep 17 00:00:00 2001
From: yanghui <2536613402@qq.com>
Date: 星期四, 17 十一月 2022 15:56:43 +0800
Subject: [PATCH] #feat 订单退款和查询

---
 springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java |  204 ++++++++++++++++++++++++++++++++++++---------------
 1 files changed, 144 insertions(+), 60 deletions(-)

diff --git a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java
index ea451de..f6021ff 100644
--- a/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java
+++ b/springcloud_k8s_panzhihuazhihuishequ/common/src/main/java/com/panzhihua/common/utlis/HttpClientUtil.java
@@ -1,29 +1,38 @@
 package com.panzhihua.common.utlis;
 
-
-import com.panzhihua.common.constants.HttpConstant;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.http.Header;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.client.methods.HttpUriRequest;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.message.BasicHeader;
-import org.apache.http.util.EntityUtils;
-import org.springframework.util.ObjectUtils;
-
 import java.io.*;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.net.URLConnection;
+import java.security.KeyStore;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+
+import com.alibaba.fastjson.JSONObject;
+import org.apache.http.Header;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicHeader;
+import org.apache.http.ssl.SSLContexts;
+import org.apache.http.util.EntityUtils;
+import org.springframework.util.ObjectUtils;
+
+import com.panzhihua.common.constants.HttpConstant;
+
+import lombok.extern.slf4j.Slf4j;
+
+import javax.net.ssl.SSLContext;
 
 /**
  * @program: springcloud_k8s_panzhihuazhihuishequ
@@ -35,21 +44,28 @@
 public class HttpClientUtil {
     /**
      * 通过post方式调用http接口
-     * @param url     url路径
-     * @param jsonParam    json格式的参数
-     * @param reSend     重发次数
-     * @param headerKey     header键值
-     * @param headerValue     headervalue
+     * 
+     * @param url
+     *            url路径
+     * @param jsonParam
+     *            json格式的参数
+     * @param reSend
+     *            重发次数
+     * @param headerKey
+     *            header键值
+     * @param headerValue
+     *            headervalue
      * @return
      * @throws Exception
      */
-    public static String sendPostByJson(String url, String jsonParam,int reSend,String headerKey,String headerValue) {
-        //声明返回结果
+    public static String sendPostByJson(String url, String jsonParam, int reSend, String headerKey,
+        String headerValue) {
+        // 声明返回结果
         String result = "";
-        //开始请求API接口时间
-        long startTime=System.currentTimeMillis();
-        //请求API接口的响应时间
-        long endTime= 0L;
+        // 开始请求API接口时间
+        long startTime = System.currentTimeMillis();
+        // 请求API接口的响应时间
+        long endTime = 0L;
         HttpEntity httpEntity = null;
         HttpResponse httpResponse = null;
         HttpClient httpClient = null;
@@ -58,68 +74,69 @@
             httpClient = HttpClientFactory.getInstance().getHttpClient();
             // 设置请求头和报文
             HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
-            Header header=new BasicHeader("Accept-Encoding",null);
+            Header header = new BasicHeader("Accept-Encoding", null);
             httpPost.setHeader(header);
             if (!ObjectUtils.isEmpty(headerKey)) {
-                httpPost.setHeader(headerKey,headerValue);
+                httpPost.setHeader(headerKey, headerValue);
             }
             // 设置报文和通讯格式
             StringEntity stringEntity = new StringEntity(jsonParam, HttpConstant.UTF8_ENCODE);
             stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
             stringEntity.setContentType(HttpConstant.APPLICATION_JSON);
             httpPost.setEntity(stringEntity);
-            log.info("请求{}接口的参数为{}",url,jsonParam);
-            //执行发送,获取相应结果
+//            log.info("请求{}接口的参数为{}", url, jsonParam);
+            // 执行发送,获取相应结果
             httpResponse = httpClient.execute(httpPost);
-            httpEntity= httpResponse.getEntity();
+            httpEntity = httpResponse.getEntity();
             result = EntityUtils.toString(httpEntity);
         } catch (Exception e) {
-            log.error("请求{}接口出现异常",url,e);
+            log.error("请求{}接口出现异常", url, e);
             if (reSend > 0) {
-                log.info("请求{}出现异常:{},进行重发。进行第{}次重发",url,e.getMessage(),(HttpConstant.REQ_TIMES-reSend +1));
-                result = sendPostByJson(url, jsonParam, reSend - 1,headerKey,headerValue);
+                log.info("请求{}出现异常:{},进行重发。进行第{}次重发", url, e.getMessage(), (HttpConstant.REQ_TIMES - reSend + 1));
+                result = sendPostByJson(url, jsonParam, reSend - 1, headerKey, headerValue);
                 if (result != null && !"".equals(result)) {
                     return result;
                 }
             }
-        }finally {
+        } finally {
             try {
                 EntityUtils.consume(httpEntity);
             } catch (IOException e) {
-                log.error("http请求释放资源异常",e);
+                log.error("http请求释放资源异常", e);
             }
         }
-        //请求接口的响应时间
-        endTime=System.currentTimeMillis();
-        log.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒",url,result,(endTime-startTime));
+        // 请求接口的响应时间
+        endTime = System.currentTimeMillis();
+//        log.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒", url, result, (endTime - startTime));
         return result;
 
     }
 
     /**
      * 使用http请求调用接口,参数类型为xml
-     * @param urlStr    请求地址
-     * @param data  请求参数
-     * @return  调用结果
+     * 
+     * @param urlStr
+     *            请求地址
+     * @param data
+     *            请求参数
+     * @return 调用结果
      */
-    public static String httpsRequest(String urlStr,String data) {
+    public static String httpsRequest(String urlStr, String data) {
         try {
             URL url = new URL(urlStr);
             URLConnection con = url.openConnection();
             con.setDoOutput(true);
-//            con.setRequestProperty("Pragma:", "no-cache");
+            // con.setRequestProperty("Pragma:", "no-cache");
             con.setRequestProperty("Cache-Control", "no-cache");
             con.setRequestProperty("Content-Type", "text/xml");
 
-            OutputStreamWriter out = new OutputStreamWriter(con
-                    .getOutputStream());
+            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
             log.info("urlStr=" + urlStr);
             log.info("xmlInfo=" + data);
             out.write(new String(data.getBytes("UTF-8")));
             out.flush();
             out.close();
-            BufferedReader br = new BufferedReader(new InputStreamReader(con
-                    .getInputStream()));
+            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
             String line = "";
             StringBuffer sb = new StringBuffer();
             for (line = br.readLine(); line != null; line = br.readLine()) {
@@ -133,7 +150,6 @@
         }
         return "";
     }
-
 
     /**
      * http请求工具类,get请求
@@ -157,7 +173,7 @@
                     key = iterator.next();
                     Object val = params.get(key);
                     if (val instanceof List) {
-                        List v = (List) val;
+                        List v = (List)val;
                         for (Object o : v) {
                             stringBuilder.append(key).append("=").append(o.toString()).append("&");
                         }
@@ -177,7 +193,7 @@
                 log.info(errorLog);
                 throw new Exception(url + errorLog);
             }
-            //读取返回信息
+            // 读取返回信息
             String charSet = "utf-8";
             if (resonseCharSet != null && resonseCharSet.length > 0)
                 charSet = resonseCharSet[0];
@@ -203,8 +219,10 @@
     /**
      * http请求工具类,post请求
      *
-     * @param url    url
-     * @param param 参数值 仅支持String
+     * @param url
+     *            url
+     * @param param
+     *            参数值 仅支持String
      * @return
      * @throws Exception
      */
@@ -226,7 +244,7 @@
                 log.info(errorLog);
                 throw new Exception(url + errorLog);
             }
-            //读取返回信息
+            // 读取返回信息
             String output;
             bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "utf-8"));
             StringBuilder stringBuilder = new StringBuilder();
@@ -248,11 +266,14 @@
 
     /**
      * get请求
-     * @param url 请求地址(get请求时参数自己组装到url上)
-     * @param headerMap 请求头
+     * 
+     * @param url
+     *            请求地址(get请求时参数自己组装到url上)
+     * @param headerMap
+     *            请求头
      * @return 响应文本
      */
-    public static String get(String url, Map<String, String> headerMap,String param) {
+    public static String get(String url, Map<String, String> headerMap, String param) {
         // 请求地址,以及参数设置
         HttpPost post = new HttpPost(url);
         if (headerMap != null) {
@@ -311,7 +332,7 @@
         InputStream in = null;
         if (entity != null) {
             try {
-                in =  entity.getContent();
+                in = entity.getContent();
             } catch (Exception e) {
                 e.printStackTrace();
             }
@@ -319,4 +340,67 @@
         return in;
     }
 
+    /**
+     * 退款请求微信
+     * @param url   请求地址
+     * @param data  请求数据
+     * @param mchId 商户id
+     * @param isTest    是否是测试
+     * @return  退款结果
+     * @throws Exception    抛出异常
+     */
+    public static String doRefund(String url, String data,String mchId,Boolean isTest) throws Exception{
+        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
+        //P12文件目录 证书路径,这里需要你自己修改,linux下还是windows下的根路径
+        String filepath = "";
+        if(isTest){
+            filepath = "D:\\wx\\WXCertUtil\\cert\\";
+        }else{
+            filepath = "/mnt/data/refund/huacheng/";
+        }
+        System.out.println("filepath->"+filepath);
+        FileInputStream instream = new FileInputStream(filepath+"apiclient_cert.p12");
+        try {
+            keyStore.load(instream, mchId.toCharArray());//这里写密码..默认是你的MCHID
+        } finally {
+            instream.close();
+        }
+
+        // Trust own CA and all self-signed certs
+        SSLContext sslcontext = SSLContexts.custom()
+                .loadKeyMaterial(keyStore, mchId.toCharArray())//这里也是写密码的
+                .build();
+        // Allow TLSv1 protocol only
+        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
+                sslcontext,
+                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
+        CloseableHttpClient httpclient = HttpClients.custom()
+                .setSSLSocketFactory(sslsf)
+                .build();
+        try {
+            HttpPost httpost = new HttpPost(url); // 设置响应头信息
+            httpost.addHeader("Connection", "keep-alive");
+            httpost.addHeader("Accept", "*/*");
+            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
+            httpost.addHeader("Host", "api.mch.weixin.qq.com");
+            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
+            httpost.addHeader("Cache-Control", "max-age=0");
+            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
+            httpost.setEntity(new StringEntity(data, "UTF-8"));
+            CloseableHttpResponse response = httpclient.execute(httpost);
+            try {
+                HttpEntity entity = response.getEntity();
+
+                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
+                log.info("请求微信退款接口返回结果:" + JSONObject.toJSONString(jsonStr));
+                EntityUtils.consume(entity);
+                return jsonStr;
+            } finally {
+                response.close();
+            }
+        } finally {
+            httpclient.close();
+        }
+
+    }
 }

--
Gitblit v1.7.1