微信支付

controller

@Slf4j
@RestController
@RequestMapping("test")
public class TestController {


    @Autowired
    private PayService payService;

    @ApiOperation(value = "付款码收款(扫客户)-服务费管理,需要服务费查询的参数外加收款的快递公司参数", notes = "已安全检查")
    @PostMapping("/serviceFeeManagement/toPayment")
    public Object toPayment(@RequestBody LittleBeeDTO json, HttpServletRequest req) {
        Map map2 = new HashMap(8);
        map2.put("mchId", "aaa");//商户号
        map2.put("key", "aaa");//秘钥
        map2.put("orderNo", "aaa");//订单号
        map2.put("money", 100);//金额
        map2.put("authCode", ""); //授权码
        Object o = payService.toPayment(map2);
        Re.success("ss", o);
        return o;
    }

}

service

package com.cc.service.impl;


import com.cc.model.dto.Re;

import java.util.Map;


public interface PayService {

    /**
     * 付款码支付
     *
     * @param map
     * @return
     */
    Re toPayment(Map<String, Object> map);

    /**
     * 扫码支付
     *
     * @param map
     * @return
     */
    Re sweepCodePayment(Map<String, Object> map);

    /**
     * 查询订单状态
     *
     * @param map
     * @return
     */
    Re queryOrderState(Map<String, Object> map);
}

serviceImpl

package com.cc.service.impl;

import com.cc.model.dto.*;
import com.cc.utils.OkHttp3Utils;
import com.cc.utils.WeChatPayUtils;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @Author: 01383474
 * @Date: 2019/6/17 9:37
 */
@Component
@Slf4j
@Service
public class PayServiceImpl implements PayService {


    @Autowired
    private WeChatPayUtils wxPayUtil;

    final String str = "butler-sit";

    @Value("${wechat.callbackUrl}")
    private String weChatCallbackUrl;

    @Value("${wechat.appId}")
    private String weChatAppId;

    @Value("${wechat.mchId}")
    private String weChatMchId;

    @Value("${wechat.key}")
    private String weChatKey;


    /**
     * 付款码支付  mchId:商户号;orderNo:订单号;total_fee:金额;authCode:授权码(前端扫描用户二维码获得);key:秘钥;certificate:证书
     *
     * @param map orderRespose:返回对象
     * @return
     */
    @Override
    public Re toPayment(Map<String, Object> map) {
        Map<String, String> requestMap = new HashMap<String, String>(16);

        //小程序appid
        String appId = weChatAppId;
        requestMap.put("appid", appId);
        //商户号
        String mchId = null;
        //秘钥
        String key = null;
        // appid:公众号ID;total_fee:总金额
        String callbackUrl = weChatCallbackUrl;
        if (callbackUrl.contains(str)) {
            //商户号
            mchId = weChatMchId;
            requestMap.put("mch_id", mchId);
            key = weChatKey;

        } else {
            //商户号
            mchId = map.get("mchId").toString();
            requestMap.put("mch_id", map.get("mchId").toString());
            //秘钥
            key = map.get("key").toString();
        }
        //订单金额
        requestMap.put("total_fee", map.get("money").toString());
        //随机字符串
        String noncestr = WeChatPayUtils.generateNonceStr();
        requestMap.put("nonce_str", noncestr);

        //商品描述 订单号
        requestMap.put("body", "付款码支付");
        //商户订单号
        String orderNo = map.get("orderNo") + "";
        requestMap.put("out_trade_no", orderNo);
        //用户端Ip地址
        String createIp = "";
        try {
            InetAddress addr = InetAddress.getLocalHost();
            //获取本机ip
            createIp = addr.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        requestMap.put("spbill_create_ip", createIp);

        //授权码
        requestMap.put("auth_code", map.get("authCode").toString());
        //签名类型
        requestMap.put("sign_type", "HMAC-SHA256");

        //签名
        String sign = null;

        try {
            sign = wxPayUtil.generateSignature(requestMap, key);
        } catch (Exception e) {
            throw new RuntimeException("生成签名错误");
        }
        requestMap.put("sign", sign);

        log.info("请求付款码支付接口参数requestMap:" + requestMap.toString());

        PaymentCodeDTO paymentCodeDTO = null;
        try {
            paymentCodeDTO = new PaymentCodeDTO();
            BeanUtils.populate(paymentCodeDTO, requestMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 请求的xml数据
        XStream xStream = new XStream();

        // to be removed after 1.5 用于处理1.4.10 xstream is probably vulnerable问题
        XStream.setupDefaultSecurity(xStream);
        xStream.allowTypesByWildcard(new String[]{
                "com.sf.sfkdgj.service.impl.**"
        });

        xStream.alias("xml", PaymentCodeDTO.class);
        String xml = xStream.toXML(paymentCodeDTO);
        String xmlToString = xml.replace("__", "_");
        log.info("付款码支付请求参数为-----------:" + xmlToString);

        UnifiedPayResposeDTO unifiedPayResposeDTO = WeChatPayUtils.httpOrder(xmlToString, WeChatConstant.TOPAYMENT_URL);

        String returnCode = "SUCCESS";
        String resultCode = "SUCCESS";
        String userPaying = "USERPAYING";
        log.info("付款码支付返回的xml转换为对象:" + unifiedPayResposeDTO.toString());
        Map<String, Object> map1 = new HashMap<>(16);
        map1.put("orderRespose", unifiedPayResposeDTO);
        try {
            if (returnCode.equals(unifiedPayResposeDTO.getReturn_code()) && resultCode.equals(unifiedPayResposeDTO.getResult_code())) {
                log.info("*******付款码**********" + "接口请求成功!");
                log.info("unifiedPayResposeDTO------------:" + unifiedPayResposeDTO.toString());
                return Re.success(map1);
            } else if (userPaying.equals(unifiedPayResposeDTO.getErr_code())) {
                UnifiedPayResposeDTO unifiedPayResposeDTO1 = null;
                int num = 3;
                for (int i = 0; i < num; i++) {
                    Thread.sleep(10000);
                    Map<String, String> data = new HashMap<>(16);
                    data.put("appid", appId);
                    data.put("mch_id", mchId);
                    String noncestr1 = WeChatPayUtils.generateNonceStr();
                    data.put("nonce_str", noncestr1);
                    data.put("out_trade_no", map.get("orderNo").toString());//签名类型
                    data.put("sign_type", "HMAC-SHA256");
                    //签名
                    String sign1 = null;
                    try {
                        sign1 = wxPayUtil.generateSignature(data, key);
                    } catch (Exception e) {
                        throw new RuntimeException("生成签名错误");
                    }
                    data.put("sign", sign1);
                    // 请求的xml数据

                    // 请求的xml数据
                    QueryOrderStateDTO queryOrderStateDTO = null;
                    try {
                        queryOrderStateDTO = new QueryOrderStateDTO();
                        BeanUtils.populate(queryOrderStateDTO, data);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }

                    XStream xStream1 = new XStream();

                    // to be removed after 1.5 用于处理1.4.10 xstream is probably vulnerable问题
                    XStream.setupDefaultSecurity(xStream1);
                    xStream1.allowTypesByWildcard(new String[]{
                            "com.sf.sfkdgj.service.impl.**"
                    });

                    xStream1.alias("xml", QueryOrderStateDTO.class);
                    String xml1 = xStream1.toXML(queryOrderStateDTO);
                    String xmlToString1 = xml1.replace("__", "_");
                    log.info("付款码支付请求参数为-----------:" + xmlToString1);

                    unifiedPayResposeDTO1 = WeChatPayUtils.httpOrder(xmlToString1, WeChatConstant.QUERYORDER_URL);
                    if (resultCode.equals(unifiedPayResposeDTO1.getTrade_state())) {
                        log.info("微信加密支付成功!");
                        return Re.success(map1);
                    }
                    log.info("正在支付" + unifiedPayResposeDTO1);
                }
                unifiedPayResposeDTO1.setReturn_msg("支付时间超时,请重新支付");
                map1.put("orderRespose", unifiedPayResposeDTO1);
                return Re.error(map1, "支付时间超时,请重新支付");
            }


            return Re.error(map1, unifiedPayResposeDTO.getErr_code_des());

        } catch (Exception e) {
            String text = "调用微信支付出错,返回状态码:" + unifiedPayResposeDTO.getReturn_code() + ",返回信息:" + unifiedPayResposeDTO.getResult_code();
            if (unifiedPayResposeDTO.getErr_code() != null && !"".equals(unifiedPayResposeDTO.getErr_code())) {
                text = text + ",错误码:" + unifiedPayResposeDTO.getErr_code() + ",错误描述:" + unifiedPayResposeDTO.getErr_code_des();

            }
            log.info("*******付款码支付失败**********" + text);
            map1.put("responseMap", unifiedPayResposeDTO);
            log.info("支付失败参数responseMap:" + unifiedPayResposeDTO.toString());
            return Re.error(map1, unifiedPayResposeDTO.getErr_code_des());
        }

    }

    /**
     * 撤销订单
     *
     * @param certificateToString
     * @param mchId
     * @param certificate
     */
    private void reverseOrder(String certificateToString, String mchId, String certificate) {
        try {
            reverseOrder(certificateToString, mchId, certificate);

            HttpPost httpPost = new HttpPost(WeChatConstant.REVERSE_URL);

            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(8000).setConnectTimeout(8000).build();
            httpPost.setConfig(requestConfig);

            StringEntity postEntity = new StringEntity(certificateToString, "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.addHeader("User-Agent", WeChatConstant.USER_AGENT + " " + mchId);
            httpPost.setEntity(postEntity);
            CloseableHttpClient httpClient = OkHttp3Utils.createCloseableHttpClient(mchId, certificate);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");
            log.info(result);
            //5.将返回的xml转换为map
            Map<String, String> responseMap = WeChatPayUtils.xmlStr2Map(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 扫码支付  money:金额;mchId:商户号;key:秘钥;orderNo:订单号
     *
     * @param map
     * @return
     */
    @Override
    public Re sweepCodePayment(Map<String, Object> map) {
        Map<String, String> requestMap = new HashMap<String, String>(16);

        //小程序appid
        String appId = weChatAppId;
        requestMap.put("appid", appId);
        //商户号
        String mchId = null;
        //秘钥
        String key = null;

        String callbackUrl = weChatCallbackUrl;
        // appid:公众号ID;total_fee:总金额
        if (callbackUrl.contains(str)) {
            //商户号
            mchId = weChatMchId;
            requestMap.put("mch_id", mchId);
            //秘钥
            key = weChatKey;
        } else {

            //商户号
            mchId = map.get("mchId").toString();
            requestMap.put("mch_id", mchId);
            //秘钥
            key = map.get("key").toString();
        }
        //订单金额
        requestMap.put("total_fee", map.get("money").toString());

        //随机字符串
        String noncestr = WeChatPayUtils.generateNonceStr();
        requestMap.put("nonce_str", noncestr);

        //商品描述 订单号
        requestMap.put("body", "扫码支付");
        //商户订单号
        String orderNo = String.valueOf(map.get("orderNo"));
        requestMap.put("out_trade_no", orderNo);

        //用户端Ip地址
        String createIp = "";
        try {
            InetAddress addr = InetAddress.getLocalHost();
            //获取本机ip
            createIp = addr.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        requestMap.put("spbill_create_ip", createIp);

        //通知地址
        requestMap.put("notify_url", callbackUrl);
        //交易类型
        requestMap.put("trade_type", "NATIVE");
        //签名类型
        requestMap.put("sign_type", "HMAC-SHA256");

        //签名
        String sign = null;

        try {
            sign = wxPayUtil.generateSignature(requestMap, key);
        } catch (Exception e) {
            throw new RuntimeException("生成签名错误");
        }
        requestMap.put("sign", sign);

        log.info("请求付款码支付接口参数requestMap:" + requestMap.toString());

        // 请求的xml数据
        SweepCodeDTO sweepCodeDTO = null;
        try {
            sweepCodeDTO = new SweepCodeDTO();
            BeanUtils.populate(sweepCodeDTO, requestMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        XStream xStream = new XStream();

        // to be removed after 1.5 用于处理1.4.10 xstream is probably vulnerable问题
        XStream.setupDefaultSecurity(xStream);
        xStream.allowTypesByWildcard(new String[]{
                "com.sf.sfkdgj.service.impl.**"
        });

        xStream.alias("xml", SweepCodeDTO.class);
        String xml = xStream.toXML(sweepCodeDTO);
        String xmlToString = xml.replace("__", "_");
        log.info("付款码支付请求参数为-----------:" + xmlToString);

        UnifiedPayResposeDTO unifiedPayResposeDTO = WeChatPayUtils.httpOrder(xmlToString, WeChatConstant.UNIFIEDORDER_URL);
        Map<String, Object> map1 = new HashMap<>(16);
        map1.put("unifiedPayRespose", unifiedPayResposeDTO);
        // 根据微信文档return_code 和result_code都为SUCCESS的时候才会返回code_url
        if (null != unifiedPayResposeDTO && WeChatConstant.SUCCESS.equals(unifiedPayResposeDTO.getReturn_code()) && WeChatConstant.SUCCESS.equals(unifiedPayResposeDTO.getResult_code())) {
            String timestamp = String.valueOf(WeChatPayUtils.getCurrentTimestamp());

            map1.put("unifiedPayRespose", unifiedPayResposeDTO);
            SortedMap<String, String> packageParams = new TreeMap<String, String>();
            packageParams.put("appId", appId);
            packageParams.put("signType", "HMACSHA256");
            packageParams.put("nonceStr", noncestr);
            packageParams.put("timeStamp", timestamp);
            String packages = "prepay_id=" + unifiedPayResposeDTO.getPrepay_id();
            packageParams.put("package", packages);
            String sign1 = null;
            try {
                sign1 = wxPayUtil.generateSignature(packageParams, key);

            } catch (Exception e) {
                log.info("生成签名错误");
                return Re.error(map1, "生成签名错误");
            }
            if (sign1 != null && !"".equals(sign1)) {
                log.info("成功!");
                return Re.success(map1);

            } else {
                return Re.error(map1, "生成签名失败");
            }
        } else { // 不成功
            String text = "调用微信扫码支付出错,返回状态码:" + unifiedPayResposeDTO.getReturn_code() + ",返回信息:" + unifiedPayResposeDTO.getReturn_msg();
            if (unifiedPayResposeDTO.getErr_code() != null && !"".equals(unifiedPayResposeDTO.getErr_code())) {
                text = text + ",错误码:" + unifiedPayResposeDTO.getErr_code() + ",错误描述:" + unifiedPayResposeDTO.getErr_code_des();
            }

            log.info("*******微信扫码支付失败**********" + text);

            return Re.error(map1, unifiedPayResposeDTO.getErr_code_des());
        }
    }

    /**
     * 查询订单状态
     *
     * @param map
     * @return
     */
    @Override
    public Re queryOrderState(Map<String, Object> map) {

        Map<String, String> requestMap = new HashMap<String, String>(16);
        //小程序appid
        String appId = weChatAppId;
        requestMap.put("appid", appId);
        //商户号
        String mchId = null;
        //秘钥
        String key = null;

        String callbackUrl = weChatCallbackUrl;
        // appid:公众号ID;total_fee:总金额
        if (callbackUrl.contains(str)) {
            //商户号
            mchId = weChatMchId;
            requestMap.put("mch_id", mchId);
            requestMap.put("total_fee", "1");
            //秘钥
            key = weChatKey;
        } else {

            requestMap.put("total_fee", map.get("money").toString());
            //商户号
            mchId = map.get("mchId").toString();
            requestMap.put("mch_id", mchId);
            //秘钥
            key = map.get("key").toString();
        }

        Map<String, String> data = new HashMap<>(16);
        data.put("appid", appId);
        data.put("mch_id", mchId);
        String noncestr1 = WeChatPayUtils.generateNonceStr();
        data.put("nonce_str", noncestr1);
        data.put("out_trade_no", map.get("orderNo").toString());//签名类型
        data.put("sign_type", "HMAC-SHA256");
        //签名
        String sign1 = null;
        try {
            sign1 = wxPayUtil.generateSignature(data, key);
        } catch (Exception e) {
            throw new RuntimeException("生成签名错误");
        }
        data.put("sign", sign1);
        // 请求的xml数据

        // 请求的xml数据
        QueryOrderStateDTO queryOrderStateDTO = null;
        try {
            queryOrderStateDTO = new QueryOrderStateDTO();
            BeanUtils.populate(queryOrderStateDTO, data);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        XStream xStream = new XStream();

        // to be removed after 1.5 用于处理1.4.10 xstream is probably vulnerable问题
        XStream.setupDefaultSecurity(xStream);
        xStream.allowTypesByWildcard(new String[]{
                "com.sf.sfkdgj.service.impl.**"
        });

        xStream.alias("xml", QueryOrderStateDTO.class);
        String xml = xStream.toXML(queryOrderStateDTO);
        String xmlToString = xml.replace("__", "_");
        log.info("付款码支付请求参数为-----------:" + xmlToString);
        UnifiedPayResposeDTO unifiedPayResposeDTO = WeChatPayUtils.httpOrder(xmlToString, WeChatConstant.QUERYORDER_URL);
        Map<String, Object> map1 = new HashMap<>(16);
        map1.put("unifiedPayRespose", unifiedPayResposeDTO);
        if (null != unifiedPayResposeDTO && WeChatConstant.SUCCESS.equals(unifiedPayResposeDTO.getReturn_code())) {
            return Re.success(map1);
        } else {
            String text = "调用微信扫码支付出错,返回状态码:" + unifiedPayResposeDTO.getReturn_code() + ",返回信息:" + unifiedPayResposeDTO.getReturn_msg();
            if (unifiedPayResposeDTO.getErr_code() != null && !"".equals(unifiedPayResposeDTO.getErr_code())) {
                text = text + ",错误码:" + unifiedPayResposeDTO.getErr_code() + ",错误描述:" + unifiedPayResposeDTO.getErr_code_des();
                log.info("*******微信扫码支付失败**********" + text);
            }
            return Re.error(map1, unifiedPayResposeDTO.getErr_code_des());
        }


    }


    /**
     * 支付成功回调接口
     *
     * @param request
     * @return
     * @throws Exception
     */
    public String callback(HttpServletRequest request) throws Exception {
        log.info("进入接口callback");
        ServletInputStream instream = null;
        StringBuffer sb = new StringBuffer();
        Map<String, String> returnData = new HashMap<String, String>(4);
        try {
            instream = request.getInputStream();
            int len = -1;
            byte[] buffer = new byte[1024];
            while ((len = instream.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, len));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("读取微信请求参数错误");
        } finally {
            instream.close();
        }
        // 接受微信的回调的通知参数
        Map<String, String> map = WeChatPayUtils.xmlStr2Map(sb.toString());
        //log.info("支付返回值为" + map.toString());
        //处理数据
        if (map != null) {
            String outTradeNo = map.get("out_trade_no");
            // 支付openid
            String openid = map.get("openid");
            //订单费用
            BigDecimal money = new BigDecimal(map.get("total_fee")).divide(new BigDecimal("100"));
        }


        String xml = WeChatPayUtils.GetMapToXml(returnData);
        log.info("不可以");
        log.info(xml);
        return xml;

    }


}

WeChatConstant

package com.cc.model.dto;

import org.apache.http.client.HttpClient;


public class WeChatConstant {
    public static final String ZERO = "0";
    public static final String ONE = "1";
    public static final String NULL = "null";
    public static final String DETAIL = "TestDetail";
    public static final String SUCCESS = "SUCCESS";
    public static final String FAIL = "FAIL";
    public static final String OK = "OK";
    public static final String WXPAYSDK_VERSION = "WXPaySDK/3.0.9";
    public static final String USER_AGENT = WXPAYSDK_VERSION +
            " (" + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version") +
            ") Java/" + System.getProperty("java.version") + " HttpClient/" + HttpClient.class.getPackage().getImplementationVersion();

    public static final String FENZ_URL ="https://api.mch.weixin.qq.com/secapi/pay/profitsharing";

    public static final String TOPAYMENT_URL = "https://api.mch.weixin.qq.com/pay/micropay";
    public static final String QUERYORDER_URL = "https://api.mch.weixin.qq.com/pay/orderquery";
    public static final String REVERSE_URL = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
    public static final String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    /**
     * 微信分账返回参数
     */
    public static final String RETURN_CODE ="return_code";
    public static final String RETURN_MSG ="return_msg";
    public static final String RESULT_CODE ="result_code";
    public static final String ERR_CODE ="err_code";
    public static final String ERR_CODE_DES ="err_code_des";
    public static final String MCH_ID ="mch_id";
    public static final String SUB_MCH_ID ="sub_mch_id";
    public static final String APPID ="appid";
    public static final String SUB_APPID ="sub_appid";
    public static final String NONCE_STR ="nonce_str";
    public static final String SIGN ="sign";
    public static final String TRANSACTION_ID ="transaction_id";
    public static final String OUT_ORDER_NO ="out_order_no";
    public static final String ORDER_ID ="order_id";


    /**
     * 工具类整合
     */
    public enum SignType {
        /**
         * 签名标志
         */
        MD5,
        /**
         * 签名标志
         */
        HMACSHA256
    }
    // 测试号--------------------------------------------------------------------

    // 测试环境微信开发者id
	/*public static final String TEST_APP_ID = "wxdb995bfcf7625e3f";
	// 测试环境微信开发者密钥
	public static final String TEST_APPSECRET = "05638854000fc90232f36d782e10a7a9";
	// 测试环境微信开发者token
	public static final String TEST_TOKEN = "dongluda";
	// 测试环境下单页面url
	public static final String TEST_ORDERS_URL = "http://dongluda.natapp1.cc/index.html%23/storageOrderConfirm";
	// 测试环境查询页面url
	public static final String TEST_QUERY_URL = "https://hbjjq.sf-express.com/traffic/index.html%23/query";*/

    // 常用--------------------------------------------------------------------
    /**
     * cc 公众账号开发者ID
     */
    public static final String APP_ID = "wx485a4fb5bd28a751";
    /**
     * c 公众账号开发者密码
     */
    public static final String APP_SECRET = "a6792f30037cf7efaa02748df188d369";
    /**
     * cc token
     */
    public static final String TOKEN = "jishipei";
    /**
     * api证书路径
     */
    public static final String CERTIFICATE_PATH="C:/tools/apiclient_cert.p12";

    public static final String REFUND_URL ="https://api.mch.weixin.qq.com/secapi/pay/refund";
    /**
     * 系统地址
     */
    public static final String BASE_URL = "http://weixin.xinfor.com";

    // url--------------------------------------------------------------------

    /**
     * 微信公众号创建自定义菜单url
     */
    public static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";

    /**
     * 模板消息相关--------------------------------------------------------------------
     * 支付成功通知消息模板id
     */
    public static final String PAY_SUCCESS_MESSAGE_ID = "rVUVeBgQI8LalswUQ9NiaQ_8OZBM8nge35wzVYOeDkA";
    /**
     * 发送模板消息url,需要追加accessToken。
     */
    public static final String SEND_TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

    /**
     * 其他--------------------------------------------------------------------
     */
    public static final String DOMAIN_API = "api.mch.weixin.qq.com";
    public static final String DOMAIN_API2 = "api2.mch.weixin.qq.com";
    public static final String DOMAIN_APIHK = "apihk.mch.weixin.qq.com";
    public static final String DOMAIN_APIUS = "apius.mch.weixin.qq.com";

    public static final String HMACSHA256 = "HMAC-SHA256";
    public static final String MD5 = "MD5";

    public static final String FIELD_SIGN = "sign";
    public static final String FIELD_SIGN_TYPE = "sign_type";

    public static final String MICROPAY_URL_SUFFIX = "/pay/micropay";
    public static final String UNIFIEDORDER_URL_SUFFIX = "/pay/unifiedorder";
    public static final String ORDERQUERY_URL_SUFFIX = "/pay/orderquery";
    public static final String REVERSE_URL_SUFFIX = "/secapi/pay/reverse";
    public static final String CLOSEORDER_URL_SUFFIX = "/pay/closeorder";
    public static final String REFUND_URL_SUFFIX = "/secapi/pay/refund";
    public static final String REFUNDQUERY_URL_SUFFIX = "/pay/refundquery";
    public static final String DOWNLOADBILL_URL_SUFFIX = "/pay/downloadbill";
    public static final String REPORT_URL_SUFFIX = "/payitil/report";
    public static final String SHORTURL_URL_SUFFIX = "/tools/shorturl";
    public static final String AUTHCODETOOPENID_URL_SUFFIX = "/tools/authcodetoopenid";


    public static final String SANDBOX_MICROPAY_URL_SUFFIX = "/sandboxnew/pay/micropay";
    public static final String SANDBOX_UNIFIEDORDER_URL_SUFFIX = "/sandboxnew/pay/unifiedorder";
    public static final String SANDBOX_ORDERQUERY_URL_SUFFIX = "/sandboxnew/pay/orderquery";
    public static final String SANDBOX_REVERSE_URL_SUFFIX = "/sandboxnew/secapi/pay/reverse";
    public static final String SANDBOX_CLOSEORDER_URL_SUFFIX = "/sandboxnew/pay/closeorder";
    public static final String SANDBOX_REFUND_URL_SUFFIX = "/sandboxnew/secapi/pay/refund";
    public static final String SANDBOX_REFUNDQUERY_URL_SUFFIX = "/sandboxnew/pay/refundquery";
    public static final String SANDBOX_DOWNLOADBILL_URL_SUFFIX = "/sandboxnew/pay/downloadbill";
    public static final String SANDBOX_REPORT_URL_SUFFIX = "/sandboxnew/payitil/report";
    public static final String SANDBOX_SHORTURL_URL_SUFFIX = "/sandboxnew/tools/shorturl";
    public static final String SANDBOX_AUTHCODETOOPENID_URL_SUFFIX = "/sandboxnew/tools/authcodetoopenid";


}

PaymentCodeDTO

package com.cc.model.dto;

import lombok.Data;


@Data
public class PaymentCodeDTO {
    /**
     * 公众号appid
     */
    private String appid;
    /**
     * 商户号
     */
    private String mch_id;
    /**
     * 金额
     */
    private String total_fee;
    /**
     * 随机字符串
     */
    private String nonce_str;
    /**
     * 商品描述
     */
    private String body;
    /**
     * 商户订单号
     */
    private String out_trade_no;
    /**
     * 用户端Ip地址
     */
    private String spbill_create_ip;
    /**
     * 授权码
     */
    private String auth_code;
    /**
     * 签名
     */
    private String sign;
    /**
     * 签名类型
     */
    private String sign_type;
}

QueryOrderStateDTO

package com.cc.model.dto;

import lombok.Data;


@Data
public class QueryOrderStateDTO {
    /**
     * 公众号appid
     */
    private String appid;
    /**
     * 商户号
     */
    private String mch_id;
    /**
     * 商户订单号
     */
    private String out_trade_no;
    /**
     * 随机字符串
     */
    private String nonce_str;
    /**
     * 签名
     */
    private String sign;
    /**
     * 签名类型
     */
    private String sign_type;

}

Re

package com.cc.model.dto;


import com.cc.model.ResponseConstant;

/**
 * 响应结构
 */
public class Re<T> {


    private Integer status;


    private String msg;

    private T data;

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Re(Integer status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public Re(T data) {
        this.status = ResponseConstant.SUCCESS_STATUS;
        this.msg = ResponseConstant.SUCCESS_MSG;
        this.data = data;
    }

    public Re() {
        this.status = ResponseConstant.ERROR_STATUS;
        this.msg = "error";
        this.data = null;
    }

    public static <T> Re<T> success() {
        return new Re<T>(ResponseConstant.SUCCESS_STATUS, ResponseConstant.SUCCESS_MSG, null);
    }

    public static <T> Re<T> success(T data) {
        return new Re<T>(ResponseConstant.SUCCESS_STATUS, ResponseConstant.SUCCESS_MSG, data);
    }

    public static <T> Re<T> success(String msg, T data) {
        return new Re<T>(ResponseConstant.SUCCESS_STATUS, msg, data);
    }

    public static <T> Re<T> error(T data) {
        return new Re<T>(ResponseConstant.ERROR_STATUS, "error", data);
    }

    public static <T> Re<T> errorMsg(String msg) {
        return new Re<T>(ResponseConstant.ERROR_STATUS, msg, null);
    }


    public static <T> Re<T> error(T data, String msg) {
        return new Re<T>(ResponseConstant.ERROR_STATUS, msg, data);
    }


    @Override
    public String toString() {
        return "ResultUtil [status=" + status + ", msg=" + msg + ", data=" + data + "]";
    }

}

SweepCodeDTO

package com.cc.model.dto;


import lombok.Data;


@Data
public class SweepCodeDTO {
    /**
     * 公众号appid
     */
    private String appid;
    /**
     * 商户号
     */
    private String mch_id;
    /**
     * 金额
     */
    private String total_fee;
    /**
     * 随机字符串
     */
    private String nonce_str;
    /**
     * 商品描述
     */
    private String body;
    /**
     * 商户订单号
     */
    private String out_trade_no;
    /**
     * 用户端Ip地址
     */
    private String spbill_create_ip;
    /**
     * 通知地址
     */
    private String notify_url;
    /**
     * 交易类型
     */
    private String trade_type;
    /**
     * 签名
     */
    private String sign;
    /**
     * 签名类型
     */
    private String sign_type;

}

UnifiedPayResposeDTO

package com.cc.model.dto;

import lombok.Data;


@Data
public class UnifiedPayResposeDTO {
    /**
     * 返回状态码
     */
    private String return_code;
    /**
     * 返回信息
     */
    private String return_msg;
    /**
     * 公众账号ID
     */
    private String appid;
    /**
     * 商户号
     */
    private String mch_id;
    /**
     * 设备号
     */
    private String device_info;
    /**
     * 随机字符串
     */
    private String nonce_str;
    /**
     * 签名
     */
    private String sign;
    /**
     * 业务结果
     */
    private String result_code;
    /**
     * 错误代码
     */
    private String err_code;
    /**
     * 错误代码描述
     */
    private String err_code_des;
    /**
     * 用户标识
     */
    private String openid;
    /**
     * 是否关注公众账号
     */
    private String is_subscribe;
    /**
     * 交易类型
     */
    private String trade_type;
    /**
     * 预支付交易会话标识预支付交易会话标识
     */
    private String prepay_id;
    /**
     * 二维码链接
     */
    private String code_url;
    /**
     * 付款银行
     */
    private String bank_type;
    /**
     * 订单金额
     */
    private String total_fee;
    /**
     * 现金支付金额
     */
    private String cash_fee;
    /**
     * 微信支付订单号
     */
    private String transaction_id;
    /**
     * 商户订单号
     */
    private String out_trade_no;
    /**
     * 支付完成时间
     */
    private String time_end;
    /**
     * 交易状态
     */
    private String trade_state;
    /**
     * 货币类型
     */
    private String fee_type;
    /**
     * 商家数据包
     */
    private String attach;
    /**
     *营销详情
     */
    private String promotion_detail;
    /**
     * 现金支付货币类型
     */
    private String cash_fee_type;
    /**
     * 应结订单金额
     */
    private String settlement_total_fee;
    /**
     * 代金券金额
     */
    private String coupon_fee;
    /**
     * 交易状态描述
     */
    private String trade_state_desc;

}

OkHttp3Utils

package com.cc.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;



@Component
@Slf4j
public class OkHttp3Utils {


    /**
     * MEDIA_TYPE <==> Content-Type
     */
    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    /**
     * MEDIA_TYPE_TEXT post请求不是application/x-www-form-urlencoded的,全部直接返回,不作处理,即不会解析表单数据来放到request parameter map中。
     * 所以通过request.getParameter(name)是获取不到的。只能使用最原始的方式,读取输入流来获取。
    */
    private static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");


    /**
     * 地址
     **/
    private static String SF_MAP_URL ;

    /**
     * 秘钥
     **/
    private static String KEY ;

    /**
     * 邮箱url
     **/
    private static String URL ;

    /**
     * 通知平台接入Id
     **/
    private static String ACCESS_Id ;

    /**
     * 通知平台接入Id
     **/
    private static String ACCESS_TOKEN ;

    @Value("${dm.gis.url}")
    public void setGisUrl(String url) {
        SF_MAP_URL = url;
    }

    @Value("${dm.gis.ak}")
    public void setKEY(String ak) {
        KEY = ak;
    }


    @Value("${email.url}")
    public void setURL(String url) {
        URL = url;
    }

    @Value("${ds.sms.accessId}")
    public void setAccessId(String accessId) {
        ACCESS_Id = accessId;
    }

    @Value("${ds.sms.accessToken}")
    public void setAccessToken(String accessToken) {
        ACCESS_TOKEN = accessToken;
    }


    /**
     * @param addres 地址
     * @return java.lang.String
     * @descprition
     * @version 1.0
     */
    public static String sendByGetUrl(String addres) {

        String url = SF_MAP_URL + KEY
                + "&address=" + addres;
        String result;
        OkHttpClient client = new OkHttpClient();
        //10秒连接超时
        client.newBuilder().connectTimeout(3, TimeUnit.SECONDS)
                //10m秒写入超时
                .writeTimeout(10, TimeUnit.SECONDS)
                //10秒读取超时
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            result = response.body().string();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String sendByGet(String url,String params) {
        String result;
        OkHttpClient client = new OkHttpClient();
        //10秒连接超时
        client.newBuilder().connectTimeout(3, TimeUnit.SECONDS)
                //10m秒写入超时
                .writeTimeout(10, TimeUnit.SECONDS)
                //10秒读取超时
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url+"?"+params)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            result = response.body().string();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * @param url , json
     * @return java.lang.String
     * @descprition
     * @version 1.0 post+json方式
     */
    public static String sendByPostJson(String url, String json) {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param url , json
     * @return java.lang.String
     * @descprition
     * @version 1.0 post+json方式
     */
    public static String sendByPostJsonByUrlencoded(String url, String json) {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MEDIA_TYPE_TEXT, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean  sendEmailByPost(JSONObject templateJson, String email, String templateCode) throws Exception{
        JSONObject params = new JSONObject();
        //收件人邮箱,支持多收件人,分号隔离;如下面的抄送人格式
        params.put("userId", email);
        //params.put("ccId", "sfuat888@sfuat.com;sfuat777@sfuat.com");// 抄送人,如果没有可以屏蔽该语句
        // 业务模板code
        params.put("templateCode", templateCode);
        //TODO  调用方法前封装对象
       /* JSONObject templateJson = new JSONObject();
        //对应渠道模板中{{userName}}中参数
        templateJson.put("userName", "张三");
        //对应渠道模板中{{bugTitle}}中参数
        templateJson.put("bugTitle", "空指针错误");
        //对应渠道模板中{{postTime}}中参数
        templateJson.put("postTime", "2017-08-16 15:46:00");*/
        //如果对应渠道模板中没有类{{}}格式的参数,可以屏蔽该语句
        params.put("templateParam", templateJson);
        // 邮件主题,默认是渠道模板名称
        params.put("subject", "企业邮箱验证码");
//		params.put("expectedTime", "2017-06-08 15:48:00");// 定时通知

        //如果需要发送附件,请按如下方式,把附件内容转化成byte[]传入,附件没有格式限制
//		Map<String, byte[]> attachments = new LinkedHashMap<>();
//		attachments.put("a.txt", getFile("a.txt")); //附件a.txt
//		attachments.put("b.jpg", getFile("b.jpg"));//普通附件b.jpg
//		params.put("attachments", attachments);//多附件

        // 通知平台接入Id
        params.put("accessId", ACCESS_Id);
        // 通知平台接入Token
        params.put("accessToken", ACCESS_TOKEN);

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, params.toJSONString());
        Request request = new Request.Builder()
                .url(URL)
                .post(body)
                .build();
        Response response = null;
        try {
            boolean isSuccess = false;
            response = client.newCall(request).execute();
            assert response.body() != null;
            String string = response.body().string();

            JSONObject result = JSON.parseObject(string);
            log.info("发邮件返回"+result);
            if(result != null){
                isSuccess = result.getBooleanValue("success"); //返回值保存,请按实际需求修改
                String requestId = result.getString("requestId");//返回值保存,请按实际需求修改
                if(!isSuccess){
                    log.error(email+"邮件发送失败:"+result.getString("errorMessage"));//false的情况,一定要记录errorMessage,以便跟踪问题
                }
            }
            return isSuccess;
        } catch (Exception e) {
            log.error(email+"邮件发送失败:"+e.getMessage());//false的情况,一定要记录errorMessage,以便跟踪问题
            return false;
        }

    }


    /**
     * @param url , params]
     * @return java.lang.String
     * @descprition  post方式请求
     * @version 1.0
     */
    public static String sendByPostMap(String url, Map<String, String> params) {
        String result;
        OkHttpClient client = new OkHttpClient();
        StringBuilder content = new StringBuilder();
        Set<Map.Entry<String, String>> entrys = params.entrySet();
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            content.append(entry.getKey()).append("=").append(entry.getValue());
            if (iterator.hasNext()) {
                content.append("&");
            }
        }

        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_TEXT, content.toString());
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            result = response.body().string();
            System.out.println("result = " + result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static CloseableHttpClient createCloseableHttpClient(String mchId, String certificate )throws Exception{
        //1.指定读取证书格式为PKCS12
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //2.读取本机存放的PKCS12证书文件
        Resource resource = new ClassPathResource(certificate);
        InputStream in = resource.getInputStream();
        DataInputStream instream = new DataInputStream(in);


        try {
            //指定PKCS12的密码(商户ID)
            keyStore.load(instream, mchId.toCharArray());
        } finally {
            instream.close();
        }
        //3.ssl双向验证发送http请求报文
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();
        /*SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);*/
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpClient;
    }


}

WeChatPayUtils

package com.cc.utils;


import com.cc.model.dto.UnifiedPayResposeDTO;
import com.cc.model.dto.WeChatConstant;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;


@Component
public class WeChatPayUtils {

	private static Logger log = LoggerFactory.getLogger(WeChatPayUtils.class);

	public static final String ENCRYPTION_TYPE = "MD5";


	public static XStream xstream = new XStream(new XppDriver() {
		@Override
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 对所有xml节点的转换都增加CDATA标记
				boolean cdata = true;
				String nodeName = "";

				@SuppressWarnings("unchecked")
				@Override
				public void startNode(String name, Class clazz) {
					nodeName = name;
					super.startNode(name, clazz);
				}

				@Override
				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						String detail="detail";
						if (!detail.equals(nodeName)) {
							writer.write(text);
						} else {
							writer.write("<![CDATA[");
							writer.write(text);
							writer.write("]]>");
						}
					} else {
						writer.write(text);
					}
				}
			};
		}
	});


	/**
	 * 付款码支付API
	 *
	 * @param orderInfo
	 * @return
	 */
	public static UnifiedPayResposeDTO httpOrder(String orderInfo, String url) {
		//String url = "https://api.mch.weixin.qq.com/pay/micropay";
		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			// 加入数据
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
			buffOutStr.write(orderInfo.getBytes("UTF-8"));
			buffOutStr.flush();
			buffOutStr.close();
			// 获取输入流
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			// 将请求返回的内容通过xStream转换为UnifiedOrderRespose对象
			xstream.alias("xml", UnifiedPayResposeDTO.class);
			UnifiedPayResposeDTO unifiedPayResposeDTO = (UnifiedPayResposeDTO) xstream.fromXML(sb.toString());
			return unifiedPayResposeDTO;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * xml形式的字符串转换为map集合
	 * @param xmlStr
	 * @return
	 */
		public static Map<String,String> xmlStr2Map(String xmlStr){
			Map<String,String> map = new HashMap<String,String>(5);
			org.dom4j.Document doc;
			try {
				doc = DocumentHelper.parseText(xmlStr);
		        org.dom4j.Element root = doc.getRootElement();
		        List children = root.elements();
		        if(children != null && children.size() > 0) {
		            for(int i = 0; i < children.size(); i++) {
		            	org.dom4j.Element child = (org.dom4j.Element)children.get(i);
		                map.put(child.getName(), child.getTextTrim());
		            }
		        }
			} catch (DocumentException e) {
				e.printStackTrace();
			}
			return map;
//			return null;
		}


	/**
	 * 将Map转换为XML格式的字符串
	 *
	 * @param data
	 *            Map类型数据
	 * @return XML格式的字符串
	 * @throws Exception
	 */
	public static String mapToXml(Map<String, String> data) throws Exception {
		/*DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		org.w3c.dom.Document document = documentBuilder.newDocument();
		org.w3c.dom.Element root = document.createElement("xml");
		document.appendChild(root);
		for (String key : data.keySet()) {
			String value = data.get(key);
			if (value == null) {
				value = "";
			}
			value = value.trim();
			org.w3c.dom.Element filed = document.createElement(key);
			filed.appendChild(document.createTextNode(value));
			root.appendChild(filed);
		}
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		DOMSource source = new DOMSource(document);
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		StringWriter writer = new StringWriter();
		StreamResult result = new StreamResult(writer);
		transformer.transform(source, result);
		String output = writer.getBuffer().toString(); // .replaceAll("\n|\r", "");
		try {
			writer.close();
		} catch (Exception ex) {
		}
		return output;*/
		return null;
	}

	/**
	 * 生成带有 sign 的 XML 格式字符串
	 *
	 * @param data
	 *            Map类型数据
	 * @param key
	 *            API密钥
	 * @return 含有sign字段的XML
	 */
	/*public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {

		return generateSignedXml(data, key, SignType.MD5);
	}*/

	/**
	 * 生成带有 sign 的 XML 格式字符串
	 *
	 * @param data
	 *            Map类型数据
	 * @param key
	 *            API密钥
	 * @param signType
	 *            签名类型
	 * @return 含有sign字段的XML
	 */
	public  String generateSignedXml(final Map<String, String> data, String key, WeChatConstant.SignType signType) throws Exception {
		String sign = generateSignature(data, key, signType);
		data.put(WeChatConstant.FIELD_SIGN, sign);
		return mapToXml(data);
	}

	/**
	 * 判断签名是否正确
	 *
	 * @param xmlStr
	 *            XML格式数据
	 * @param key
	 *            API密钥
	 * @return 签名是否正确
	 * @throws Exception
	 */
	/*public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
		Map<String, String> data = xmlToMap(xmlStr);
		if (!data.containsKey(WXPayConstants.FIELD_SIGN)) {
			return false;
		}
		String sign = data.get(WXPayConstants.FIELD_SIGN);
		return generateSignature(data, key).equals(sign);
	}*/

	/**
	 * 判断签名是否正确,必须包含sign字段,否则返回false。使用MD5签名。
	 *
	 * @param data
	 *            Map类型数据
	 * @param key
	 *            API密钥
	 * @return 签名是否正确
	 * @throws Exception
	 */
	public  boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
		return isSignatureValid(data, key, WeChatConstant.SignType.MD5);
	}

	/**
	 * 判断签名是否正确,必须包含sign字段,否则返回false。
	 *
	 * @param data
	 *            Map类型数据
	 * @param key
	 *            API密钥
	 * @param signType
	 *            签名方式
	 * @return 签名是否正确
	 * @throws Exception
	 */
	public  boolean isSignatureValid(Map<String, String> data, String key, WeChatConstant.SignType signType) throws Exception {
		if (!data.containsKey(WeChatConstant.FIELD_SIGN)) {
			return false;
		}
		String sign = data.get(WeChatConstant.FIELD_SIGN);
		return generateSignature(data, key, signType).equals(sign);
	}

	/**
	 * MD5生成签名
	 *
	 * @param data
	 *            待签名数据
	 * @param key
	 *            API密钥
	 * @return 签名
	 */
	public  String generateSignature(final Map<String, String> data, String key) throws Exception {
		return generateSignature(data, key, WeChatConstant.SignType.HMACSHA256);
	}

    /**
     * HMACSHA256生成签名
     *
     * @param data
     *            待签名数据
     * @param key
     *            API密钥
     * @return 签名
     */
    public  String signature(final Map<String, String> data, String key) throws Exception {
        return generateSignature(data, key, WeChatConstant.SignType.HMACSHA256);
    }

	/**
	 * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
	 *
	 * @param data
	 *            待签名数据
	 * @param key
	 *            API密钥
	 * @param signType
	 *            签名方式
	 * @return 签名
	 */
	public  String generateSignature(final Map<String, String> data, String key, WeChatConstant.SignType signType) throws Exception {
		Set<String> keySet = data.keySet();
		String[] keyArray = keySet.toArray(new String[keySet.size()]);
		Arrays.sort(keyArray);
		StringBuilder sb = new StringBuilder();
		for (String k : keyArray) {
			if (k.equals(WeChatConstant.FIELD_SIGN)) {
				continue;
			}
			// 参数值为空,则不参与签名
			if (data.get(k).trim().length() > 0)
            {
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
		}
		sb.append("key=").append(key);
		if (WeChatConstant.SignType.MD5.equals(signType)) {
			log.info("获取签名原串:"+sb.toString());
			throw new Exception(String.format("Invalid sign_type: %s", signType));
		} else if (WeChatConstant.SignType.HMACSHA256.equals(signType)) {
			return hmacsha256(sb.toString(), key);
		} else {
			log.error("获取签名失败,失败原因:" + String.format("Invalid sign_type: %s", signType));
			throw new Exception(String.format("Invalid sign_type: %s", signType));
		}
	}

	/**
	 * 生成 HMACSHA256
	 * @param data 待处理数据
	 * @param key 密钥
	 * @return 加密结果
	 * @throws Exception
	 */
	public static String hmacsha256(String data, String key) throws Exception {
		Mac sha256 = Mac.getInstance("HmacSHA256");
		SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
		sha256.init(secretKey);
		byte[] array = sha256.doFinal(data.getBytes("UTF-8"));
		StringBuilder sb = new StringBuilder();
		for (byte item : array) {
			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
		}
		return sb.toString().toUpperCase();
	}

	/**
	 * 获取随机字符串 Nonce Str
	 *
	 * @return String 随机字符串
	 */
	public static String generateNonceStr() {
		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
	}

	/**
	 * Map转xml数据
	 */
	public static String GetMapToXml(Map<String, String> param) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		for (Map.Entry<String, String> entry : param.entrySet()) {
			String str = "<" + entry.getKey() + ">";
			sb.append(str);
			sb.append(entry.getValue());
			String str1 = "</" + entry.getKey() + ">";
			sb.append(str1);
		}
		sb.append("</xml>");
		return sb.toString();
	}

	/**
	 * 生成 MD5
	 *
	 * @param data
	 *            待处理数据
	 * @return MD5结果
	 */
	/*public static String MD5(String data) throws Exception {
		MessageDigest md = MessageDigest.getInstance(ENCRYPTION_TYPE);
		byte[] array = md.digest(data.getBytes("UTF-8"));
		StringBuilder sb = new StringBuilder();
		for (byte item : array) {
			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
		}
		return sb.toString().toUpperCase();
	}*/


	/**
	 * 日志
	 *
	 * @return
	 */
	public static Logger getLogger() {
		Logger logger = LoggerFactory.getLogger("wxpay java sdk");
		return logger;
	}

	/**
	 * 获取当前时间戳,单位秒
	 *
	 * @return
	 */
	public static long getCurrentTimestamp() {
		return System.currentTimeMillis() / 1000;
	}

	/**
	 * 获取当前时间戳,单位毫秒
	 *
	 * @return
	 */
	public static long getCurrentTimestampMs() {
		return System.currentTimeMillis();
	}

	/**
	 * 生成 uuid, 即用来标识一笔单,也用做 nonce_str
	 *
	 * @return
	 */
	public static String generateUuid() {
		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
	}


}

配置文件

#微信配置文件
wechat:
  callbackUrl: aaa
  appId: bbbb
  mchId: cccc
  key: ddd

email:
  url: ccceee

dm:
  gis:
    url: bbbb
    ak: ssssssss

ds:
  sms:
    accessId: dddddd
    accessToken: ffffffffff

ResponseConstant

package com.cc.model;


public class ResponseConstant {
    /**
     * Feign调用失败,没有可用链接
     */
    public static final String MSG = "错误,当前没有可连接的服务";
    /**
     * Feign调用失败,没有可用链接
     */
    public static final int ERROR_STATUS = 500;
    /**
     * 返回成功状态码
     */
    public static final int SUCCESS_STATUS = 200;
    /**
     * 返回成功消息
     */
    public static final String SUCCESS_MSG = "success";
}

pom

    <!--微信支付相关依赖start-->
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.16</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.10.0</version>
        </dependency>
        <!--微信支付相关依赖end-->

退款证书

微信退款证书

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值