调用微信支付接口成功后后端会收到两次回调请求
调用微信支付接口成功后后端会收到两次回调请求,第一个请求是正常的,请求里可以拿到回调的信息,处理完后还会收到第二个请求,第二个请求中拿到的信息就是空了,解析这个空xml时代码就会报错了。下面上日志和代码 日志: [图片] 代码: @ApiOperation("支付成功后的回调接口")
@RequestMapping(value = "/notify", produces = "application/json;charset=UTF-8")
public void payNotifyUrl(HttpServletRequest request, HttpServletResponse response) {
String resultTemplate = "<xml><return_code><![CDATA[%s]]></return_code><return_msg><![CDATA[%s]]></return_msg></xml>";
String returnCode;
String returnMsg;
try (BufferedReader reader = request.getReader()) {
String line;
StringBuilder input = new StringBuilder();
while ((line = reader.readLine()) != null) {
input.append(line);
}
String xmlString = input.toString();
log.info("----------------回调Xml:---------{}", xmlString);
Map<String, String> map = CommonUtils.xmlToMap(xmlString);
if (WxConstant.RESP_VALUE_SUCCESS.equals(map.get(WxConstant.FIELD_RESULT_CODE)) &&
WxConstant.RESP_VALUE_SUCCESS.equals(map.get(WxConstant.FIELD_RETURN_CODE))) {
// 检查签名,防止数据泄露导致出现“假通知”,造成资金损失。(微信支付推荐)
if (CommonUtils.isSignatureValid(new TreeMap<>(map), WxConstant.API_KEY)) {
// 更新订单状态,记录日志
orderService.afterOrderPaid(map.get(WxConstant.FIELD_OUT_TRADE_NO));
returnCode = WxConstant.RESP_VALUE_SUCCESS;
returnMsg = WxConstant.RESP_MESSAGE_SUCCESS;
} else {
log.error("支付回调处理失败, 签名不正确,param: {}", map);
returnCode = WxConstant.RESP_VALUE_FAIL;
returnMsg = "签名不正确";
}
} else {
returnCode = WxConstant.RESP_VALUE_FAIL;
returnMsg = "参数校验不正确";
}
String result = String.format(resultTemplate, returnCode, returnMsg);
log.info("----------------处理回调后返回的信息:---------{}", result);
response.getWriter().write(result);
} catch (Exception e) {
log.error("支付回调处理异常", e);
try (PrintWriter writer = response.getWriter()) {
writer.write(String.format(resultTemplate, WxConstant.RESP_VALUE_FAIL, "回调处理异常"));
} catch (Exception e2) {
log.error("支付回调处理异常", e2);
}
}
}