From bc472feefdfc4afbcb0fcd35a8fb8d047edf6a9f Mon Sep 17 00:00:00 2001
From: “djh” <“3298565835@qq.com”>
Date: 星期二, 18 二月 2025 16:50:30 +0800
Subject: [PATCH] 煤矿缴费修改

---
 exam-system/src/main/java/com/gkhy/exam/pay/utils/PayUtils.java |  379 ++++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 322 insertions(+), 57 deletions(-)

diff --git a/exam-system/src/main/java/com/gkhy/exam/pay/utils/PayUtils.java b/exam-system/src/main/java/com/gkhy/exam/pay/utils/PayUtils.java
index 135fade..4f2e5c6 100644
--- a/exam-system/src/main/java/com/gkhy/exam/pay/utils/PayUtils.java
+++ b/exam-system/src/main/java/com/gkhy/exam/pay/utils/PayUtils.java
@@ -1,9 +1,20 @@
 package com.gkhy.exam.pay.utils;
 
+import cn.com.jit.mof.MOFClient;
+import cn.com.jit.mof.bean.MOFSignResult;
+import cn.com.jit.mof.bean.MOFVerifyResult;
+import cn.com.jit.new_vstk.AdvanceSignClient;
+import cn.com.jit.new_vstk.Bean.*;
+import cn.com.jit.new_vstk.SignClient;
+import cn.com.jit.new_vstk.exception.NewCSSException;
 import com.alibaba.fastjson2.JSONObject;
 import com.gkhy.exam.pay.entity.PayReqData;
+import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.codec.digest.DigestUtils;
-import org.apache.http.*;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.NameValuePair;
+import org.apache.http.StatusLine;
 import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.HttpResponseException;
@@ -25,13 +36,18 @@
 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
 import org.apache.http.message.BasicNameValuePair;
 import org.apache.http.util.EntityUtils;
+import org.dom4j.Element;
+import org.dom4j.io.OutputFormat;
+import org.dom4j.io.XMLWriter;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
 
-import javax.annotation.Resource;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509TrustManager;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
+import java.io.*;
+import java.nio.charset.StandardCharsets;
 import java.security.KeyManagementException;
 import java.security.NoSuchAlgorithmException;
 import java.security.cert.X509Certificate;
@@ -40,38 +56,66 @@
 /**
  * 缴费相关接口
  */
+@Component
+@Slf4j
 public class PayUtils {
 
-    private final static String appid="ED76A5F1703540BE977D34780B371FEB";
+//    private final static String appid = "ED76A5F1703540BE977D34780B371FEB";
 
+    @Value("${finance.orderUrl}")
+    private String orderUrl;
 
-    public static ResultVo sendApiPost(PayReqData payReqData) throws IOException {
+    @Value("${finance.payNotifyUrl}")
+    private String payNotifyUrl;
 
-        //正式
-        String proUrl="http://finpt.xjcz.gov.cn/fs-service/fs-pay/invoice.do";
-        //测试
-        String testUrl= "http://finpt.xjcz.gov.cn/fs-service-test/fs-pay/invoice.do";
+    @Value("${finance.payQueryUrl}")
+    private String payQueryUrl;
+
+    @Value("${finance.apiId}")
+    private String appId;
+
+    @Value("${finance.queryUrl}")
+    private String queryUrl;
+
+    @Value("${finance.uploadXmlUrl}")
+    private String uploadXmlUrl;
+
+//    @Value(("${finance.path}"))
+//    private String path;
+
+    /**
+     * 请求开票,发起支付
+     * @param payReqData
+     * @return
+     * @throws IOException
+     */
+    public ResultVo sendApiPost(PayReqData payReqData) throws IOException {
 
         Map<String, String> param = new HashMap<>();
+//        String appid = "A1749891493E4CDDBFE4506357B1F0AB";
+//        String orderUrl = "http://finpt.xjcz.gov.cn/fs-service/fs-pay/invoice.do";
 
-        HttpPost httpPost = new HttpPost(testUrl);
-
+        HttpPost httpPost = new HttpPost(orderUrl);
+        log.info("请求地址:"+orderUrl);
         //请求参数转为json格式base64编码
         String reqData = Base64.getEncoder().encodeToString(JSONObject.toJSONString(payReqData).getBytes());
-        String mac = appid+"||"+reqData;
+        String mac = appId + "||" + reqData;
         mac = DigestUtils.md5Hex(mac.getBytes());
-        param.put("appid",appid);
-        param.put("reqdata",reqData);
-        param.put("mac",mac);
+        param.put("appid", appId);
+        log.info("请求appid:"+appId);
+        param.put("reqdata", reqData);
+        param.put("mac", mac);
 
-        httpPost.setEntity(assemblyFormEntity(param,"utf-8"));
-        HttpClient httpClient = getHttpClient(testUrl);
+        httpPost.setEntity(assemblyFormEntity(param, "utf-8"));
+        HttpClient httpClient = getHttpClient(orderUrl);
         HttpResultVo execute = httpClient.execute(httpPost, getResponseHandler());
         String stringContent = execute.getStringContent();
         ResultVo resultVo = JSONObject.parseObject(stringContent, ResultVo.class);
+        log.info("请求结果为:"+resultVo);
         return resultVo;
     }
 
+    //组装请求体
     private static UrlEncodedFormEntity assemblyFormEntity(Map<String, String> parameters, String charset) {
         List<NameValuePair> formParameters = assemblyParameter(parameters);
         UrlEncodedFormEntity formEntity = null;
@@ -107,6 +151,7 @@
 
     }
 
+    //在调用SSL之前需要重写验证方法,取消检测SSL 创建ConnectionManager,添加Connection配置信息
     private static HttpClient sslClient() {
         try {
             // 在调用SSL之前需要重写验证方法,取消检测SSL
@@ -117,13 +162,15 @@
                 }
 
                 @Override
-                public void checkClientTrusted(X509Certificate[] xcs, String str) {}
+                public void checkClientTrusted(X509Certificate[] xcs, String str) {
+                }
 
                 @Override
-                public void checkServerTrusted(X509Certificate[] xcs, String str) {}
+                public void checkServerTrusted(X509Certificate[] xcs, String str) {
+                }
             };
             SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
-            ctx.init(null, new TrustManager[] {trustManager}, null);
+            ctx.init(null, new TrustManager[]{trustManager}, null);
             SSLConnectionSocketFactory socketFactory =
                     new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
             // 创建Registry
@@ -147,6 +194,7 @@
 
     }
 
+    //获取响应结果处理器,将响应结果封装为HttpResult对象
     private static ResponseHandler<HttpResultVo> getResponseHandler() {
         ResponseHandler<HttpResultVo> responseHandler = new ResponseHandler<HttpResultVo>() {
             @Override
@@ -187,6 +235,7 @@
         return responseHandler;
     }
 
+    //判断相应内容是否为文本类型
     private static boolean isTextType(ContentType contentType) {
         if (contentType == null) {
             throw new RuntimeException("ContentType is null");
@@ -210,81 +259,297 @@
 
 
     //缴费结果通知
-    public static Map<String,String> receive(JSONObject jsonObject) throws IOException {
+    public Map<String, String> receive(JSONObject jsonObject) throws IOException {
 
         Map<String, String> params = new HashMap<>();
         JSONObject reqdata = new JSONObject();
 
-        Map<String,String> result = (Map<String, String>) jsonObject.get("reqdata");
+        Map<String, String> result = (Map<String, String>) jsonObject.get("reqdata");
         String orderNo = result.get("orderNo");
 
         //确认是否成功
-        String  notarize= affirmPost(orderNo);
-        reqdata.put("orderNo",orderNo);
-        reqdata.put("status",notarize);
+        String notarize = affirmPost(orderNo);
+        reqdata.put("orderNo", orderNo);
+        reqdata.put("status", notarize);
 
         String req = Base64.getEncoder().encodeToString(reqdata.toJSONString().getBytes());
-        String mac = appid+"||"+req;
+        String mac = appId + "||" + req;
         mac = DigestUtils.md5Hex(mac.getBytes());
-        params.put("appid",appid);
-        params.put("reqdata",req);
-        params.put("mac",mac);
+        params.put("appid", appId);
+        params.put("reqdata", req);
+        params.put("mac", mac);
 
         return params;
     }
 
     //缴费结果确认查询
-    public static String affirmPost(String orderNo) throws IOException {
-        String porUrl="http://finpt.xjcz.gov.cn/fs-service/fs-pay/notifyConfirm.do";
-        String testUrl="http://finpt.xjcz.gov.cn/fs-service-test/fs-pay/notifyConfirm.do";
+    public String affirmPost(String orderNo) throws IOException {
 
         HashMap<String, String> param = new HashMap<>();
 
         JSONObject jsonObject = new JSONObject();
-        jsonObject.put("orderNo",orderNo);
+        jsonObject.put("orderNo", orderNo);
         String reqdata = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
-        String mac = appid+"||"+reqdata;
-        mac=DigestUtils.md5Hex(mac.getBytes());
-        param.put("appid",appid);
-        param.put("reqdata",reqdata);
-        param.put("mac",mac);
+        String mac = appId + "||" + reqdata;
+        mac = DigestUtils.md5Hex(mac.getBytes());
+        param.put("appid", appId);
+        param.put("reqdata", reqdata);
+        param.put("mac", mac);
 
-        HttpPost httppost = new HttpPost(testUrl);
-        httppost.setEntity(assemblyFormEntity(param,"utf-8"));
-        HttpClient httpClient = getHttpClient(testUrl);
+        HttpPost httppost = new HttpPost(payNotifyUrl);
+        httppost.setEntity(assemblyFormEntity(param, "utf-8"));
+        HttpClient httpClient = getHttpClient(payNotifyUrl);
         HttpResultVo execute = httpClient.execute(httppost, getResponseHandler());
         String stringContent = execute.getStringContent();
         ResultVo resultVo = JSONObject.parseObject(stringContent, ResultVo.class);
-        System.out.printf("请求结果为:"+resultVo);
-        if (resultVo.getRespcode().equals("BUS0000")){
+        log.info("请求结果为:" + resultVo);
+        if (resultVo.getRespcode().equals("BUS0000")) {
             return "success";
         }
         return "fail";
     }
 
     //缴费结果查询
-    public static JSONObject query(String orderNo) throws IOException {
-        String proUrl="http://finpt.xjcz.gov.cn/fs-service/fs-pay/query.do";
-        String testUrl="http://finpt.xjcz.gov.cn/fs-service-test/fs-pay/query.do";
-
+    public JSONObject query(String orderNo) throws IOException {
         HashMap<String, String> param = new HashMap<>();
 
         JSONObject jsonObject = new JSONObject();
-        jsonObject.put("orderNo",orderNo);
+        jsonObject.put("orderNo", orderNo);
         String reqdata = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
-        String mac = appid+"||"+reqdata;
+        String mac = appId + "||" + reqdata;
         mac = DigestUtils.md5Hex(mac.getBytes());
-        param.put("appid",appid);
-        param.put("reqdata",reqdata);
-        param.put("mac",mac);
+        param.put("appid", appId);
+        param.put("reqdata", reqdata);
+        param.put("mac", mac);
 
-        HttpPost httppost = new HttpPost(testUrl);
-        httppost.setEntity(assemblyFormEntity(param,"utf-8"));
-        HttpClient httpClient = getHttpClient(testUrl);
+        HttpPost httppost = new HttpPost(payQueryUrl);
+        httppost.setEntity(assemblyFormEntity(param, "utf-8"));
+        HttpClient httpClient = getHttpClient(payQueryUrl);
         HttpResultVo execute = httpClient.execute(httppost, getResponseHandler());
         String stringContent = execute.getStringContent();
         JSONObject result = JSONObject.parseObject(stringContent);
-        System.out.printf("请求结果json为:"+result);
+        log.info("请求结果json为:" + result);
         return result;
     }
+
+
+    //票据查询
+    public ResponseEntity<String> findBill(String billNO) throws IOException {
+        Map<String, String> params = new HashMap<>();
+
+        JSONObject jsonObject = new JSONObject();
+        jsonObject.put("billNo",billNO);
+        String reqdata = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
+        String mac = appId+"||"+reqdata;
+        mac = DigestUtils.md5Hex(mac.getBytes());
+        params.put("appid",appId);
+        params.put("reqdata",reqdata);
+        params.put("mac",mac);
+
+        HttpPost httpPost = new HttpPost(queryUrl);
+        httpPost.setEntity(assemblyFormEntity(params,"utf-8"));
+        HttpClient httpClient = getHttpClient(queryUrl);
+        HttpResultVo execute = httpClient.execute(httpPost, getResponseHandler());
+        String stringContent = execute.getStringContent();
+        JSONObject jsonObject1 = JSONObject.parseObject(stringContent);
+        log.info("请求结果转json后为:"+jsonObject1);
+        String result = (String) jsonObject1.get("reqdata");
+        return ResponseEntity.ok(result);
+
+    }
+
+    //上传财政电子票据签名文件
+    public ResultVo uploadXml(String orderId, String plain) throws IOException {
+        Map<String, String> params = new HashMap<>();
+
+//        String appid = "A1749891493E4CDDBFE4506357B1F0AB";
+//        String orderUrl = "http://finpt.xjcz.gov.cn/fs-service/fs-pay/uploadXml.do";
+
+        JSONObject jsonObject = new JSONObject();
+        jsonObject.put("orderNo",orderId);
+        jsonObject.put("fileData", Base64.getEncoder().encodeToString(plain.getBytes()));
+
+        String reqdata = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
+        String mac = appId+"||" +reqdata;
+        mac = DigestUtils.md5Hex(mac.getBytes());
+
+        params.put("appid",appId);
+        params.put("reqdata",reqdata);
+        params.put("mac",mac);
+
+        HttpPost httpPost = new HttpPost(uploadXmlUrl);
+        httpPost.setEntity(assemblyFormEntity(params,"utf-8"));
+        HttpClient httpClient = getHttpClient(uploadXmlUrl);
+        HttpResultVo execute = httpClient.execute(httpPost, getResponseHandler());
+        String stringContent = execute.getStringContent();
+        ResultVo resultVo = JSONObject.parseObject(stringContent, ResultVo.class);
+        log.info("请求结果转为:"+resultVo);
+        return resultVo;
+    }
+
+    //获取XML文件字节码
+    public static byte[] convertElementToByteArray(Element element) {
+        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+
+        try {
+            // 设置输出格式
+            OutputFormat format = OutputFormat.createPrettyPrint();
+            format.setEncoding("UTF-8"); // 设置编码为UTF-8
+
+            // 创建 XMLWriter
+            XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8), format);
+
+            // 写入 Element 对象
+            writer.write(element.getDocument());
+            writer.close(); // 关闭 writer,确保所有数据都被写入
+
+        } catch (IOException e) {
+            e.printStackTrace(); // 打印异常信息
+            // 处理异常,比如返回一个空的字节数组或重新抛出异常
+            return new byte[0];
+        }
+
+        // 返回字节数组
+        return byteArrayOutputStream.toByteArray();
+    }
+
+
+    public JSONObject signFileV2(String fileData) throws Exception {
+        JSONObject xysfResult = new JSONObject();
+        String certId = "11650000MB1957293J";
+        MOFSignResult result = null;
+//        Map<String, Object> mmp = new HashMap<>();
+
+        try {
+            String filePath = "F:\\text\\cssconfig.properties";
+            System.out.println("配置文件路径:" + filePath);
+            MOFClient client = new MOFClient(filePath);
+            System.out.println("证书标识为:" + certId);
+            System.out.println("待签名数据:" + fileData);
+            result = client.sign(certId, fileData.getBytes(StandardCharsets.UTF_8));
+            System.out.println("签名返回结果:" + JSONObject.toJSONString(result));
+            byte[] signData = result.getSignData();
+            String base64Str = new String(Base64.getEncoder().encode(signData));
+//            mmp.put("signResult", base64Str);
+            MOFVerifyResult resultVer = client.verifySign(signData, fileData.getBytes(StandardCharsets.UTF_8));
+            System.out.println("验签结果为:" + JSONObject.toJSONString(resultVer));
+//            mmp.put("issure", resultVer.getIssure());
+//            mmp.put("sn", resultVer.getSn());
+//            mmp.put("signTime", resultVer.getSignTime());
+            SignDto signDto = new SignDto(resultVer.getSignTime(),base64Str,resultVer.getIssure(),resultVer.getSn());
+            xysfResult.put("success", Boolean.valueOf(true));
+            xysfResult.put("content", signDto);
+            return xysfResult;
+        } catch (NewCSSException e) {
+            System.out.println("****签名失败****");
+            System.out.println("错误号为:" + e.getCode());
+            System.out.println("错误描述为:" + e.getDescription());
+            xysfResult.put("success", Boolean.valueOf(false));
+            xysfResult.put("msg", "系统错误");
+            return xysfResult;
+        }
+    }
+
+
+
+    //签名
+    public SignResult sign(String strData) {
+        SignResult result = null;
+        String certId = "11650000MB1957293J";
+        try {
+            MOFClient client = new MOFClient("F:\\text\\cssconfig.properties");
+            result = client.sign(certId,strData.getBytes(StandardCharsets.UTF_8));
+            log.info("***签名成功***");
+            log.info("签名返回结果为:"+result);
+            byte[] signData = result.getSignData();
+            String s = new String(Base64.getEncoder().encode(signData));
+            log.info("签名结果为:"+s);
+        } catch (NewCSSException e) {
+            log.info("签名失败");
+            log.info("错误号为:" + e.getCode());
+            log.info("错误描述为: " + e.getDescription());
+            log.info("日志标识码: " + e.getSerialNumber());
+        }
+        return result;
+    }
+
+    /**
+     * 验签名
+     */
+    public MOFVerifyResult verify(byte[] strData,String signData){
+        MOFVerifyResult verify = null;
+        try {
+            MOFClient client = new MOFClient("F:\\text\\cssconfig.properties");
+
+            verify = client.verifySign(strData, signData.getBytes(StandardCharsets.UTF_8));
+            log.info("验签成功");
+            log.info("    证书subjectdn: " + verify.getSubjectdn());
+            log.info("    证书issuer: " + verify.getIssure());
+            log.info("    证书SN: " + verify.getSn());
+            log.info("    证书实体base64: " + verify.getDsCert());
+
+        } catch (NewCSSException e) {
+            log.info("****操作失败****");
+            log.info("错误号为:" + e.getCode());
+            log.info("错误描述为: " + e.getDescription());
+            log.info("日志标识码: " + e.getSerialNumber());
+        }
+        return verify;
+    }
+
+    /**
+     * 制作数字信封
+     */
+    public EnvelopResult encryptEnvelop(byte[] plain){
+        EnvelopResult envelopResult = null;
+        try {
+            AdvanceSignClient client = new AdvanceSignClient("F:\\text\\cssconfig.properties");
+            String certId = "rsa";
+            CertIdParams certIdParams = new CertIdParams(certId);
+            //将封装好的加密证书参数对象放入 数组中
+            CertParams[] envelopCerts =  new CertIdParams[]{certIdParams};
+            /* 制作信封 */
+            envelopResult = client.encryptEnvelop(envelopCerts, plain);
+            byte[] envelopData = envelopResult.getEnvelopData();
+            log.info("信封结果:["+envelopData+"]");
+        } catch (NewCSSException e) {
+            throw new RuntimeException(e);
+        }
+        return envelopResult;
+    }
+
+    /**
+     * 解密数字信封
+     */
+    public DecryptResult decryptEnvelop(String signData){
+        DecryptResult result = null;
+        try {
+            AdvanceSignClient client = new AdvanceSignClient("F:\\text\\cssconfig.properties");
+            byte[] enc_data = signData.getBytes();
+            result = client.decryptEnvelop(enc_data);
+            log.info("解密数字信封结果成功");
+            String plainData = new String(result.getPlainData());
+            log.info("原文:"+plainData);
+            log.info("    证书subjectdn: " + result.getSubjectdn());
+            log.info("    证书issuer: " + result.getIssure());
+            log.info("    证书SN: " + result.getSn());
+            log.info("    证书实体base64: " + result.getDsCert());
+
+        } catch (NewCSSException e) {
+            log.info("****操作失败****");
+            log.info("错误号为:" + e.getCode());
+            log.info("错误描述为: " + e.getDescription());
+            log.info("日志标识码: " + e.getSerialNumber());
+        }
+        return result;
+    }
+
+
+
+
+
+
+
+
+
 }

--
Gitblit v1.9.2