/src/main/java/com/penuel/mythopoet/controllers/PayController.java
Java | 327 lines | 237 code | 30 blank | 60 comment | 68 complexity | 1ba3c5b3fe5496eae3e7654727fd349e MD5 | raw file
- package com.penuel.mythopoet.controllers;
- import com.alibaba.fastjson.JSONObject;
- import com.penuel.mythopoet.annotation.LoginRequired;
- import com.penuel.mythopoet.constants.PoetConstants;
- import com.penuel.mythopoet.model.*;
- import com.penuel.mythopoet.modelView.OrderView;
- import com.penuel.mythopoet.service.*;
- import com.penuel.mythopoet.utils.RequestUtil;
- import com.penuel.mythopoet.utils.ResponseUtil;
- import org.apache.commons.lang3.math.NumberUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.util.CollectionUtils;
- import org.springframework.web.bind.annotation.*;
- import javax.servlet.http.Cookie;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.util.Date;
- import java.util.List;
- import java.util.SortedMap;
- /**
- * PayController Created with mythopoet.
- * User: penuel (penuel.leo@gmail.com)
- * Date: 15/4/23 上午8:29
- * Desc:
- */
- @Controller @RequestMapping("/pay")
- public class PayController {
- private static final Logger LOGGER = LoggerFactory.getLogger(PayController.class);
- @Autowired
- private PayService payService;
- @Autowired
- private OrderService orderService;
- @Autowired
- private OrderDetailService orderDetailService;
- @Autowired
- private ItemSkuService itemSkuService;
- @Autowired
- private WxAuthService wxAuthService;
- @Autowired
- private AccessLogService accessLogService;
-
- /*
- https://api.mch.weixin.qq.com/pay/unifiedorder
- */
- @LoginRequired
- @RequestMapping(value = "/prepay", method = RequestMethod.POST, produces = "application/json;charset=utf-8") @ResponseBody
- public String prepay(HttpServletRequest request, Model model,
- @CookieValue("userId") Long userId,
- @RequestParam("orderId") Long orderId,
- @RequestParam( value = "payType", defaultValue = "0" ) int payType) {
- Orders order;
- try {
- order = orderService.getById(userId, orderId);
- List<OrderDetail> orderDetailList = orderDetailService.getByOrderId(orderId);
- if ( order == null || CollectionUtils.isEmpty(orderDetailList) ) {
- return ResponseUtil.result(1, "该订单不存在", "");
- }
- if ( order.getAddressId() == 0 ) {
- return ResponseUtil.result(1, "未选择收货地址,请确认", "");
- }
- for ( OrderDetail orderDetail : orderDetailList ) {
- ItemSku itemSku = itemSkuService.getValidSkuByItemAndProps(orderDetail.getItemId(), orderDetail.getProps());
- if ( itemSku == null || itemSku.getCount() < orderDetail.getCount() ) {
- int haveCount = itemSku == null ? 0 : itemSku.getCount();
- return ResponseUtil.result(1, "下手太慢了,【" + itemSku.getName() + "】商品已被其他人抢先支付了,剩余" + haveCount + "件", null);
- }
- }
- String userIp = RequestUtil.getRemoteHost(request);
- WxAuthUser wxAuthUser = wxAuthService.getByUserId(userId);
- if ( wxAuthUser == null || "".equals(wxAuthUser.getCode())) {
- //发送授权请求
- String authUrl = wxAuthService.authorizeURL(userId, orderId);
- return ResponseUtil.result(1001, "微信授权", authUrl);
- }
- //accesstoken expired
- long millSecond = (new Date()).getTime() - wxAuthUser.getRefreshTime().getTime();
- if ( millSecond + 5 * 60 * 1000 > wxAuthUser.getExpiresIn() * 1000 ) {//提前5分钟,就刷新accesstoken
- wxAuthService.refreshAccessToken(wxAuthUser);
- }
- PayResult prePayResult = payService.prePay(order, userIp, wxAuthUser.getOpenId());
- if ( prePayResult.isRequestSuccess() ) {
- if ( prePayResult.isTradeSuccess() ) {
- SortedMap<Object, Object> map = payService.fillPayParam4JS(prePayResult.getPrepay_id());
- return ResponseUtil.result(0, "OK", map);
- } else {
- LOGGER.info("PayController.prepay prePayResult=" + JSONObject.toJSONString(prePayResult));
- return ResponseUtil.result(1, prePayResult.getErr_code_des(), null);
- }
- }
- return ResponseUtil.result(1, "支付失败,请重试", order);
- } catch ( Exception e ) {
- LOGGER.error("OrderController.detail Error:userId=" + userId + ",ordrId=" + orderId, e);
- return ResponseUtil.result(1, "支付失败", null);
- }
- }
- /**
- * 微信支付 回调URL
- *
- * @param request
- * @param model
- * @param userId
- * @param orderId
- * @return
- */
- @RequestMapping(value = "/recall", method = RequestMethod.POST, produces = "application/json;charset=utf-8") @ResponseBody
- public String recall(HttpServletRequest request, HttpServletResponse response, Model model, @CookieValue("userId") Long userId,
- @RequestParam("orderId") Long orderId) {
- Orders order;
- try {
- LOGGER.info("PayController.recall : request=" + request.getQueryString() + "---" + request.getParameterMap());
- //TODO 判断返回值
- order = orderService.getById(userId, orderId);
- //TODO 判断订单状态,不冲突的情况下,进行修改
- //TODO 回执给微信,表示收到
- payService.paySuccess(request, response);
- } catch ( Exception e ) {
- LOGGER.error("OrderController.recall Error:userId=" + userId + ",ordrId=" + orderId, e);
- return ResponseUtil.result(1, "微信通知失败", null);
- }
- return ResponseUtil.result(0, "OK", order);
- }
- /**
- * js收到回调之后,通知后段,后段再去调用微信查询接口,更改订单状态
- *
- * @param model
- * @param userId
- * @param orderId
- * @return
- */
- @RequestMapping(value = "/jsNotify", method = RequestMethod.POST, produces = "application/json;charset=utf-8") @ResponseBody
- public String jsNotify(Model model, @CookieValue("userId") Long userId, @RequestParam("orderId") Long orderId) {
- Orders order;
- try {
- LOGGER.info("PayController.jsNotify : userId=" + userId + ",orderId=" + orderId);
- order = orderService.getById(userId, orderId);
- PayResult payResult;
- if ( order != null ) {
- payResult = payService.orderQuery(order);
- LOGGER.info(
- "PayController.jsNotify-orderQuery : userId=" + userId + ",orderId=" + orderId + ",payResult=" + JSONObject.toJSONString(payResult));
- if ( payResult.getOut_trade_no() != null && payResult.getOut_trade_no().equals(order.getViewId())) {
- //0=未支付,1=支付中,4=支付完成,5=支付失败,6=取消支付,7=转入退款
- if ( "SUCCESS".equals(payResult.getTrade_state()) ) {//支付成功
- if ( order.getPayStatus() < 4 && order.getStatus() < 4 ) {
- order.setPayStatus(4);
- order.setStatus(1);
- itemSkuService.reduceSku(order);//支付成功减少库存
- /*if(pword==null||pword.equals("")){
- ticketServcie.haveUsed(order.getId(),pword);//将券状态设置为已经使用
- }*/
- }
- } else if ( "REFUND".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(7);
- } else if ( "NOTPAY".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(0);
- } else if ( "CLOSED".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(5);
- } else if ( "REVOKED".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(6);
- } else if ( "USERPAYING".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(1);
- } else if ( "PAYERROR".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(5);
- }
- orderService.payOrder(order);
- }
- if ( order.getPayStatus() == 4 ) {
- return ResponseUtil.result(0, "支付成功", order);
- } else {
- return ResponseUtil.result(0, payResult.getTrade_state_desc(), order);
- }
- }
- //TODO 回执给微信,表示收到
- } catch ( Exception e ) {
- LOGGER.error("OrderController.jsNotify Error:userId=" + userId + ",ordrId=" + orderId, e);
- return ResponseUtil.result(1, "微信通知错误", null);
- }
- return ResponseUtil.result(1, "支付通知失败", null);
- }
-
- /**
- * js收到回调之后,通知后段,后段再去调用微信查询接口,更改订单状态
- *
- * @param model
- * @param userId
- * @param orderId
- * @return
- */
- @RequestMapping(value = "/notify/{orderId}", method = RequestMethod.GET)
- public String notify(Model model, @CookieValue("userId") Long userId, @PathVariable("orderId") Long orderId) {
- Orders order;
- try {
- LOGGER.info("PayController.notify : userId=" + userId + ",orderId=" + orderId);
- order = orderService.getById(userId, orderId);
- PayResult payResult;
- if ( order != null ) {
- payResult = payService.orderQuery(order);
- LOGGER.info(
- "PayController.notify-orderQuery : userId=" + userId + ",orderId=" + orderId + ",payResult=" + JSONObject.toJSONString(payResult));
- if ( payResult.getOut_trade_no() != null && payResult.getOut_trade_no().equals(order.getViewId())) {
- //0=未支付,1=支付中,4=支付完成,5=支付失败,6=取消支付,7=转入退款
- if ( "SUCCESS".equals(payResult.getTrade_state()) ) {//支付成功
- if ( order.getPayStatus() < 4 && order.getStatus() < 4 ) {
- order.setPayStatus(4);
- order.setStatus(1);
- itemSkuService.reduceSku(order);//支付成功减少库存
- /*if(pword==null||pword.equals("")){
- ticketServcie.haveUsed(order.getId(),pword);//将券状态设置为已经使用
- }*/
- }
- } else if ( "REFUND".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(7);
- } else if ( "NOTPAY".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(0);
- } else if ( "CLOSED".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(5);
- } else if ( "REVOKED".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(6);
- } else if ( "USERPAYING".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(1);
- } else if ( "PAYERROR".equals(payResult.getTrade_state()) ) {
- order.setPayStatus(5);
- }
- orderService.payOrder(order);
- }
- if ( order.getPayStatus() == 4 ) {
- LOGGER.info("PayController.notify : order is OK" );
- } else {
- LOGGER.error( "PayController.notify: order is fail ");
- }
- }
- //TODO 回执给微信,表示收到
- } catch ( Exception e ) {
- LOGGER.error("OrderController.notify Error:userId=" + userId + ",ordrId=" + orderId, e);
- }
- return "redirect:/order/page";
- }
- @RequestMapping(value = "/confirm/{orderId}", method = RequestMethod.GET)
- public String confirm(Model model, @PathVariable Long orderId) {
- model.addAttribute("orderId", orderId);
- return "/order/pay_confirm";
- }
- @RequestMapping(value = "/order", method = RequestMethod.POST, produces = "application/json;charset=utf-8") @ResponseBody
- public String payOrder(Model model, @CookieValue("userId") Long userId, @RequestParam(value = "orderId", defaultValue = "0") Long orderId,@RequestParam(value = "source", defaultValue = "hshs") String source) {
- try {
- Orders order = orderService.getById(userId, orderId);
- if ( order != null ) {
- order.setStatus(1);
- order.setPayStatus(4);
- order.setPayType(PoetConstants.PAY_STATUS_WX_WEB);
- } else {
- return ResponseUtil.result(1, "支付订单错误,请重新下单", null);
- }
- int result = orderService.payOrder(order);
- if ( result > 0 ) {
- return ResponseUtil.result(0, "支付成功", order);
- }
- } catch ( Exception e ) {
- LOGGER.error("PayController.payOrder Error:userId=" + userId + ",orderId=" + orderId, e);
- return ResponseUtil.result(1, "支付订单失败", null);
- }
- return ResponseUtil.result(1, "支付订单失败,请重试", null);
- }
- /**
- * 支付页面<br/>
- * 请求本页面可以加上 ?showwxpaytitle=1 微信中会出现安全支付 副标题
- *
- * @param request
- * @param userId
- * @param orderId
- * @param model
- * @param errMsg
- * @return
- */
- @RequestMapping(value = "/order/{orderId}")
- public String pay(HttpServletRequest request, HttpServletResponse response,@CookieValue("userId") Long userId, @PathVariable Long orderId, Model model,
- @RequestParam(value = "errMsg", defaultValue = "") String errMsg) {
- OrderView orderView = null;
- try {
- Orders order = orderService.getById(userId, orderId);
- orderView = orderService.buildOrderViewByOrder(order);
- } catch ( Exception e ) {
- LOGGER.error("OrderController.detail Error:userId=" + userId + ",orderId=" + orderId, e);
- }
- model.addAttribute("errMsg", errMsg);
- model.addAttribute("order", orderView);
-
-
- boolean isWeixin = false;
- String ua = request.getHeader("user-agent");
- if(ua!=null&&ua.contains("MicroMessenger")){
- isWeixin = true;
- }
- model.addAttribute("isWeixin", isWeixin);
-
-
- return "order/pay";
- }
- }