准备
<!-- WeChat Pay --> <dependency> <groupId>com.github.wechatpay-apiv3</groupId> <artifactId>wechatpay-apache-httpclient</artifactId> <version>0.2.0</version> </dependency> <dependency> <groupId>com.github.wxpay</groupId> <artifactId>wxpay-sdk</artifactId> <version>0.0.3</version> </dependency>
|
方法
微信支付,支付结果通知:官方地址 主要方法,工具类在下方
@PostMapping("wXCallBack") public String wXCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception { ServletInputStream inputStream = null; inputStream = request.getInputStream(); String notifyXml = StreamUtil.inputStreamString(inputStream, "utf-8"); if (WXPayUtil.isSignatureValid(notifyXml, "your key")) { log.info("[支付_微信支付]验签成功!"); JSONObject jsonObject = WeChatPayUtil.xmlToJson(notifyXml); String result_code = jsonObject.getString("result_code"); if (result_code.equals(WXPayConstants.SUCCESS)) {
HashMap<String, String> map = new HashMap<>(); map.put("return_code", "SUCCESS"); map.put("return_msg", "OK"); String resultXml = WXPayUtil.mapToXml(map); response.setContentType("text/xml"); log.info("[支付_微信支付]通知已处理"); return resultXml; } } Map<String, String> returnMap = new HashMap<>(); returnMap.put("return_code", "FAIL"); returnMap.put("return_msg", ""); String returnXml = WXPayUtil.mapToXml(returnMap); log.info("[支付_微信支付]处理失败!"); response.setContentType("text/xml"); return returnXml; }
|
StreamUtil
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream;
public class StreamUtil {
private static int _buffer_size = 1024;
public static String inputStreamString(InputStream inStream, String encoding) { String result = null; ByteArrayOutputStream outStream = null; try { if (inStream != null) { outStream = new ByteArrayOutputStream(); byte[] tempBytes = new byte[_buffer_size]; int count = -1; while ((count = inStream.read(tempBytes, 0, _buffer_size)) != -1) { outStream.write(tempBytes, 0, count); } outStream.flush(); result = new String(outStream.toByteArray(), encoding); outStream.close(); } } catch (Exception e) { result = null; } finally { try { if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } }
|
WeChatPayUtil.xmlToJson() 需要Jar依赖
<!-- 解析xml --> <dependency> <groupId>org.dom4j</groupId> <artifactId>dom4j</artifactId> <version>2.1.1</version> </dependency>
|
public static JSONObject xmlToJson(String xmlContent) throws DocumentException { Document document = DocumentHelper.parseText(xmlContent); Element rootElement = document.getRootElement(); Iterator iterator = rootElement.elementIterator(); JSONObject jsonObject = new JSONObject(); while (iterator.hasNext()) { DefaultElement defaultElement = (DefaultElement) iterator.next(); jsonObject.fluentPut(defaultElement.getName(), defaultElement.getStringValue()); } return jsonObject; }
|
WXPayUtil、WXPayConstants这两个最上方微信官方依赖中带有