/**
* 微信支付实现
*
* @author: Sun
* @create: 2019-10-10 17:54
* @version: v1.0
*/
@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {
@Autowired
private MyWxPayConfig myWxPayConfig;
@Autowired
private WxDecodeUtil wxDecodeUtil;
/**
* 微信响应字段
*/
private static final String RETURN_CODE = "return_code";
@Override
public String refundAsyncNotify(HttpServletRequest httpServletRequest) {
String returnXmlMessage = null;
String notifyXmlData = null;
try {
notifyXmlData = readXmlFromStream(httpServletRequest);
Map notifyMapData = WXPayUtil.xmlToMap(notifyXmlData);
log.info("[refundAsyncNotify] [xml转换为map数据成功] [notifyMapData:{}]", notifyMapData);
if (WXPayConstants.SUCCESS.equals(notifyMapData.get(RETURN_CODE))) {
// 获得加密信息
String reqInfo = notifyMapData.get("req_info");
// 进行AES解密 获取req_info中包含的相关信息(解密失败会抛出异常)
String refundDecryptedData = wxDecodeUtil.decryptData(reqInfo);
Map reqInfoMap = WXPayUtil.xmlToMap(refundDecryptedData);
log.info("[refundAsyncNotify] [reqInfo解密成功] [reqInfoMap:{}]", reqInfoMap);
// TODO 订单退款成功后相关业务逻辑...
// 组装返回给微信的xml数据
returnXmlMessage = setReturnXml(WXPayConstants.SUCCESS, "OK");
log.info("[refundAsyncNotify] [out_trade_no:{}] [out_refund_no:{}] [退款异步消息处理成功:{}]",
reqInfoMap.get("out_trade_no"), reqInfoMap.get("out_refund_no"), returnXmlMessage);
} else {
returnXmlMessage = setReturnXml(WXPayConstants.FAIL, "return_code不为success");
}
} catch (IOException e) {
log.error("[refundAsyncNotify] [读取微信服务器返回流中xml数据时发生异常:{}] ", ExceptionUtils.getStackTrace(e));
returnXmlMessage = setReturnXml(WXPayConstants.FAIL, "An exception occurred while reading the WeChat server returning xml data in the stream.");
} catch (Exception e) {
log.error("[refundAsyncNotify [处理异常]] [xml数据:{}] [异常:{}] ", notifyXmlData, ExceptionUtils.getStackTrace(e));
returnXmlMessage = setReturnXml(WXPayConstants.FAIL, "Refund successful, exception occurred during asynchronous notification processing.");
log.warn("[refundAsyncNotify] [退款异步消息处理失败:{}]", returnXmlMessage);
}
return returnXmlMessage;
}
/**
* 设置返回给微信服务器的xml信息
*
* @param returnCode
* @param returnMsg
* @return
*/
private String setReturnXml(String returnCode, String returnMsg) {
return "+ returnCode + "]]>+ returnMsg + "]]>";
}
/**
* 从流中读取微信返回的xml数据
*
* @param httpServletRequest
* @return
* @throws IOException
*/
private String readXmlFromStream(HttpServletRequest httpServletRequest) throws IOException {
InputStream inputStream = httpServletRequest.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
final StringBuffer sb = new StringBuffer();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} finally {
bufferedReader.close();
inputStream.close();
}
return sb.toString();
}
}