springboot 微信支付

1. 定义常量

public class WechatConstants {


    public static String WechatAccessToken = "";

    public final static String APPID = "xxx";

    public final static String APPSECRET = "xxx";

    //支付API_KEY
    public final static String API_KEY = "xxx";

    //商户id
    public final static String MCH_ID = "xxx";

    //支付成功后的回调接口,不能带任何参数 否则验签异常
    public static String PAY_CALLBACK = "https://xxx/xxx/callbackPay";


}




 2. 微信工具

import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.*;


@Slf4j
public class WXPayUtil {

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<>();
            DocumentBuilder documentBuilder = newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes(StandardCharsets.UTF_8));
            Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            log.warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }

    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        Document document = 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 ignored) {
        }
        return output;
    }


    /**
     * 生成带有 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, "MD5");
    }

    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data     Map类型数据
     * @param key      API密钥
     * @param signType 签名类型
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key, String signType) throws Exception {
        String sign = generateSignature(data, key, signType);
        data.put("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("sign")) {
            return false;
        }
        String sign = data.get("sign");
        return generateSignature(data, key).equals(sign);
    }

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

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

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

    /**
     * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key, String signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        //规则是:按参数名称a-z排序,遇到空值的参数不参加签名
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if ("sign".equals(k)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) {
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(key);
        if ("MD5".equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        } else if ("HMACSHA256".equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        } else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }


    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }


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

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

    public static String inputStream2String(InputStream inStream, String charset) {
        try (ByteArrayOutputStream outSteam = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            return outSteam.toString(charset);
        } catch (Exception e) {
            return null;
        } finally {
            try {
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

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

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


    public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);

        return documentBuilderFactory.newDocumentBuilder();
    }

    public static Document newDocument() throws ParserConfigurationException {
        return newDocumentBuilder().newDocument();
    }

}



3. http工具


import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Slf4j
public class HttpUtil {


    //请求方法
    public static String wxHttpsRequest(String requestUrl, String requestMethod, String outputStr) {
        try {

            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes(StandardCharsets.UTF_8));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            log.warn("连接超时:{}" + ce);
        } catch (Exception e) {
            log.warn("https请求异常:{}" + e);
        }
        return null;
    }

}

4. 预支付参数
import lombok.Data;


/**
 * @author 7788
 */
@Data
public class Pay {

    private String openid;

    /**
     * 缴费人 单位 分
     */
    private String wxUser;

    /**
     * 当前缴费 单位 分
     */
    private String paid;

    /**
     * 账单id
     */
    private String billId;

}


5. 支付接口
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.*;



@Slf4j
@RestController
@RequestMapping("/xxx/xxx")
public class WxPayController {

    @Autowired
    private IIrrWaterFeeHistoryService irrWaterFeeHistoryService;

    @Autowired
    private IIrrWaterFeeBillService iIrrWaterFeeBillService;

    @ApiOperation("获取微信openid")
    @GetMapping("/getOpenId")
    public Result getOpenId(@RequestParam String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        String openId = HttpUtil.createGet(url)
                .timeout(3600)
                .execute()
                .charset(StandardCharsets.UTF_8)
                .body();
        JSONObject jsonObject = JSONObject.parseObject(openId);
        return Result.OK(jsonObject);
    }

    @PostMapping(value = "/prePay", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result weixinPrePay(@RequestBody Pay pay, HttpServletRequest request) throws Exception {
        log.info("微信支付 " + pay);
        IrrWaterFeeBill year = iIrrWaterFeeBillService.getById(pay.getBillId());
        if (null == year) {
            throw new BusinessException("当前账单ID未检查到账单,请核对缴费信息");
        }
        // 生成唯一订单号
        IrrWaterFeeHistory irrWaterFeeHistory = new IrrWaterFeeHistory();
        irrWaterFeeHistory.setTyp(1);//1 微信缴费, 2 线下缴费
        irrWaterFeeHistory.setBillId(pay.getBillId());
        irrWaterFeeHistory.setTotalPayable(year.getTotalPayable());
        irrWaterFeeHistory.setPaid(Long.parseLong(pay.getPaid()));
        irrWaterFeeHistory.setCreateBy(StringUtils.isEmpty(pay.getWxUser()) ? pay.getOpenid() : pay.getWxUser());
        irrWaterFeeHistory.setCreateTime(new Date());
        irrWaterFeeHistory.setStatus(3);//状态 1 正常, 2删除, 3 待支付
        irrWaterFeeHistoryService.save(irrWaterFeeHistory);
        String out_trade_no = irrWaterFeeHistory.getId();
        Map<String, String> parameterMap = new HashMap<>(16);
        //微信公众号的appid
        parameterMap.put("appid", APPID);
        //商户号
        parameterMap.put("mch_id", MCH_ID);
        parameterMap.put("device_info", "WEB");
        // 随机字符串
        parameterMap.put("nonce_str", WXPayUtil.generateNonceStr());
        // 商品描述
        parameterMap.put("body", "水费收缴");
        // 商户订单号(唯一) 我是用当前时间戳+随意数字生成的
        parameterMap.put("out_trade_no", "xxx_fee_" + out_trade_no);
        //货币类型 CNY:人民币
        parameterMap.put("fee_type", "CNY");
        // 总金额  分 单位
        parameterMap.put("total_fee", pay.getPaid());
        // 支付成功后的回调地址  
        parameterMap.put("notify_url", PAY_CALLBACK);
        //JSAPI--JSAPI支付(或小程序支付)、NATIVE--Native支付、APP--app支付,MWEB--H5支付,不同trade_type决定了调起支付的方式
        parameterMap.put("trade_type", "JSAPI");
        //trade_type为JSAPI是 openid为必填项
        parameterMap.put("openid", pay.getOpenid());
        // 加密格式  MD5 微信底层默认加密是HMAC-SHA256  具体你可以去看微信的支付底层代码(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1)
        parameterMap.put("sign_type", "MD5");
        // 生成支付签名 参数值的参数按照参数名ASCII码从小到大排序(字典序)规则是:按参数名称a-z排序,遇到空值的参数不参加签名
        parameterMap.put("sign", WXPayUtil.generateSignature(parameterMap, API_KEY));
        // 微信的统一下单接口 需要将集合中的参数 拼接成<xml></xml> 格式
        String requestXML = WXPayUtil.mapToXml(parameterMap);
        // 调用微信的统一下单接口
        String result = HttpUtil.wxHttpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", requestXML);
        // 返回的数据是 xml 格式的数据
        Map<String, String> map = null;
        try {
            // 微信统一下单接口返回的数据 也是xml 格式的  所以需要把它转成map 集合,因为我们只需要当中的一个统一下单编号 prepay_id
            map = WXPayUtil.xmlToMap(result);
            log.info(result);
            log.info(map.toString());
            map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
            // 时间戳 需要转换成秒
            // 二次签名 微信支付签名需要签名两次,第一次是用来获取统一下单的订单号
            if ("SUCCESS".equals(map.get("result_code"))) {
                SortedMap<String, String> map2 = new TreeMap<>();
                // 第二次支付签名的 参数 需要将 第一次签名中的 订单号带入签名中
                map2.put("appId", map.get("appid"));
                map2.put("timeStamp", map.get("timestamp"));
                //这边的随机字符串必须是第一次生成sign时,微信返回的随机字符串,不然支付时会报签名错误
                map2.put("nonceStr", map.get("nonce_str"));
                // 订单详情扩展字符串 统一下单接口返回的prepay_id参数值,提交格式如:prepay_id=***
                map2.put("package", "prepay_id=" + map.get("prepay_id"));
                // 签名方式 要和第一次签名方式一致
                map2.put("signType", "MD5");
                // 将你前端需要的数据 放在集合中
                Map<String, Object> payInfo = new HashMap<>(8);
                payInfo.put("appId", map.get("appid"));
                payInfo.put("timeStamp", map.get("timestamp"));
                payInfo.put("nonceStr", map.get("nonce_str"));
                payInfo.put("prepay_id", map.get("prepay_id"));
                payInfo.put("signType", "MD5");
                payInfo.put("paySign", WXPayUtil.generateSignature(map2, API_KEY));
                payInfo.put("packageStr", "prepay_id=" + map.get("prepay_id"));
                // 返回给前端的集合数据
                log.info("预支付成功 " + payInfo);
                return Result.OK(payInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("服务器异常");
    }


    /**
     * 此函数会被执行多次,如果支付状态已经修改为已支付,则下次再调的时候判断是否已经支付,如果已经支付了,则什么也不执行
     * <p>
     * 支付回调地址
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/callbackPay", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Result callbackPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result resultState = new Result();
        resultState.setSuccess(true);
        resultState.setCode(200);
        resultState.setMessage("成功");
        // 反馈给微信服务器
        String resXml = "";
        log.info("微信支付回调");
        String xml = WXPayUtil.inputStream2String(request.getInputStream(), "UTF-8");
        //将微信发的xml转map
        Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);
        log.info(xml);
        log.info(notifyMap.toString());
        if (isSignatureValid(xml, API_KEY)) {
            if ("SUCCESS".equals(notifyMap.get("return_code")) && "SUCCESS".equals(notifyMap.get("result_code"))) {
                //商户订单号
                String ordersSn = notifyMap.get("out_trade_no");
                ordersSn = ordersSn.replace("xxx_fee_", "");
                //实际支付的订单金额:单位 分
                String amountpaid = notifyMap.get("total_fee");
                IrrWaterFeeHistory irrWaterFeeHistory = irrWaterFeeHistoryService.queryById(ordersSn);
                log.info(irrWaterFeeHistory.toString());
                irrWaterFeeHistory.setPaid(Long.valueOf(amountpaid));
                irrWaterFeeHistory.setStatus(1);
                irrWaterFeeHistoryService.update(irrWaterFeeHistory);
                // 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            } else {
                // 支付失败
                resultState.setSuccess(false);
                resultState.setCode(-1);
                resultState.setMessage(notifyMap.get("err_code_des"));
                log.info("支付失败,错误信息:" + notifyMap.get("err_code_des"));
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[" + notifyMap.get("err_code_des") + "]]></return_msg>" + "</xml> ";
            }
        } else {
            // 支付失败
            resultState.setSuccess(false);
            resultState.setCode(-1);
            resultState.setMessage("签名验证错误");
            log.info("签名验证错误");
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[签名验证错误]]></return_msg>" + "</xml> ";
        }

        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();

        resultState.setResult(resXml);
        log.info("支付回调结果 " + resultState);
        return resultState;
    }


}
posted @ 2024-07-24 16:10  qwer78  阅读(36)  评论(0)    收藏  举报