SpringBoot2.0微信小程序支付多次回調問題
WxJava - 微信開發 Java SDK(開發工具包); 支持包括微信支付、開放平台、公眾號、企業微信/企業號、小程序等微信功能的后端開發。
第一步: 支付回調問題
微信小程序使用請參考上一篇博客:https://www.codepeople.cn/2019/04/15/SpringBoot2.x-WX-Pay/
這里主要講的是微信小程序回調問題
微信這個坑,對第一次接觸微信支付功能的人可能都會不由自主的踩一下,不是程序猿不給力而是微信回調敵人太強大。
1.首先確定支付回調是返回的String
2.確定返回給微信的通知是正確的
首先看一下微信支付回調地址中的方法怎么寫吧?
@SuppressWarnings("deprecation")
@ApiOperation("微信支付回調地址")
@PostMapping("/notify") // 返回訂單號
public String payNotify(HttpServletRequest request, HttpServletResponse response) {
log.info("======================>>>微信支付回調<<======================");
log.info("======================>>>微信支付回調<<======================");
String resXml = "";
try {
/*
* HttpSession session = request.getSession(); String mobile = (String)
* session.getAttribute("userphone"); if (StringUtils.isBlank(mobile)) { return
* R.error(401, "session獲取不到授權手機號!"); } //獲取用戶手機號,根據用戶手機號獲取用戶ID
* AuthorizationEntity user = authorizationService.getOneByMobile(mobile);
*/
String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
WxPayOrderNotifyResult notifyResult = wxService.parseOrderNotifyResult(xmlResult);
// 結果正確 outTradeNo
String orderId = notifyResult.getOutTradeNo();
String tradeNo = notifyResult.getTransactionId();
String totalFee = BaseWxPayResult.fenToYuan(notifyResult.getTotalFee());
log.info("微信支付回調付款總金額==>{}元", totalFee);
// 自己處理訂單的業務邏輯,需要判斷訂單是否已經支付過,否則可能會重復調用
// 通知微信.異步確認成功.必寫.不然會一直通知后台.十次之后就認為交易失敗了.
resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
response.setContentType("text/xml");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
// return WxPayNotifyResponse.success("成功");
return resXml;
} catch (Exception e) {
log.error("微信回調結果異常,異常原因{}", e.getMessage());
// WxPayNotifyResponse.fail(e.getMessage());
return WxPayNotifyResponse.success("code:" + 9999 + "微信回調結果異常,異常原因:" + e.getMessage());
}
}
注意:
@PostMapping("/notify")
這個注解使用,使其返回的是是String,千萬不要加@ResponseBody
注解
response.setContentType("text/xml");
這個方法一定要加上
使用這種格式的返回數據給微信,微信就會收到通知,不會發生多次回調
如果方法上加上了@ResponseBody
該注解,微信支付會一直重復回調10次。
為了防止微信支付回調的多次調用。支付邏輯一定要判斷是否已經支付完成。還有訂單生成問題也一定要判斷。不然可能會造成多個訂單數據問題。
==================================================================
博客地址:https://www.codepeople.cn
==================================================================