无关风月
2025-05-08 9486766c806fe1d9e082b2fd02ea1cc558f1b443
cloud-server-management/src/main/java/com/dsh/guns/modular/system/util/PayMoneyUtil.java
@@ -12,6 +12,9 @@
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsh.course.util.UUIDUtil;
import com.dsh.guns.modular.system.controller.util.HttpClientUtil;
import com.dsh.guns.modular.system.controller.util.MD5AndKL;
import com.dsh.guns.modular.system.model.OperatorAuthAlipay;
import com.dsh.guns.modular.system.model.OperatorUser;
import com.dsh.guns.modular.system.service.IOperatorAuthService;
@@ -22,11 +25,18 @@
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;
import static com.dsh.guns.modular.system.controller.util.MD5AndKL.byteArrayToHexString;
/**
 * 第三方支付工具类
 */
@@ -40,15 +50,17 @@
    private String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmu8n/4yTHWbn7VOrNc9OsLtDL1bEQ8gC1dHkj8Wy5z0mkaOsjJRIG/28ze12M0V8jdCKuuDr5Z1OPKiqf+XO3ypguEh+mYUVMBM/cZodDFQfTY1TKLWjvQCuaqlA+QUTCK6f7T7stsgyQ1o9Jj0rXZDz6PM4QHSTzjrLIBaeqM5WIBvH+fy/X+QG5Utd+/UT0kc0JyvuKhZ65yVUd/C9VcwJJAPliRsAQNrqYterwAJ9zvw9tF11wj9W0XgJ8Ccu4x3gR1vrlLRJJo/OA97RmxPQ+5hSacWQZCUd1dwiBq+YCrKVHGTj14izRHXrLc0yBlRXo7tBOIqcy3IsvKVthQIDAQAB";//支付宝支付公钥
    private String appid = "";//微信appid
    private String smid = "2088330203191220";//平台支付宝商户号...
    private String appletsAppid = "";//微信小程序appid
    private String appid = "wx41d32f362ba0f911";//微信appid
    private String mchId = "";//微信商户号
    private String appSecret = "cf0ebf950f5926a69041a0e2bbe20f3e";
    private String key = "";//微信商户号
    private String mchId = "1501481761";//微信商户号
    private String callbackPath = "http://221.182.45.100:56666/account";//支付回调网关地址
    private String key = "6f5e0c2dcabfa9c27b5da5836a362fef";//微信商户号
    private String callbackPath = "https://online.daowepark.com:443/account";//支付回调网关地址
    private String app_cert_path = "C:/cert/alipay/user/app_cert_path.crt";//应用公钥证书路径
@@ -56,7 +68,7 @@
    private String alipay_root_cert_path = "C:/cert/alipay/user/alipay_root_cert_path.crt";//支付宝CA根证书文件路径
    private String certPath = "C:\\cert\\1523106371_20211206_cert\\apiclient_cert.p12";//微信证书
    private String certPath = "/usr/playpai/cert/weixin/apiclient_cert.p12";//微信证书
    String signType =  "RSA2" ;
    String serverHost =  "openchannel.alipay.com" ;
@@ -65,8 +77,268 @@
    @Autowired
    private IOperatorUserService operatorUserService;
    /**
     * 添加分账接收方
     * @param number 商户号或者openId
     * @param name 商户全称或者个人姓名
     * @return
     */
    public ResultUtil addReceiver(String number,String name) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("mch_id", mchId);
        map.put("appid", appid);
        String nonce_str = UUIDUtil.getRandomCode(16);
        map.put("nonce_str", nonce_str);
        // 将这个字符串使用json格式拼接起来
        Map<String, Object> body = new HashMap<>();
        body.put("type", "MERCHANT_ID");
        body.put("account", number);
        body.put("name", name);
        body.put("relation_type", "PARTNER");
        JSONObject jsonObject = new JSONObject(body);
        String jsonString = jsonObject.toString();
        map.put("receiver",jsonString );
        String s = this.weixinSignature(map);
        map.put("sign", s);
        String url = "https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver";
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        StringBuffer xmlString = new StringBuffer();
        Set<String> strings = map.keySet();
        String[] keys = {};
        keys = strings.toArray(keys);
        Arrays.sort(keys);
        xmlString.append("<xml>");
        for (int l = 0; l < keys.length; l++) {
            xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">");
        }
        xmlString.append("</xml>");
        Map<String, String> map1 = null;
        String body1 = null;
        try {
            body1 = HttpClientUtil.pushHttpRequsetXml(url, xmlString.toString(), new HashMap<>()).getData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将结果xml解析成map
        body1 = body1.replaceAll("<!\\[CDATA\\[", "");
        body1 = body1.replaceAll("]]>", "");
        try {
            map1 = this.xmlToMap(body1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String return_code = map1.get("return_code");
        if ("SUCCESS".equals(return_code)) {
            String result_code = map1.get("result_code");
            if ("SUCCESS".equals(result_code)) {
                return ResultUtil.success();
            } else {
//                System.err.println(map1.get("err_code_des"));
                return ResultUtil.error(map1.get("err_code_des"));
            }
        } else {
//            System.err.println(map1.get("return_msg") + appid + "----" + mchId);
            return ResultUtil.error(map1.get("return_msg"), new JSONObject());
        }
    }
    /**
     * 发起分账
     * @param order 微信订单号
     * @return
     */
    public ResultUtil fenzhang(String order) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("mch_id", mchId);
        map.put("appid", appid);
        String nonce_str = UUIDUtil.getRandomCode(16);
        map.put("nonce_str", nonce_str);
        map.put("transaction_id", order);
        // 将这个字符串使用json格式拼接起来
        Map<String, Object> body = new HashMap<>();
        body.put("type", "MERCHANT_ID");
        // todo 分账接收方 计算分账金额
        body.put("account", "1233");
        body.put("amount", "0");
        body.put("description", "订单分账");
        JSONObject jsonObject = new JSONObject(body);
        String jsonString = jsonObject.toString();
        map.put("receiver",jsonString);
        String s = this.weixinSignature(map);
        map.put("sign", s);
        String url = "https://api.mch.weixin.qq.com/secapi/pay/profitsharing";
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        StringBuffer xmlString = new StringBuffer();
        Set<String> strings = map.keySet();
        String[] keys = {};
        keys = strings.toArray(keys);
        Arrays.sort(keys);
        xmlString.append("<xml>");
        for (int l = 0; l < keys.length; l++) {
            xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">");
        }
        xmlString.append("</xml>");
        Map<String, String> map1 = null;
        String body1 = null;
        try {
            body1 = HttpClientUtil.pushHttpRequsetXml(url, xmlString.toString(), new HashMap<>()).getData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将结果xml解析成map
        body1 = body1.replaceAll("<!\\[CDATA\\[", "");
        body1 = body1.replaceAll("]]>", "");
        try {
            map1 = this.xmlToMap(body1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String return_code = map1.get("return_code");
        if ("SUCCESS".equals(return_code)) {
            String result_code = map1.get("result_code");
            if ("SUCCESS".equals(result_code)) {
                return ResultUtil.success();
            } else {
//                System.err.println(map1.get("err_code_des"));
                return ResultUtil.error(map1.get("err_code_des"));
            }
        } else {
//            System.err.println(map1.get("return_msg") + appid + "----" + mchId);
            return ResultUtil.error(map1.get("return_msg"), new JSONObject());
        }
    }
    /**
     * 删除分账接收方
     * @param number 商户号或者openId
     * @param name 商户全称或者个人姓名
     * @return
     */
    public ResultUtil deleteReceiver(String number,String name) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("mch_id", mchId);
        map.put("appid", appid);
        String nonce_str = UUIDUtil.getRandomCode(16);
        map.put("nonce_str", nonce_str);
        // 将这个字符串使用json格式拼接起来
        Map<String, Object> body = new HashMap<>();
        body.put("type", "MERCHANT_ID");
        body.put("account", number);
        body.put("name", name);
        body.put("relation_type", "PARTNER");
        JSONObject jsonObject = new JSONObject(body);
        String jsonString = jsonObject.toString();
        map.put("receiver",jsonString );
        String s = this.weixinSignature(map);
        map.put("sign", s);
        String url = "https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver";
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        StringBuffer xmlString = new StringBuffer();
        Set<String> strings = map.keySet();
        String[] keys = {};
        keys = strings.toArray(keys);
        Arrays.sort(keys);
        xmlString.append("<xml>");
        for (int l = 0; l < keys.length; l++) {
            xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">");
        }
        xmlString.append("</xml>");
        Map<String, String> map1 = null;
        String body1 = null;
        try {
            body1 = HttpClientUtil.pushHttpRequsetXml(url, xmlString.toString(), new HashMap<>()).getData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将结果xml解析成map
        body1 = body1.replaceAll("<!\\[CDATA\\[", "");
        body1 = body1.replaceAll("]]>", "");
        try {
            map1 = this.xmlToMap(body1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String return_code = map1.get("return_code");
        if ("SUCCESS".equals(return_code)) {
            String result_code = map1.get("result_code");
            if ("SUCCESS".equals(result_code)) {
                return ResultUtil.success();
            } else {
//                System.err.println(map1.get("err_code_des"));
                return ResultUtil.error(map1.get("err_code_des"));
            }
        } else {
//            System.err.println(map1.get("return_msg") + appid + "----" + mchId);
            return ResultUtil.error(map1.get("return_msg"), new JSONObject());
        }
    }
    /**
     * 微信下单的签名算法
     *
     * @param map
     * @return
     */
    private String weixinSignature(Map<String, Object> map) {
        try {
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(entries);
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    Object val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            sb.append("key=" + key);
            String sign = sha256_HMAC(sb.toString(), key).toUpperCase();
            return sign;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * sha256_HMAC加密
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public  String sha256_HMAC(String message, String secret) {
        String hash = "";
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
            hash = byteArrayToHexString(bytes);
        } catch (Exception e) {
            System.out.println("Error HmacSHA256 ===========" + e.getMessage());
        }
        return hash;
    }
    /**
     * 处理直付通审核通过和拒绝消息