官方文档:https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_4_3.shtml
实现用户主动取消订单的功能
定义取消订单接口
/*** 用户取消订单* @param orderNo* @return* @throws Exception*/
@ApiOperation("用户取消订单")
@PostMapping("/cancel/{orderNo}")
public R cancel(@PathVariable String orderNo) throws Exception {log.info("取消订单");wxPayService.cancelOrder(orderNo);return R.ok().setMessage("订单已取消");
}
实现取消订单接口
/*** 用户取消订单* @param orderNo*/
@Override
public void cancelOrder(String orderNo) throws Exception {//调用微信支付的关单接口this.closeOrder(orderNo);//更新商户端的订单状态orderInfoService.updateStatusByOrderNo(orderNo, OrderStatus.CANCEL);
}/*** 关单接口的调用* @param orderNo*/
private void closeOrder(String orderNo) throws Exception {log.info("关单接口的调用,订单号 ===> {}", orderNo);//创建远程请求对象String url = String.format(WxApiType.CLOSE_ORDER_BY_NO.getType(), orderNo);url = wxPayConfig.getDomain().concat(url);HttpPost httpPost = new HttpPost(url);//组装json请求体Gson gson = new Gson();Map<String, String> paramsMap = new HashMap<>();paramsMap.put("mchid", wxPayConfig.getMchId());String jsonParams = gson.toJson(paramsMap);log.info("请求参数 ===> {}", jsonParams);//将请求参数设置到请求对象中StringEntity entity = new StringEntity(jsonParams,"utf-8");entity.setContentType("application/json");httpPost.setEntity(entity);httpPost.setHeader("Accept", "application/json");//完成签名并执行请求CloseableHttpResponse response = wxPayClient.execute(httpPost);try {int statusCode = response.getStatusLine().getStatusCode();//响应状态码if (statusCode == 200) { //处理成功log.info("成功200");} else if (statusCode == 204) { //处理成功,无返回Bodylog.info("成功204");} else {log.info("Native下单失败,响应码 = " + statusCode);throw new IOException("request failed");}} finally {response.close();}
}