Search in sources :

Example 1 with OrderUnpaidTask

use of com.wayn.mobile.api.task.OrderUnpaidTask in project waynboot-mall by wayn111.

the class OrderServiceImpl method wxPayNotify.

@Override
public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
    String xmlResult = null;
    try {
        xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
    } catch (IOException e) {
        log.error(WxPayNotifyResponse.fail(e.getMessage()), e);
    }
    WxPayOrderNotifyResult result = null;
    try {
        result = wxPayService.parseOrderNotifyResult(xmlResult);
        if (!WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())) {
            log.error(xmlResult);
        }
    } catch (WxPayException e) {
        log.error(e.getMessage(), e);
    }
    log.info("处理腾讯支付平台的订单支付, {}", result.getReturnMsg());
    String orderSn = result.getOutTradeNo();
    String payId = result.getTransactionId();
    // 分转化成元
    String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
    Order order = getOne(new QueryWrapper<Order>().eq("order_sn", orderSn));
    if (order == null) {
        log.error("微信支付回调:订单不存在,orderSn:{}", orderSn);
        return;
    }
    // 检查这个订单是否已经处理过
    if (OrderUtil.hasPayed(order)) {
        log.error("微信支付回调:订单已经处理过了,orderSn:{}", orderSn);
        return;
    }
    // 检查支付订单金额
    if (!totalFee.equals(order.getActualPrice().toString())) {
        log.error("微信支付回调: 支付金额不符合,orderSn:{},totalFee:{}", order.getOrderSn(), totalFee);
        return;
    }
    order.setPayId(payId);
    order.setPayTime(LocalDateTime.now());
    order.setOrderStatus(OrderUtil.STATUS_PAY);
    order.setUpdateTime(new Date());
    if (!updateById(order)) {
        log.error("微信支付回调: 更新订单状态失败,order:{}", JSON.toJSONString(order.getOrderSn()));
        return;
    }
    // 订单支付成功以后,会发送短信给用户,以及发送邮件给管理员
    String email = iMemberService.getById(order.getUserId()).getEmail();
    if (StringUtils.isNotBlank(email)) {
        iMailService.sendEmail("新订单通知", order.toString(), email, WaynConfig.getMobileUrl() + "/message/email");
    }
    // 删除redis中订单id
    redisCache.deleteZsetObject("order_zset", order.getId());
    // 取消订单超时未支付任务
    taskService.removeTask(new OrderUnpaidTask(order.getId()));
}
Also used : WxPayOrderNotifyResult(com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) WxPayException(com.github.binarywang.wxpay.exception.WxPayException) IOException(java.io.IOException) OrderUnpaidTask(com.wayn.mobile.api.task.OrderUnpaidTask)

Example 2 with OrderUnpaidTask

use of com.wayn.mobile.api.task.OrderUnpaidTask in project waynboot-mall by wayn111.

the class OrderServiceImpl method h5pay.

@Override
@Transactional(rollbackFor = Exception.class)
public R h5pay(String orderSn, Integer payType, HttpServletRequest request) {
    // 获取订单详情
    Order order = getOne(new QueryWrapper<Order>().eq("order_sn", orderSn));
    Long userId = order.getUserId();
    ReturnCodeEnum returnCodeEnum = checkOrderOperator(order);
    if (!ReturnCodeEnum.SUCCESS.equals(returnCodeEnum)) {
        return R.error(returnCodeEnum);
    }
    // 检测是否能够取消
    OrderHandleOption handleOption = OrderUtil.build(order);
    if (!handleOption.isPay()) {
        return R.error(ReturnCodeEnum.ORDER_CANNOT_PAY_ERROR);
    }
    // 保存支付方式
    boolean update = lambdaUpdate().set(Order::getPayType, payType).eq(Order::getOrderSn, orderSn).update();
    if (!update) {
        return R.error(ReturnCodeEnum.ORDER_SET_PAY_ERROR);
    }
    switch(Objects.requireNonNull(PayTypeEnum.of(payType))) {
        case WX:
            WxPayMpOrderResult result;
            try {
                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                orderRequest.setOutTradeNo(order.getOrderSn());
                orderRequest.setTradeType(WxPayConstants.TradeType.MWEB);
                orderRequest.setBody("订单:" + order.getOrderSn());
                // 元转成分
                int fee;
                BigDecimal actualPrice = order.getActualPrice();
                fee = actualPrice.multiply(new BigDecimal(100)).intValue();
                orderRequest.setTotalFee(fee);
                orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(request));
                result = wxPayService.createOrder(orderRequest);
                return R.success().add("result", result);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return R.error(ReturnCodeEnum.ORDER_CANNOT_PAY_ERROR);
            }
        case ALI:
            // 初始化
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGateway(), alipayConfig.getAppId(), alipayConfig.getRsaPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(), alipayConfig.getAlipayPublicKey(), alipayConfig.getSigntype());
            // 创建API对应的request,使用手机网站支付request
            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
            // 在公共参数中设置回跳和通知地址
            String url = WaynConfig.getMobileUrl() + request.getContextPath();
            alipayRequest.setReturnUrl(url + "/returnOrders/" + orderSn + "/" + userId);
            alipayRequest.setNotifyUrl(url + "/paySuccess?payType=1&orderSn=" + orderSn);
            // 填充业务参数
            // 必填
            // 商户订单号,需保证在商户端不重复
            String out_trade_no = orderSn + new Random().nextInt(9999);
            // 销售产品码,与支付宝签约的产品码名称。目前仅支持FAST_INSTANT_TRADE_PAY
            String product_code = "FAST_INSTANT_TRADE_PAY";
            // 订单总金额,单位为元,精确到小数点后两位,取值范围[0.01,100000000]。
            BigDecimal actualPrice = order.getActualPrice();
            String total_amount = actualPrice.toString();
            // 订单标题
            String subject = "支付宝测试";
            // 选填
            // 商品描述,可空
            String body = "商品描述";
            alipayRequest.setBizContent("{" + "\"out_trade_no\":\"" + out_trade_no + "\"," + "\"product_code\":\"" + product_code + "\"," + "\"total_amount\":\"" + total_amount + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\"}");
            // 请求
            String form;
            try {
                // 需要自行申请支付宝的沙箱账号、申请appID,并在配置文件中依次配置AppID、密钥、公钥,否则这里会报错。
                // 调用SDK生成表单
                form = alipayClient.pageExecute(alipayRequest).getBody();
                return R.success().add("form", form);
            } catch (AlipayApiException e) {
                log.error(e.getMessage(), e);
                return R.error(ReturnCodeEnum.ORDER_SUBMIT_ERROR);
            }
        case ALI_TEST:
            // 支付宝test,直接更新支付状态为已支付
            order.setPayId("xxxxx0987654321-ali");
            order.setPayTime(LocalDateTime.now());
            order.setOrderStatus(OrderUtil.STATUS_PAY);
            order.setUpdateTime(new Date());
            if (!updateById(order)) {
                return R.error(ReturnCodeEnum.ORDER_SUBMIT_ERROR);
            }
            // 订单支付成功以后,会发送短信给用户,以及发送邮件给管理员
            String email = iMemberService.getById(order.getUserId()).getEmail();
            if (StringUtils.isNotBlank(email)) {
                iMailService.sendEmail("新订单通知", order.toString(), email, WaynConfig.getMobileUrl() + "/message/email");
            }
            // 删除redis中订单id
            redisCache.deleteZsetObject("order_zset", order.getId());
            // 取消订单超时未支付任务
            taskService.removeTask(new OrderUnpaidTask(order.getId()));
            return R.success();
        default:
            return R.error(ReturnCodeEnum.ORDER_NOT_SUPPORT_PAYWAY_ERROR);
    }
}
Also used : LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) WxPayUnifiedOrderRequest(com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest) ReturnCodeEnum(com.wayn.common.enums.ReturnCodeEnum) DefaultAlipayClient(com.alipay.api.DefaultAlipayClient) OrderUnpaidTask(com.wayn.mobile.api.task.OrderUnpaidTask) BigDecimal(java.math.BigDecimal) BusinessException(com.wayn.common.exception.BusinessException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) WxPayException(com.github.binarywang.wxpay.exception.WxPayException) AlipayApiException(com.alipay.api.AlipayApiException) OrderHandleOption(com.wayn.common.core.util.OrderHandleOption) WxPayMpOrderResult(com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult) DefaultAlipayClient(com.alipay.api.DefaultAlipayClient) AlipayClient(com.alipay.api.AlipayClient) AlipayApiException(com.alipay.api.AlipayApiException) AlipayTradeWapPayRequest(com.alipay.api.request.AlipayTradeWapPayRequest) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with OrderUnpaidTask

use of com.wayn.mobile.api.task.OrderUnpaidTask in project waynboot-mall by wayn111.

the class OrderServiceImpl method aliPayNotify.

@Override
public void aliPayNotify(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException {
    // 将异步通知中收到的所有参数都存放到map中
    Map<String, String[]> parameterMap = request.getParameterMap();
    Map<String, String> paramsMap = new HashMap<>();
    parameterMap.forEach((s, strings) -> {
        paramsMap.put(s, strings[0]);
    });
    // 调用SDK验证签名
    boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSigntype());
    if (!signVerified) {
        log.error("支付宝支付回调:验签失败");
        return;
    }
    log.info("支付宝支付回调:开始");
    // 验签成功后,按照支付结果异步通知中的描述,对支付结果中的业务内容进行二次校验,校验成功后在response中返回success并继续商户自身业务处理,校验失败返回failure
    String orderSn = request.getParameter("orderSn");
    Order order = getOne(new QueryWrapper<Order>().eq("order_sn", orderSn));
    if (order == null) {
        log.error("支付宝支付回调:订单不存在,orderSn:{}", orderSn);
        return;
    }
    // 检查这个订单是否已经处理过
    if (OrderUtil.hasPayed(order)) {
        log.error("支付宝支付回调:订单已经处理过了,orderSn:{}", orderSn);
        return;
    }
    order.setPayId("0xsdfsadfas-ali");
    order.setPayTime(LocalDateTime.now());
    order.setOrderStatus(OrderUtil.STATUS_PAY);
    order.setUpdateTime(new Date());
    if (!updateById(order)) {
        log.error("支付宝支付回调: 更新订单状态失败,order:{}", JSON.toJSONString(order.getOrderSn()));
        return;
    }
    // 订单支付成功以后,会发送短信给用户,以及发送邮件给管理员
    String email = iMemberService.getById(order.getUserId()).getEmail();
    if (StringUtils.isNotBlank(email)) {
        iMailService.sendEmail("新订单通知", order.toString(), email, WaynConfig.getMobileUrl() + "/message/email");
    }
    // 删除redis中订单id
    redisCache.deleteZsetObject("order_zset", order.getId());
    // 取消订单超时未支付任务
    taskService.removeTask(new OrderUnpaidTask(order.getId()));
    log.info("支付宝支付回调:结束");
}
Also used : LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) OrderUnpaidTask(com.wayn.mobile.api.task.OrderUnpaidTask)

Example 4 with OrderUnpaidTask

use of com.wayn.mobile.api.task.OrderUnpaidTask in project waynboot-mall by wayn111.

the class OrderServiceImpl method submit.

@Override
@Transactional(rollbackFor = Exception.class)
public R submit(OrderDTO orderDTO) {
    Long userId = orderDTO.getUserId();
    // 获取用户地址
    Long addressId = orderDTO.getAddressId();
    Address checkedAddress;
    if (Objects.isNull(addressId)) {
        throw new BusinessException("收获地址为空,请求参数" + JSON.toJSONString(orderDTO));
    }
    checkedAddress = iAddressService.getById(addressId);
    // 获取用户订单商品,为空默认取购物车已选中商品
    List<Long> cartIdArr = orderDTO.getCartIdArr();
    List<Cart> checkedGoodsList;
    if (CollectionUtils.isEmpty(cartIdArr)) {
        checkedGoodsList = iCartService.list(new QueryWrapper<Cart>().eq("checked", true).eq("user_id", userId));
    } else {
        checkedGoodsList = iCartService.listByIds(cartIdArr);
    }
    // 商品费用
    BigDecimal checkedGoodsPrice = new BigDecimal("0.00");
    for (Cart checkGoods : checkedGoodsList) {
        checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber())));
    }
    // 根据订单商品总价计算运费,满足条件(例如88元)则免运费,否则需要支付运费(例如8元);
    BigDecimal freightPrice = new BigDecimal("0.00");
    /*if (checkedGoodsPrice.compareTo(SystemConfig.getFreightLimit()) < 0) {
            freightPrice = SystemConfig.getFreight();
        }*/
    // 可以使用的其他钱,例如用户积分
    BigDecimal integralPrice = new BigDecimal("0.00");
    // 优惠卷抵扣费用
    BigDecimal couponPrice = new BigDecimal("0.00");
    // 团购抵扣费用
    BigDecimal grouponPrice = new BigDecimal("0.00");
    // 订单费用
    BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal("0.00"));
    // 最终支付费用
    BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);
    // 组装订单数据
    Order order = new Order();
    order.setUserId(userId);
    order.setOrderSn(orderDTO.getOrderSn());
    order.setOrderStatus(OrderUtil.STATUS_CREATE);
    order.setConsignee(checkedAddress.getName());
    order.setMobile(checkedAddress.getTel());
    order.setMessage(orderDTO.getMessage());
    String detailedAddress = checkedAddress.getProvince() + checkedAddress.getCity() + checkedAddress.getCounty() + " " + checkedAddress.getAddressDetail();
    order.setAddress(detailedAddress);
    order.setFreightPrice(freightPrice);
    order.setCouponPrice(couponPrice);
    order.setGrouponPrice(grouponPrice);
    order.setIntegralPrice(integralPrice);
    order.setGoodsPrice(checkedGoodsPrice);
    order.setOrderPrice(orderTotalPrice);
    order.setActualPrice(actualPrice);
    order.setCreateTime(new Date());
    if (!save(order)) {
        throw new BusinessException("订单创建失败" + JSON.toJSONString(order));
    }
    Long orderId = order.getId();
    List<OrderGoods> orderGoodsList = new ArrayList<>();
    // 添加订单商品表项
    for (Cart cartGoods : checkedGoodsList) {
        // 订单商品
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderId(orderId);
        orderGoods.setGoodsId(cartGoods.getGoodsId());
        orderGoods.setGoodsSn(cartGoods.getGoodsSn());
        orderGoods.setProductId(cartGoods.getProductId());
        orderGoods.setGoodsName(cartGoods.getGoodsName());
        orderGoods.setPicUrl(cartGoods.getPicUrl());
        orderGoods.setPrice(cartGoods.getPrice());
        orderGoods.setNumber(cartGoods.getNumber());
        orderGoods.setSpecifications(cartGoods.getSpecifications());
        orderGoods.setCreateTime(LocalDateTime.now());
        orderGoodsList.add(orderGoods);
    }
    if (!iOrderGoodsService.saveBatch(orderGoodsList)) {
        throw new BusinessException("添加订单商品表项失败" + JSON.toJSONString(orderGoodsList));
    }
    // 删除购物车里面的商品信息
    if (CollectionUtils.isEmpty(cartIdArr)) {
        iCartService.remove(new QueryWrapper<Cart>().eq("user_id", userId));
    } else {
        iCartService.removeByIds(cartIdArr);
    }
    // 下单60s内未支付自动取消订单
    long delay = 1000;
    redisCache.setCacheZset("order_zset", order.getId(), System.currentTimeMillis() + 60 * delay);
    taskService.addTask(new OrderUnpaidTask(order.getId(), delay * 60));
    return R.success().add("orderId", order.getId());
}
Also used : LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) OrderUnpaidTask(com.wayn.mobile.api.task.OrderUnpaidTask) BigDecimal(java.math.BigDecimal) BusinessException(com.wayn.common.exception.BusinessException) Cart(com.wayn.mobile.api.domain.Cart) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

LambdaQueryWrapper (com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper)4 QueryWrapper (com.baomidou.mybatisplus.core.conditions.query.QueryWrapper)4 OrderUnpaidTask (com.wayn.mobile.api.task.OrderUnpaidTask)4 WxPayException (com.github.binarywang.wxpay.exception.WxPayException)2 BusinessException (com.wayn.common.exception.BusinessException)2 IOException (java.io.IOException)2 BigDecimal (java.math.BigDecimal)2 Transactional (org.springframework.transaction.annotation.Transactional)2 AlipayApiException (com.alipay.api.AlipayApiException)1 AlipayClient (com.alipay.api.AlipayClient)1 DefaultAlipayClient (com.alipay.api.DefaultAlipayClient)1 AlipayTradeWapPayRequest (com.alipay.api.request.AlipayTradeWapPayRequest)1 WxPayOrderNotifyResult (com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult)1 WxPayMpOrderResult (com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult)1 WxPayUnifiedOrderRequest (com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest)1 OrderHandleOption (com.wayn.common.core.util.OrderHandleOption)1 ReturnCodeEnum (com.wayn.common.enums.ReturnCodeEnum)1 Cart (com.wayn.mobile.api.domain.Cart)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1