modify file

This commit is contained in:
Cauchy
2023-10-10 18:10:40 +08:00
15 changed files with 637 additions and 490 deletions

View File

@@ -0,0 +1,59 @@
package com.peanut.config;
/**
* @Description: 常量类
* @Author: Cauchy
* @CreateTime: 2023/10/10
*/
public class Constants {
/**
* 订单状态 - 待支付
*/
public static final String ORDER_STATUS_TO_BE_PAID = "0";
/**
* 订单状态 - 待发货
*/
public static final String ORDER_STATUS_TO_BE_SHIPPED = "1";
/**
* 订单状态 - 已发货
*/
public static final String ORDER_STATUS_SHIPPED = "2";
/**
* 订单状态 - 已发货
*/
public static final String ORDER_STATUS_FINISHED = "3";
/**
* 订单状态 - 交易失败
*/
public static final String ORDER_STATUS_FAIL = "4";
/**
* 订单状态 - 订单超时
*/
public static final String ORDER_STATUS_OUT_OF_TIME = "5";
/**
* 支付方式 - 微信支付
*/
public static final String PAYMENT_METHOD_WECHAT_PAY = "1";
/**
* 支付方式 - 支付宝 - 支付宝支付
*/
public static final String PAYMENT_METHOD_ALI_PAY = "2";
/**
* 支付方式 - IOS 内购
*/
public static final String PAYMENT_METHOD_IOS = "3";
/**
* 支付方式 - 虚拟币支付
*/
public static final String PAYMENT_METHOD_VIRTUAL = "4";
/**
* 购买方式 - 直接购买
*/
public static final String BUY_TYPE_REDIRECT = "0";
/**
* 购买方式 - 购物车
*/
public static final String BUY_TYPE_CART = "1";
}

View File

@@ -11,6 +11,7 @@ import java.util.Map;
/** /**
* RabbitMq 延时队列实现 * RabbitMq 延时队列实现
*
* @author AnYuan * @author AnYuan
*/ */
@@ -41,17 +42,31 @@ public class DelayQueueConfig {
public static final String DEAD_LETTER_QUEUE_ROUTING_KEY = "delay.queue.deadLetter.delay_10s.routingKey"; public static final String DEAD_LETTER_QUEUE_ROUTING_KEY = "delay.queue.deadLetter.delay_10s.routingKey";
public static final String DEAD_LETTER_QUEUE = "delay.queue.deadLetter.queue"; public static final String DEAD_LETTER_QUEUE = "delay.queue.deadLetter.queue";
/**
* 订单待支付交换机
*/
public static final String ORDER_TO_BE_PAY_EXCHANGE = "order_to_be_pay_exchange";
public static final String ORDER_TO_BE_PAY_ROUTING_KEY = "order_to_be_pay_routingKey";
public static final String ORDER_TO_BE_PAY_QUEUE = "order_to_be_pay_queue";
/**
* 订单取消队列
*/
public static final String ORDER_CANCEL_DEAD_LETTER_EXCHANGE = "order_cancel_dead_letter_exchange";
public static final String ORDER_CANCEL_DEAD_LETTER_ROUTING_KEY = "order_cancel_dead_letter_routingKey";
public static final String ORDER_CANCEL_DEAD_LETTER_QUEUE = "order_cancel_dead_letter_queue";
/** /**
* 快递队列 * 快递队列
*/ */
public static final String FMS_QUEUE= "fms.queue"; public static final String FMS_QUEUE = "fms.queue";
public static final String FMS_EXCHANGE = "fms.exchange"; public static final String FMS_EXCHANGE = "fms.exchange";
public static final String FMS_ROUTING_KEY = "fms.routing.key"; public static final String FMS_ROUTING_KEY = "fms.routing.key";
/** /**
* 声明 死信交换机 * 声明 死信交换机
*
* @return deadLetterExchange * @return deadLetterExchange
*/ */
@Bean @Bean
@@ -62,11 +77,12 @@ public class DelayQueueConfig {
/** /**
* 声明 订单交换机 * 声明 订单交换机
*
* @return deadLetterExchange * @return deadLetterExchange
*/ */
@Bean @Bean
public Exchange orderEventExchange() { public Exchange orderEventExchange() {
return new TopicExchange(ORDER_EVENT_EXCHANGE,true,false); return new TopicExchange(ORDER_EVENT_EXCHANGE, true, false);
} }
@@ -82,7 +98,7 @@ public class DelayQueueConfig {
map.put("x-message-ttl", 60000); map.put("x-message-ttl", 60000);
Queue queue = new Queue(ORDER_DELAY_QUEUE, true, false, false,map); Queue queue = new Queue(ORDER_DELAY_QUEUE, true, false, false, map);
return queue; return queue;
} }
@@ -97,9 +113,9 @@ public class DelayQueueConfig {
} }
/** /**
* 声明 死信队列 用于接收死信消息 * 声明 死信队列 用于接收死信消息
*
* @return deadLetterQueueA * @return deadLetterQueueA
*/ */
@Bean @Bean
@@ -109,6 +125,7 @@ public class DelayQueueConfig {
/** /**
* 将 死信队列 绑定到死信交换机上 * 将 死信队列 绑定到死信交换机上
*
* @return deadLetterBindingA * @return deadLetterBindingA
*/ */
@Bean @Bean
@@ -121,6 +138,7 @@ public class DelayQueueConfig {
/** /**
* 声明 延时交换机 * 声明 延时交换机
*
* @return delayExchange * @return delayExchange
*/ */
@Bean @Bean
@@ -130,6 +148,7 @@ public class DelayQueueConfig {
/** /**
* 将 延时队列 绑定参数 * 将 延时队列 绑定参数
*
* @return Queue * @return Queue
*/ */
@Bean @Bean
@@ -146,6 +165,7 @@ public class DelayQueueConfig {
/** /**
* 将 延时队列 绑定到延时交换机上面 * 将 延时队列 绑定到延时交换机上面
*
* @return delayBindingA * @return delayBindingA
*/ */
@Bean @Bean
@@ -158,28 +178,62 @@ public class DelayQueueConfig {
@Bean @Bean
public Binding orderCreateOrderBingding(){ public Binding orderCreateOrderBingding() {
return new Binding(ORDER_DELAY_QUEUE, Binding.DestinationType.QUEUE,ORDER_EVENT_EXCHANGE,"order.create.order",null); return new Binding(ORDER_DELAY_QUEUE, Binding.DestinationType.QUEUE, ORDER_EVENT_EXCHANGE, "order.create.order", null);
} }
@Bean @Bean
public Binding orderReleaseOrderBingding(){ public Binding orderReleaseOrderBingding() {
return new Binding(ORDER_RELEASE_QUEUE, Binding.DestinationType.QUEUE,ORDER_EVENT_EXCHANGE,ORDER_QUEUE_ROUTING_KEY,null); return new Binding(ORDER_RELEASE_QUEUE, Binding.DestinationType.QUEUE, ORDER_EVENT_EXCHANGE, ORDER_QUEUE_ROUTING_KEY, null);
} }
@Bean @Bean
public Queue FMSQueue(){ public Queue FMSQueue() {
return new Queue(FMS_QUEUE); return new Queue(FMS_QUEUE);
} }
@Bean @Bean
TopicExchange FMSExchange() { TopicExchange FMSExchange() {
return new TopicExchange(FMS_EXCHANGE); return new TopicExchange(FMS_EXCHANGE);
} }
Binding bindingExchangeMessage(){ Binding bindingExchangeMessage() {
return BindingBuilder.bind(FMSQueue()).to(FMSExchange()).with(FMS_ROUTING_KEY); return BindingBuilder.bind(FMSQueue()).to(FMSExchange()).with(FMS_ROUTING_KEY);
} }
@Bean
public DirectExchange orderCancelDeadLetterExchange() {
return new DirectExchange(ORDER_CANCEL_DEAD_LETTER_EXCHANGE);
}
@Bean
public Queue orderCancelDeadLetterQueue() {
return new Queue(ORDER_CANCEL_DEAD_LETTER_QUEUE);
}
@Bean
public DirectExchange orderExchange() {
return new DirectExchange(ORDER_TO_BE_PAY_EXCHANGE);
}
@Bean
public Queue orderQueue() {
Map<String, Object> arguments = new HashMap<>(2);
// 绑定死信交换机
arguments.put("x-dead-letter-exchange", ORDER_CANCEL_DEAD_LETTER_EXCHANGE);
// 绑定我们的路由key
arguments.put("x-dead-letter-routing-key", ORDER_CANCEL_DEAD_LETTER_ROUTING_KEY);
return new Queue(ORDER_TO_BE_PAY_QUEUE, true, false, false, arguments);
}
@Bean
public Binding orderBinding() {
return BindingBuilder.bind(orderQueue()).to(orderExchange()).with(ORDER_TO_BE_PAY_ROUTING_KEY);
}
@Bean
public Binding binding() {
return BindingBuilder.bind(orderCancelDeadLetterQueue()).to(orderCancelDeadLetterExchange()).with(ORDER_CANCEL_DEAD_LETTER_ROUTING_KEY);
}
} }

View File

@@ -1,26 +1,29 @@
package com.peanut.modules.book.controller; package com.peanut.modules.book.controller;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker; import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peanut.modules.book.entity.*;
import com.peanut.modules.book.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.peanut.common.utils.PageUtils; import com.peanut.common.utils.PageUtils;
import com.peanut.common.utils.R; import com.peanut.common.utils.R;
import com.peanut.config.Constants;
import com.peanut.config.DelayQueueConfig;
import com.peanut.modules.book.entity.*;
import com.peanut.modules.book.service.*;
import com.peanut.modules.pay.weChatPay.dto.WechatPaymentInfo;
import com.peanut.modules.pay.weChatPay.service.WxpayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/** /**
@@ -54,44 +57,10 @@ public class BuyOrderController {
private UserEbookBuyService userEbookBuyService; private UserEbookBuyService userEbookBuyService;
@Autowired @Autowired
private UserRecordService userRecordService; private UserRecordService userRecordService;
@Autowired
/** private WxpayService wxpayService;
* 订单状态 - 待支付 @Autowired
*/ private RabbitTemplate rabbitTemplate;
private static final String ORDER_STATUS_TO_BE_PAID = "0";
/**
* 订单状态 - 待发货
*/
private static final String ORDER_STATUS_TO_BE_SHIPPED = "1";
/**
* 订单状态 - 待收货
*/
private static final String ORDER_STATUS_TO_BE_RECEIVED = "2";
/**
* 支付方式 - 支付宝 - 支付宝支付
*/
private static final String PAYMENT_METHOD_ALI_PAY = "1";
/**
* 支付方式 - 微信支付
*/
private static final String PAYMENT_METHOD_WECHAT_PAY = "2";
/**
* 支付方式 - IOS 内购
*/
private static final String PAYMENT_METHOD_IOS = "3";
/**
* 支付方式 - 虚拟币支付
*/
private static final String PAYMENT_METHOD_VIRTUAL = "4";
/**
* 购买方式 - 直接购买
*/
private static final String BUY_TYPE_REDIRECT = "0";
/**
* 购买方式 - 购物车
*/
private static final String BUY_TYPE_CART = "1";
@Autowired @Autowired
private ShopProudictBookService shopProudictBookService; private ShopProudictBookService shopProudictBookService;
@@ -144,7 +113,7 @@ public class BuyOrderController {
*/ */
@RequestMapping("/buySave") @RequestMapping("/buySave")
@Transactional @Transactional
public R buySave(@RequestBody BuyOrderEntity buyOrder) { public R buySave(@RequestBody BuyOrderEntity buyOrder) throws IOException {
// 获取订单详情 // 获取订单详情
List<BuyOrderDetailEntity> products = buyOrder.getProducts(); List<BuyOrderDetailEntity> products = buyOrder.getProducts();
// 订单总金额 // 订单总金额
@@ -163,7 +132,7 @@ public class BuyOrderController {
buyOrderDetail.setProductPrice(product.getPrice()); buyOrderDetail.setProductPrice(product.getPrice());
buyOrderDetail.setAddressId(buyOrder.getAddressId()); buyOrderDetail.setAddressId(buyOrder.getAddressId());
buyOrderDetail.setProductUrl(product.getProductImages()); buyOrderDetail.setProductUrl(product.getProductImages());
buyOrderDetail.setOrderStatus(ORDER_STATUS_TO_BE_PAID); buyOrderDetail.setOrderStatus(Constants.ORDER_STATUS_TO_BE_PAID);
} }
totalPrice = totalPrice.subtract(useCouponAmount(buyOrder)); totalPrice = totalPrice.subtract(useCouponAmount(buyOrder));
@@ -176,21 +145,38 @@ public class BuyOrderController {
for (BuyOrderDetailEntity buyOrderDetail : products) { for (BuyOrderDetailEntity buyOrderDetail : products) {
buyOrderDetail.setOrderId(buyOrder.getOrderId()); buyOrderDetail.setOrderId(buyOrder.getOrderId());
buyOrderDetail.setUserId(buyOrder.getUserId()); buyOrderDetail.setUserId(buyOrder.getUserId());
if (BUY_TYPE_CART.equals(buyOrder.getBuyType())) { if (Constants.BUY_TYPE_CART.equals(buyOrder.getBuyType())) {
handleBuyCart(buyOrder, buyOrderDetail); handleBuyCart(buyOrder, buyOrderDetail);
} }
} }
buyOrderDetailService.saveBatch(products); buyOrderDetailService.saveBatch(products);
if (PAYMENT_METHOD_VIRTUAL.equals(buyOrder.getPaymentMethod())) { // 1. 虚拟币支付
buyOrder.setOrderStatus(ORDER_STATUS_TO_BE_SHIPPED); if (Constants.PAYMENT_METHOD_VIRTUAL.equals(buyOrder.getPaymentMethod())) {
buyOrder.setOrderStatus(Constants.ORDER_STATUS_TO_BE_SHIPPED);
MyUserEntity user = this.myUserService.getById(buyOrder.getUserId()); MyUserEntity user = this.myUserService.getById(buyOrder.getUserId());
if (usePeanutCoin(user, totalPrice)) { if (usePeanutCoin(user, totalPrice)) {
// 更新订单状态
buyOrderService.updateOrderStatus(user.getId(), buyOrder.getOrderSn(), "0");
recordTransaction(buyOrder, user, totalPrice); recordTransaction(buyOrder, user, totalPrice);
addEbookToUser(products, buyOrder); addEbookToUser(products, buyOrder);
} else { } else {
return R.error(500, "花生币余额不足!"); return R.error(500, "花生币余额不足!");
} }
} }
// 2. 微信支付
if (Constants.PAYMENT_METHOD_WECHAT_PAY.equals(buyOrder.getPaymentMethod())) {
rabbitTemplate.convertAndSend(
DelayQueueConfig.ORDER_TO_BE_PAY_EXCHANGE,
DelayQueueConfig.ORDER_TO_BE_PAY_ROUTING_KEY,
buyOrder.getOrderId(),
messagePostProcessor()
);
WechatPaymentInfo paymentInfo = new WechatPaymentInfo();
paymentInfo.setOrderSn(orderSn);
paymentInfo.setBuyOrderId(buyOrder.getOrderId());
paymentInfo.setTotalAmount(totalPrice);
wxpayService.prepay(paymentInfo);
}
Map<String, Object> result = new HashMap<>(); Map<String, Object> result = new HashMap<>();
result.put("orderSn", buyOrder.getOrderSn()); result.put("orderSn", buyOrder.getOrderSn());
result.put("money", totalPrice); result.put("money", totalPrice);
@@ -283,6 +269,7 @@ public class BuyOrderController {
@RequestMapping("/appGetOrderInfo/{type}") @RequestMapping("/appGetOrderInfo/{type}")
public R appGetOrderInfo(@PathVariable String type, @RequestParam("orderId") Integer orderId) { public R appGetOrderInfo(@PathVariable String type, @RequestParam("orderId") Integer orderId) {
BuyOrderEntity buyOrder = buyOrderService.getById(orderId); BuyOrderEntity buyOrder = buyOrderService.getById(orderId);
buyOrder.setTimestamp(buyOrder.getCreateTime().getTime()/1000);
List<BuyOrderDetailEntity> orderDetail = null; List<BuyOrderDetailEntity> orderDetail = null;
if ("1".equals(type)) { if ("1".equals(type)) {
orderDetail = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper<BuyOrderDetailEntity>() orderDetail = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper<BuyOrderDetailEntity>()
@@ -557,4 +544,12 @@ public class BuyOrderController {
orderCartService.removeByIds(collect); orderCartService.removeByIds(collect);
} }
} }
private MessagePostProcessor messagePostProcessor() {
return message -> {
//设置有效期30分钟
message.getMessageProperties().setExpiration(String.valueOf(30*60*1000));
return message;
};
}
} }

View File

@@ -113,4 +113,7 @@ public class BuyOrderDetailEntity implements Serializable {
@TableField("record_id") @TableField("record_id")
private Integer recordId; private Integer recordId;
@TableField(exist = false)
private Long timestamp;
} }

View File

@@ -21,9 +21,6 @@ import lombok.Data;
public class BuyOrderEntity implements Serializable { public class BuyOrderEntity implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/**
*
*/
@TableId @TableId
private Integer orderId; private Integer orderId;
/** /**
@@ -47,8 +44,6 @@ public class BuyOrderEntity implements Serializable {
* 收货人手机号 * 收货人手机号
*/ */
private String userPhone; private String userPhone;
/** /**
* 省 * 省
*/ */
@@ -66,7 +61,7 @@ public class BuyOrderEntity implements Serializable {
*/ */
private String address; private String address;
/** /**
* 支付方式 1支付宝2微信3ios内购 4虚拟币 * 支付方式 1微信2支付宝3ios内购 4虚拟币
*/ */
private String paymentMethod; private String paymentMethod;
/** /**
@@ -109,6 +104,7 @@ public class BuyOrderEntity implements Serializable {
* 2: 已发货 * 2: 已发货
* 3已完成 * 3已完成
* 4: 交易失败 * 4: 交易失败
* 5: 已过期
*/ */
private String orderStatus; private String orderStatus;
/** /**
@@ -153,19 +149,14 @@ public class BuyOrderEntity implements Serializable {
* 地址id * 地址id
*/ */
private Integer addressId; private Integer addressId;
/** /**
* 订单备注 * 订单备注
*/ */
private String remark; private String remark;
/** /**
* 快递鸟订单编号 * 快递鸟订单编号
*/ */
private String orderCode; private String orderCode;
/** /**
* 支付时间 * 支付时间
*/ */
@@ -175,4 +166,7 @@ public class BuyOrderEntity implements Serializable {
@TableField("record_id") @TableField("record_id")
private Integer recordId; private Integer recordId;
@TableField(exist = false)
private Long timestamp;
} }

View File

@@ -16,5 +16,7 @@ import java.util.Map;
public interface PayWechatOrderService extends IService<PayWechatOrderEntity> { public interface PayWechatOrderService extends IService<PayWechatOrderEntity> {
PageUtils queryPage(Map<String, Object> params); PageUtils queryPage(Map<String, Object> params);
void add(String orderSn,String prepayId);
} }

View File

@@ -1,6 +1,5 @@
package com.peanut.modules.book.service.impl; package com.peanut.modules.book.service.impl;
import cn.com.marsoft.tool.ToolObject;
import com.alibaba.druid.mock.MockConnection; import com.alibaba.druid.mock.MockConnection;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
@@ -30,9 +29,6 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.xml.soap.Text;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -61,32 +57,32 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
private MockConnection connection; private MockConnection connection;
@Override @Override
public PageUtils queryPage(Map<String, Object> params) throws Exception{ public PageUtils queryPage(Map<String, Object> params) throws Exception {
IPage<BuyOrderEntity> page = null; IPage<BuyOrderEntity> page = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startTime = null; String startTime = null;
String endTime = null; String endTime = null;
if(params.containsKey("startTime")){ if (params.containsKey("startTime")) {
startTime = sdf.format(Long.parseLong(params.get("startTime").toString())); startTime = sdf.format(Long.parseLong(params.get("startTime").toString()));
endTime = sdf.format(Long.parseLong(params.get("endTime").toString())); endTime = sdf.format(Long.parseLong(params.get("endTime").toString()));
} }
if (ObjectUtils.isEmpty(params.get("orderStatus"))) { if (ObjectUtils.isEmpty(params.get("orderStatus"))) {
page = this.page( page = this.page(
new Query<BuyOrderEntity>().getPage(params), new Query<BuyOrderEntity>().getPage(params),
new ExcludeEmptyQueryWrapper<BuyOrderEntity>().eq("user_phone",params.get("key")). new ExcludeEmptyQueryWrapper<BuyOrderEntity>().eq("user_phone", params.get("key")).
or().like("order_sn",params.get("key")).or().like("shipping_user",params.get("key")) or().like("order_sn", params.get("key")).or().like("shipping_user", params.get("key"))
.apply(startTime != null ,"date_format (create_time,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')",startTime) .apply(startTime != null, "date_format (create_time,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", startTime)
.apply(endTime != null,"date_format (create_time,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", endTime).orderByDesc("create_time") .apply(endTime != null, "date_format (create_time,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", endTime).orderByDesc("create_time")
); );
} else { } else {
page = this.page( page = this.page(
new Query<BuyOrderEntity>().getPage(params), new Query<BuyOrderEntity>().getPage(params),
new ExcludeEmptyQueryWrapper<BuyOrderEntity>().eq("order_status", params.get("orderStatus")).eq("user_phone",params.get("key")) new ExcludeEmptyQueryWrapper<BuyOrderEntity>().eq("order_status", params.get("orderStatus")).eq("user_phone", params.get("key"))
.or().like("order_sn",params.get("key")).or().like("shipping_user",params.get("key")) .or().like("order_sn", params.get("key")).or().like("shipping_user", params.get("key"))
.apply(startTime != null ,"date_format (create_time,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')",startTime) .apply(startTime != null, "date_format (create_time,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", startTime)
.apply(endTime != null,"date_format (create_time,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", endTime).orderByDesc("create_time") .apply(endTime != null, "date_format (create_time,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", endTime).orderByDesc("create_time")
); );
} }
@@ -95,7 +91,7 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
for (BuyOrderEntity record : records) { for (BuyOrderEntity record : records) {
Integer userId = record.getUserId(); Integer userId = record.getUserId();
MyUserEntity myUserEntity = myUserService.getById(userId); MyUserEntity myUserEntity = myUserService.getById(userId);
if(!ObjectUtils.isEmpty(myUserEntity)){ if (!ObjectUtils.isEmpty(myUserEntity)) {
record.setUserName(myUserEntity.getName()); record.setUserName(myUserEntity.getName());
record.setProducts(buyOrderDetailService.list(new QueryWrapper<BuyOrderDetailEntity>() record.setProducts(buyOrderDetailService.list(new QueryWrapper<BuyOrderDetailEntity>()
.eq("order_id", record.getOrderId()))); .eq("order_id", record.getOrderId())));
@@ -128,9 +124,10 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
List<BuyOrderEntity> records = page.getRecords(); List<BuyOrderEntity> records = page.getRecords();
for (BuyOrderEntity buyOrderEntity : records) { for (BuyOrderEntity buyOrderEntity : records) {
Integer orderId = buyOrderEntity.getOrderId(); Integer orderId = buyOrderEntity.getOrderId();
buyOrderEntity.setTimestamp(buyOrderEntity.getCreateTime().getTime()/1000);
List<BuyOrderDetailEntity> entities = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper<BuyOrderDetailEntity>() List<BuyOrderDetailEntity> entities = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper<BuyOrderDetailEntity>()
.eq("order_id", orderId)); .eq("order_id", orderId));
if (entities!=null) { if (entities != null) {
for (BuyOrderDetailEntity entity : entities) { for (BuyOrderDetailEntity entity : entities) {
Integer productId = entity.getProductId(); Integer productId = entity.getProductId();
ShopProductEntity shopPro = shopProductService.getById(productId); ShopProductEntity shopPro = shopProductService.getById(productId);
@@ -141,7 +138,6 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
} }
} }
} }
@@ -185,24 +181,24 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
@Transactional @Transactional
public void sendFMS(Integer[] orderIds, String shipperCode, String shipperName) { public void sendFMS(Integer[] orderIds, String shipperCode, String shipperName) {
logger.info("##########################开始批量发货!时间:"+ new Date()); logger.info("##########################开始批量发货!时间:" + new Date());
try { try {
String timeId = IdWorker.getTimeId(); String timeId = IdWorker.getTimeId();
List<FMSOrderEntity> fmsOrderList = new ArrayList<>(); List<FMSOrderEntity> fmsOrderList = new ArrayList<>();
// 查询订单详情 // 查询订单详情
List<BuyOrderEntity> orderList = this.buyOrderDao.queryListByOrderIds(orderIds); List<BuyOrderEntity> orderList = this.buyOrderDao.queryListByOrderIds(orderIds);
Map<Integer,Object> userMap = new HashMap<>(); Map<Integer, Object> userMap = new HashMap<>();
// 清洗出有哪些用户 // 清洗出有哪些用户
for(BuyOrderEntity order : orderList){ for (BuyOrderEntity order : orderList) {
order.setOrderCode(timeId+order.getUserId()); order.setOrderCode(timeId + order.getUserId());
userMap.put(order.getUserId(),order); userMap.put(order.getUserId(), order);
} }
this.saveOrUpdateBatch(orderList); this.saveOrUpdateBatch(orderList);
List<Integer> keys = userMap.keySet().stream().collect(Collectors.toList()); List<Integer> keys = userMap.keySet().stream().collect(Collectors.toList());
List<BuyOrderDetailEntity> buyOrderDetailList = this.buyOrderDetailDao.queryListByOrderIds(orderIds); List<BuyOrderDetailEntity> buyOrderDetailList = this.buyOrderDetailDao.queryListByOrderIds(orderIds);
for(int k : keys){ for (int k : keys) {
Object o = userMap.get(k); Object o = userMap.get(k);
BuyOrderEntity order = new ObjectMapper().convertValue(o,BuyOrderEntity.class); BuyOrderEntity order = new ObjectMapper().convertValue(o, BuyOrderEntity.class);
FMSOrderEntity fmsOrder = new FMSOrderEntity(); FMSOrderEntity fmsOrder = new FMSOrderEntity();
// 生成一个新的订单号保存到订单表中 // 生成一个新的订单号保存到订单表中
@@ -216,8 +212,8 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
fmsOrder.setReceiverAddress(order.getAddress()); fmsOrder.setReceiverAddress(order.getAddress());
fmsOrder.setRemark(order.getRemark()); fmsOrder.setRemark(order.getRemark());
List<FMSCommodity> fmsCommoditylist = new ArrayList<>(); List<FMSCommodity> fmsCommoditylist = new ArrayList<>();
for (BuyOrderDetailEntity orderDetail : buyOrderDetailList){ for (BuyOrderDetailEntity orderDetail : buyOrderDetailList) {
if(orderDetail.getUserId().equals(k)){ if (orderDetail.getUserId().equals(k)) {
FMSCommodity fmsCommodity = new FMSCommodity(); FMSCommodity fmsCommodity = new FMSCommodity();
fmsCommodity.setGoodsName(orderDetail.getProductName()); fmsCommodity.setGoodsName(orderDetail.getProductName());
fmsCommodity.setGoodsQuantity(orderDetail.getQuantity()); fmsCommodity.setGoodsQuantity(orderDetail.getQuantity());
@@ -242,24 +238,24 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
if ("true".equals(json.getString("Success"))) { if ("true".equals(json.getString("Success"))) {
JSONObject jsonObj = JSONObject.parseObject(json.getString("Order")); JSONObject jsonObj = JSONObject.parseObject(json.getString("Order"));
// 业务数据 // 业务数据
Map<Integer,Object> objMap = new HashMap<>(); Map<Integer, Object> objMap = new HashMap<>();
List<BuyOrderEntity> list = this.list(new QueryWrapper<BuyOrderEntity>().eq("order_code", jsonObj.getString("OrderCode"))); List<BuyOrderEntity> list = this.list(new QueryWrapper<BuyOrderEntity>().eq("order_code", jsonObj.getString("OrderCode")));
for(BuyOrderEntity order : list){ for (BuyOrderEntity order : list) {
// 改变订单状态为已发货 // 改变订单状态为已发货
order.setOrderStatus("2"); order.setOrderStatus("2");
// 改变订单信息为已有商品发货 // 改变订单信息为已有商品发货
order.setIsSend("1"); order.setIsSend("1");
this.updateById(order); this.updateById(order);
objMap.put(order.getOrderId(),order); objMap.put(order.getOrderId(), order);
} }
List<Integer> orderIdList = objMap.keySet().stream().collect(Collectors.toList()); List<Integer> orderIdList = objMap.keySet().stream().collect(Collectors.toList());
Integer [] oIds = orderIdList.toArray(new Integer[orderIdList.size()]); Integer[] oIds = orderIdList.toArray(new Integer[orderIdList.size()]);
List<BuyOrderDetailEntity> buyOrderEntityList = this.buyOrderDetailDao.queryListByOrderIds(oIds); List<BuyOrderDetailEntity> buyOrderEntityList = this.buyOrderDetailDao.queryListByOrderIds(oIds);
String SortingCode = jsonObj.getString("SortingCode"); String SortingCode = jsonObj.getString("SortingCode");
for(BuyOrderDetailEntity buy :buyOrderEntityList){ for (BuyOrderDetailEntity buy : buyOrderEntityList) {
buy.setFmsHtml(json.getString("PrintTemplate")); buy.setFmsHtml(json.getString("PrintTemplate"));
buy.setCreatTime(new Date()); buy.setCreatTime(new Date());
buy.setShippingSn(SortingCode.substring(0,SortingCode.indexOf("/"))); buy.setShippingSn(SortingCode.substring(0, SortingCode.indexOf("/")));
buy.setShipperCode(jsonObj.getString("ShipperCode")); buy.setShipperCode(jsonObj.getString("ShipperCode"));
buy.setShipperName(shipperName); buy.setShipperName(shipperName);
buy.setIsPrint("0"); buy.setIsPrint("0");
@@ -268,7 +264,7 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
} }
} }
logger.info("##########################结束批量发货!时间:"+ new Date()); logger.info("##########################结束批量发货!时间:" + new Date());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -318,14 +314,14 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
// }else { // }else {
// 直接展示 // 直接展示
// } // }
String A =expNo; String A = expNo;
if (!expNo.equals(1)){ if (!expNo.equals(1)) {
String rntStr = KdApiEOrder.queryOrderOnlineByJson(param); String rntStr = KdApiEOrder.queryOrderOnlineByJson(param);
JSONObject jsonObject = JSONObject.parseObject(rntStr); JSONObject jsonObject = JSONObject.parseObject(rntStr);
if ("true".equals(jsonObject.getString("Success"))) { if ("true".equals(jsonObject.getString("Success"))) {
return jsonObject; return jsonObject;
} }
}else { } else {
String rntStr = KdApiEOrder.queryOrderOnlineByJson(param); String rntStr = KdApiEOrder.queryOrderOnlineByJson(param);
JSONObject jsonObject = JSONObject.parseObject(rntStr); JSONObject jsonObject = JSONObject.parseObject(rntStr);
if ("true".equals(jsonObject.getString("Success"))) { if ("true".equals(jsonObject.getString("Success"))) {
@@ -374,22 +370,22 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
} }
} }
Map<Integer,Object> map = new HashMap<>(); Map<Integer, Object> map = new HashMap<>();
// 使用清洗后的List获得其中有多少个用户 // 使用清洗后的List获得其中有多少个用户
for(BuyOrderEntity o : washOrderList){ for (BuyOrderEntity o : washOrderList) {
map.put(o.getUserId(), o); map.put(o.getUserId(), o);
} }
//获取map的所有key转为list //获取map的所有key转为list
List<Integer> keys = map.keySet().stream().collect(Collectors.toList()); List<Integer> keys = map.keySet().stream().collect(Collectors.toList());
List<UserOrderVo> userOrderVoList = new ArrayList<>(); List<UserOrderVo> userOrderVoList = new ArrayList<>();
for(int key : keys){ for (int key : keys) {
UserOrderVo userOrderVo = new UserOrderVo(); UserOrderVo userOrderVo = new UserOrderVo();
List<BuyOrderEntity> orderEntityList = new ArrayList<>(); List<BuyOrderEntity> orderEntityList = new ArrayList<>();
for(BuyOrderEntity o : buyOrderList){ for (BuyOrderEntity o : buyOrderList) {
if(o.getUserId().equals(key)){ if (o.getUserId().equals(key)) {
userOrderVo.setTel(o.getUserPhone()); userOrderVo.setTel(o.getUserPhone());
userOrderVo.setUserName(o.getShippingUser()); userOrderVo.setUserName(o.getShippingUser());
userOrderVo.setAddress(o.getProvince()+o.getCity()+o.getDistrict()+o.getAddress()); userOrderVo.setAddress(o.getProvince() + o.getCity() + o.getDistrict() + o.getAddress());
orderEntityList.add(o); orderEntityList.add(o);
userOrderVo.setOrderList(orderEntityList); userOrderVo.setOrderList(orderEntityList);
} }
@@ -398,11 +394,11 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
} }
// 判断订单是否有可合并的如果没有移除掉该值 // 判断订单是否有可合并的如果没有移除掉该值
for (UserOrderVo u : userOrderVoList) { for (UserOrderVo u : userOrderVoList) {
if(u.getOrderList().size() <= 1){ if (u.getOrderList().size() <= 1) {
userOrderVoList.remove(u); userOrderVoList.remove(u);
u.getOrderList().remove(0); u.getOrderList().remove(0);
} }
if(u.getOrderList().size() == 0){ if (u.getOrderList().size() == 0) {
break; break;
} }
} }
@@ -417,7 +413,7 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
*/ */
@Override @Override
@Transactional @Transactional
public Page checkOrder(Map<String, Object> params){ public Page checkOrder(Map<String, Object> params) {
// 查询所有订单信息 // 查询所有订单信息
List<BuyOrderEntity> orderList = new ArrayList<>(); List<BuyOrderEntity> orderList = new ArrayList<>();
@@ -435,22 +431,22 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
orderList.add(order); orderList.add(order);
} }
// 获取有订单的所有用户 // 获取有订单的所有用户
Map<Integer,Object> map = new HashMap<>(); Map<Integer, Object> map = new HashMap<>();
for(BuyOrderEntity order : orderList){ for (BuyOrderEntity order : orderList) {
map.put(order.getUserId(), order); map.put(order.getUserId(), order);
} }
//获取map的所有key转为list //获取map的所有key转为list
List<Integer> keys = map.keySet().stream().collect(Collectors.toList()); List<Integer> keys = map.keySet().stream().collect(Collectors.toList());
for(int key : keys){ for (int key : keys) {
UserOrderVo userOrderVo = new UserOrderVo(); UserOrderVo userOrderVo = new UserOrderVo();
List<BuyOrderEntity> orderEntityList = new ArrayList<>(); List<BuyOrderEntity> orderEntityList = new ArrayList<>();
for(BuyOrderEntity o : buyOrderList.getRecords()){ for (BuyOrderEntity o : buyOrderList.getRecords()) {
if(o.getUserId().equals(key)){ if (o.getUserId().equals(key)) {
userOrderVo.setUserName(o.getShippingUser()); userOrderVo.setUserName(o.getShippingUser());
userOrderVo.setTel(o.getUserPhone()); userOrderVo.setTel(o.getUserPhone());
userOrderVo.setAddress(o.getProvince()+o.getCity()+o.getDistrict()+o.getAddress()); userOrderVo.setAddress(o.getProvince() + o.getCity() + o.getDistrict() + o.getAddress());
orderEntityList.add(o); orderEntityList.add(o);
userOrderVo.setOrderList(orderEntityList); userOrderVo.setOrderList(orderEntityList);
} }
@@ -458,8 +454,8 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
userOrderVoList.add(userOrderVo); userOrderVoList.add(userOrderVo);
} }
for(UserOrderVo userOrder : userOrderVoList){ for (UserOrderVo userOrder : userOrderVoList) {
if(userOrder.getOrderList().size() > 1){ if (userOrder.getOrderList().size() > 1) {
rntList.add(userOrder); rntList.add(userOrder);
} }
@@ -477,7 +473,7 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
*/ */
@Override @Override
public void blendSendFMS(Integer[] orderDetailIds, String shipperCode, String shipperName) { public void blendSendFMS(Integer[] orderDetailIds, String shipperCode, String shipperName) {
logger.info("##########################开始混合发货!:"+ new Date()); logger.info("##########################开始混合发货!:" + new Date());
try { try {
// 生成订单号 // 生成订单号
String timeId = IdWorker.getTimeId(); String timeId = IdWorker.getTimeId();
@@ -485,12 +481,12 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
List<BuyOrderDetailEntity> washDetailList = new ArrayList<>(); List<BuyOrderDetailEntity> washDetailList = new ArrayList<>();
List<BuyOrderDetailEntity> detailList = this.buyOrderDetailService.list(new QueryWrapper<BuyOrderDetailEntity>()); List<BuyOrderDetailEntity> detailList = this.buyOrderDetailService.list(new QueryWrapper<BuyOrderDetailEntity>());
for(BuyOrderDetailEntity buy : detailList){ for (BuyOrderDetailEntity buy : detailList) {
for(int orderDetailId : orderDetailIds){ for (int orderDetailId : orderDetailIds) {
if(buy.getAllOrderId() == orderDetailId){ if (buy.getAllOrderId() == orderDetailId) {
FMSOrderDetailEntity fms = new FMSOrderDetailEntity(); FMSOrderDetailEntity fms = new FMSOrderDetailEntity();
fms.setDetailId(buy.getAllOrderId()); fms.setDetailId(buy.getAllOrderId());
fms.setOrderCode(timeId+buy.getUserId()); fms.setOrderCode(timeId + buy.getUserId());
fms.setOrderId(buy.getOrderId()); fms.setOrderId(buy.getOrderId());
fmsList.add(fms); fmsList.add(fms);
washDetailList.add(buy); washDetailList.add(buy);
@@ -505,9 +501,9 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
// 初始化快递商品信息 // 初始化快递商品信息
List<FMSCommodity> fmsCommoditylist = new ArrayList<>(); List<FMSCommodity> fmsCommoditylist = new ArrayList<>();
if(washDetailList != null && washDetailList.size() > 0){ if (washDetailList != null && washDetailList.size() > 0) {
BuyOrderEntity order = this.getById(washDetailList.get(0).getOrderId()); BuyOrderEntity order = this.getById(washDetailList.get(0).getOrderId());
fmsOrder.setOrderCode(timeId+order.getUserId()); fmsOrder.setOrderCode(timeId + order.getUserId());
fmsOrder.setShipperCode(shipperCode); fmsOrder.setShipperCode(shipperCode);
fmsOrder.setReceiverName(order.getShippingUser()); fmsOrder.setReceiverName(order.getShippingUser());
fmsOrder.setReceiverMobile(order.getUserPhone()); fmsOrder.setReceiverMobile(order.getUserPhone());
@@ -515,7 +511,7 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
fmsOrder.setReceiverCityName(order.getCity()); fmsOrder.setReceiverCityName(order.getCity());
fmsOrder.setReceiverExpAreaName(order.getDistrict()); fmsOrder.setReceiverExpAreaName(order.getDistrict());
fmsOrder.setReceiverAddress(order.getAddress()); fmsOrder.setReceiverAddress(order.getAddress());
for(BuyOrderDetailEntity buy : washDetailList){ for (BuyOrderDetailEntity buy : washDetailList) {
FMSCommodity fmsCommodity = new FMSCommodity(); FMSCommodity fmsCommodity = new FMSCommodity();
fmsCommodity.setGoodsName(buy.getProductName()); fmsCommodity.setGoodsName(buy.getProductName());
fmsCommodity.setGoodsQuantity(buy.getQuantity()); fmsCommodity.setGoodsQuantity(buy.getQuantity());
@@ -533,17 +529,17 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
JSONObject jsonObj = JSONObject.parseObject(json.getString("Order")); JSONObject jsonObj = JSONObject.parseObject(json.getString("Order"));
String orderCode = jsonObj.getString("OrderCode"); String orderCode = jsonObj.getString("OrderCode");
List<FMSOrderDetailEntity> fmsOrderDetailList = this.fmsOrderDetailService.list(new QueryWrapper<FMSOrderDetailEntity>().eq("order_code", orderCode)); List<FMSOrderDetailEntity> fmsOrderDetailList = this.fmsOrderDetailService.list(new QueryWrapper<FMSOrderDetailEntity>().eq("order_code", orderCode));
System.out.println("############################################开始进入判断4444444jsonArr"+ jsonArr+"json="+json+"orderCode="+orderCode); System.out.println("############################################开始进入判断4444444jsonArr" + jsonArr + "json=" + json + "orderCode=" + orderCode);
String SortingCode = jsonObj.getString("LogisticCode"); String SortingCode = jsonObj.getString("LogisticCode");
String ShipperCode=jsonObj.getString("ShipperCode"); String ShipperCode = jsonObj.getString("ShipperCode");
String PrintTemplate=json.getString("PrintTemplate"); String PrintTemplate = json.getString("PrintTemplate");
for(FMSOrderDetailEntity fms : fmsOrderDetailList){ for (FMSOrderDetailEntity fms : fmsOrderDetailList) {
BuyOrderEntity o = this.getById(fms.getOrderId()); BuyOrderEntity o = this.getById(fms.getOrderId());
BuyOrderDetailEntity detail = this.buyOrderDetailService.getById(fms.getDetailId()); BuyOrderDetailEntity detail = this.buyOrderDetailService.getById(fms.getDetailId());
detail.setOrderStatus("1"); detail.setOrderStatus("1");
if (PrintTemplate.equals(buyOrderDetailService.getById(detail))){ if (PrintTemplate.equals(buyOrderDetailService.getById(detail))) {
return; return;
}else { } else {
detail.setFmsHtml(PrintTemplate); detail.setFmsHtml(PrintTemplate);
} }
@@ -558,10 +554,10 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
List<BuyOrderDetailEntity> list = this.buyOrderDetailService.list(new QueryWrapper<BuyOrderDetailEntity>().eq("order_id", fms.getOrderId()) List<BuyOrderDetailEntity> list = this.buyOrderDetailService.list(new QueryWrapper<BuyOrderDetailEntity>().eq("order_id", fms.getOrderId())
.eq("order_status", "0")); .eq("order_status", "0"));
// .eq("order_status", "0") // .eq("order_status", "0")
if(list.size() == 0){ if (list.size() == 0) {
o.setIsSend("1"); o.setIsSend("1");
o.setOrderStatus("2"); o.setOrderStatus("2");
}else{ } else {
o.setIsSend("1"); o.setIsSend("1");
} }
this.updateById(o); this.updateById(o);
@@ -578,8 +574,8 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
} }
} }
logger.info("##########################结束混合发货!时间:"+ new Date()); logger.info("##########################结束混合发货!时间:" + new Date());
}catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -594,42 +590,42 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
*/ */
@Override @Override
public int getProductGoodsType(Map<String, Object> param,Map<String, Object> productMap){ public int getProductGoodsType(Map<String, Object> param, Map<String, Object> productMap) {
// param key商品Id,value商品数量 // param key商品Id,value商品数量
// 定义不同种类的数组 // 定义不同种类的数组
Map<String,Object> pictureMap = new HashMap<>(); Map<String, Object> pictureMap = new HashMap<>();
Map<String,Object> bookMap = new HashMap<>(); Map<String, Object> bookMap = new HashMap<>();
List<ProductVo> advanceBookingList = new ArrayList<>(); List<ProductVo> advanceBookingList = new ArrayList<>();
List<ProductVo> deviceList = new ArrayList<>(); List<ProductVo> deviceList = new ArrayList<>();
int transPrice = 0; int transPrice = 0;
if(!ObjectUtils.isEmpty(productMap)){ if (!ObjectUtils.isEmpty(productMap)) {
Set set = productMap.keySet(); Set set = productMap.keySet();
Iterator ite = set.iterator(); Iterator ite = set.iterator();
while (ite.hasNext()) { while (ite.hasNext()) {
int i = 1; int i = 1;
Object next =ite.next(); Object next = ite.next();
// 根据Id查询信息后 计算出各个种类商品的总重量 // 根据Id查询信息后 计算出各个种类商品的总重量
ShopProductEntity product = this.shopProductService.getById(Integer.valueOf(next.toString())); ShopProductEntity product = this.shopProductService.getById(Integer.valueOf(next.toString()));
if("0".equals(product.getIsFreeMail())){ if ("0".equals(product.getIsFreeMail())) {
product.setWeight(0f); product.setWeight(0f);
} }
if("01".equals(product.getGoodsType())){ if ("01".equals(product.getGoodsType())) {
if(ObjectUtils.isEmpty(pictureMap)){ if (ObjectUtils.isEmpty(pictureMap)) {
pictureMap.put("picture",(float)product.getWeight() * Integer.valueOf(productMap.get(next.toString()).toString())); pictureMap.put("picture", (float) product.getWeight() * Integer.valueOf(productMap.get(next.toString()).toString()));
}else{ } else {
pictureMap.put("picture",(float)pictureMap.get("picture") + (float)product.getWeight() * Integer.valueOf(productMap.get(next.toString()).toString())); pictureMap.put("picture", (float) pictureMap.get("picture") + (float) product.getWeight() * Integer.valueOf(productMap.get(next.toString()).toString()));
} }
} }
if("02".equals(product.getGoodsType())){ if ("02".equals(product.getGoodsType())) {
if(ObjectUtils.isEmpty(bookMap)){ if (ObjectUtils.isEmpty(bookMap)) {
bookMap.put("book",(float)product.getWeight() * Integer.valueOf(productMap.get(next.toString()).toString())); bookMap.put("book", (float) product.getWeight() * Integer.valueOf(productMap.get(next.toString()).toString()));
}else{ } else {
bookMap.put("book",(float)bookMap.get("book") + (float)product.getWeight() * Integer.valueOf(productMap.get(next.toString()).toString())); bookMap.put("book", (float) bookMap.get("book") + (float) product.getWeight() * Integer.valueOf(productMap.get(next.toString()).toString()));
} }
} }
if("03".equals(product.getGoodsType())){ if ("03".equals(product.getGoodsType())) {
ProductVo p = new ProductVo(); ProductVo p = new ProductVo();
p.setKdCode(param.get("kdCode").toString()); p.setKdCode(param.get("kdCode").toString());
p.setArea(param.get("area").toString()); p.setArea(param.get("area").toString());
@@ -637,7 +633,7 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
p.setWeight(product.getWeight().intValue()); p.setWeight(product.getWeight().intValue());
deviceList.add(p); deviceList.add(p);
} }
if("04".equals(product.getGoodsType())){ if ("04".equals(product.getGoodsType())) {
ProductVo p = new ProductVo(); ProductVo p = new ProductVo();
p.setKdCode(param.get("kdCode").toString()); p.setKdCode(param.get("kdCode").toString());
p.setArea(param.get("area").toString()); p.setArea(param.get("area").toString());
@@ -647,29 +643,28 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
} }
} }
} }
if(!ObjectUtils.isEmpty(pictureMap)){ if (!ObjectUtils.isEmpty(pictureMap)) {
pictureMap.put("kdCode",param.get("kdCode")); pictureMap.put("kdCode", param.get("kdCode"));
pictureMap.put("area",param.get("area")); pictureMap.put("area", param.get("area"));
pictureMap.put("weight",pictureMap.get("picture")); pictureMap.put("weight", pictureMap.get("picture"));
transPrice += this.getTransPrice(pictureMap); transPrice += this.getTransPrice(pictureMap);
} }
if(!ObjectUtils.isEmpty(bookMap)){ if (!ObjectUtils.isEmpty(bookMap)) {
bookMap.put("kdCode",param.get("kdCode")); bookMap.put("kdCode", param.get("kdCode"));
bookMap.put("area",param.get("area")); bookMap.put("area", param.get("area"));
bookMap.put("weight",bookMap.get("book")); bookMap.put("weight", bookMap.get("book"));
transPrice += this.getTransPrice(bookMap); transPrice += this.getTransPrice(bookMap);
} }
if(!ObjectUtils.isEmpty(deviceList)){ if (!ObjectUtils.isEmpty(deviceList)) {
transPrice += this.getTransPrice(deviceList); transPrice += this.getTransPrice(deviceList);
} }
if(!ObjectUtils.isEmpty(advanceBookingList)){ if (!ObjectUtils.isEmpty(advanceBookingList)) {
transPrice += this.getTransPrice(advanceBookingList); transPrice += this.getTransPrice(advanceBookingList);
} }
return transPrice; return transPrice;
} }
public static String getRandom(int len) { public static String getRandom(int len) {
Random r = new Random(); Random r = new Random();
StringBuilder rs = new StringBuilder(); StringBuilder rs = new StringBuilder();
@@ -680,7 +675,7 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
} }
@Override @Override
public R randomOrderCode( BuyOrderEntity buyOrder) { public R randomOrderCode(BuyOrderEntity buyOrder) {
SimpleDateFormat dmDate = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat dmDate = new SimpleDateFormat("yyyyMMddHHmmss");
String randata = getRandom(6); String randata = getRandom(6);
Date date = new Date(); Date date = new Date();
@@ -689,8 +684,9 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
if (Xsode.length() < 24) { if (Xsode.length() < 24) {
Xsode = Xsode + 0; Xsode = Xsode + 0;
} }
return R.ok(Xsode) ; return R.ok(Xsode);
} }
/* /*
打印时查重 打印时查重
*/ */
@@ -698,7 +694,7 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
public PageUtils querySheet(Map<String, Object> params) { public PageUtils querySheet(Map<String, Object> params) {
IPage<BuyOrderEntity> page = this.page( IPage<BuyOrderEntity> page = this.page(
new Query<BuyOrderEntity>().getPage(params), new Query<BuyOrderEntity>().getPage(params),
new QueryWrapper<BuyOrderEntity>().eq("is_print","0") new QueryWrapper<BuyOrderEntity>().eq("is_print", "0")
.groupBy("shipping_sn") .groupBy("shipping_sn")
); );
return new PageUtils(page); return new PageUtils(page);
@@ -738,14 +734,13 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
} }
/** /**
* 计算仪器,预售快递费用 * 计算仪器,预售快递费用
* *
* @param productList * @param productList
* @return * @return
*/ */
public int getTransPrice(List<ProductVo> productList){ public int getTransPrice(List<ProductVo> productList) {
// 首重 // 首重
int amount = 0; int amount = 0;
@@ -753,43 +748,43 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
int continuousWeight = 0; int continuousWeight = 0;
// 费用 // 费用
int fare = 0; int fare = 0;
for(ProductVo p : productList){ for (ProductVo p : productList) {
String prov = p.getArea().substring(0,p.getArea().indexOf("_")); String prov = p.getArea().substring(0, p.getArea().indexOf("_"));
float weight = p.getNum() * p.getWeight(); float weight = p.getNum() * p.getWeight();
// 韵达计费规则 // 韵达计费规则
if("YD".equals(p.getKdCode())){ if ("YD".equals(p.getKdCode())) {
// 如果ID等于71 说明是天津发天津 // 如果ID等于71 说明是天津发天津
if("71".equals(prov)){ if ("71".equals(prov)) {
amount = 6; amount = 6;
continuousWeight = 3; continuousWeight = 3;
} }
// 首重十元 续重四元 // 首重十元 续重四元
String tenStr [] = {"70","73","75","76","77","79","81","82","83","84","85","86","87","88","91","92","96","80","78"}; String tenStr[] = {"70", "73", "75", "76", "77", "79", "81", "82", "83", "84", "85", "86", "87", "88", "91", "92", "96", "80", "78"};
boolean tenBoolean = Arrays.asList(tenStr).contains(prov); boolean tenBoolean = Arrays.asList(tenStr).contains(prov);
if(tenBoolean){ if (tenBoolean) {
amount = 10; amount = 10;
continuousWeight = 4; continuousWeight = 4;
} }
// 首重十二元 // 首重十二元
String twelveStr[] = {"74","89","90","93","94","97","98","99"}; String twelveStr[] = {"74", "89", "90", "93", "94", "97", "98", "99"};
boolean twelveBoolean = Arrays.asList(twelveStr).contains(prov); boolean twelveBoolean = Arrays.asList(twelveStr).contains(prov);
if(twelveBoolean){ if (twelveBoolean) {
amount = 12; amount = 12;
continuousWeight = 5; continuousWeight = 5;
// 甘肃 97青海 98内蒙古 74 海南90 续重 6元 // 甘肃 97青海 98内蒙古 74 海南90 续重 6元
if(prov.equals("97") || prov.equals("98")|| prov.equals("74") || prov.equals("90")){ if (prov.equals("97") || prov.equals("98") || prov.equals("74") || prov.equals("90")) {
continuousWeight = 6; continuousWeight = 6;
} }
} }
// 首重二十元,续重二十元 // 首重二十元,续重二十元
if("100".equals(prov)){ if ("100".equals(prov)) {
amount = 20; amount = 20;
continuousWeight = 20; continuousWeight = 20;
} }
if(weight <= 1000){ if (weight <= 1000) {
fare += amount; fare += amount;
}else { } else {
fare += (int) (amount + (continuousWeight * Math.floor(weight / 1000))); fare += (int) (amount + (continuousWeight * Math.floor(weight / 1000)));
} }
} }
@@ -801,6 +796,7 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
/** /**
* 计算快递费用 * 计算快递费用
*
* @param param * @param param
*/ */
public int getTransPrice(Map<String, Object> param) { public int getTransPrice(Map<String, Object> param) {
@@ -808,46 +804,46 @@ public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrderEntity
int fare = 0; int fare = 0;
String KDCode = param.get("kdCode").toString(); String KDCode = param.get("kdCode").toString();
String area = param.get("area").toString(); String area = param.get("area").toString();
String prov = area.substring(0,area.indexOf("_")); String prov = area.substring(0, area.indexOf("_"));
float weight = (float)param.get("weight"); float weight = (float) param.get("weight");
// 韵达计费规则 // 韵达计费规则
if("YD".equals(KDCode)){ if ("YD".equals(KDCode)) {
// 如果ID等于71 说明是天津发天津 // 如果ID等于71 说明是天津发天津
int amount = 0; int amount = 0;
int continuousWeight = 0; int continuousWeight = 0;
if("71".equals(prov)){ if ("71".equals(prov)) {
amount = 6; amount = 6;
continuousWeight = 3; continuousWeight = 3;
} }
// 首重十元 续重四元 // 首重十元 续重四元
String tenStr [] = {"70","73","75","76","77","79","81","82","83","84","85","86","87","88","91","92","96","80","78"}; String tenStr[] = {"70", "73", "75", "76", "77", "79", "81", "82", "83", "84", "85", "86", "87", "88", "91", "92", "96", "80", "78"};
boolean tenBoolean = Arrays.asList(tenStr).contains(prov); boolean tenBoolean = Arrays.asList(tenStr).contains(prov);
if(tenBoolean){ if (tenBoolean) {
amount = 10; amount = 10;
continuousWeight = 4; continuousWeight = 4;
} }
// 首重十二元 // 首重十二元
String twelveStr[] = {"74","89","90","93","94","97","98","99"}; String twelveStr[] = {"74", "89", "90", "93", "94", "97", "98", "99"};
boolean twelveBoolean = Arrays.asList(twelveStr).contains(prov); boolean twelveBoolean = Arrays.asList(twelveStr).contains(prov);
if(twelveBoolean){ if (twelveBoolean) {
amount = 12; amount = 12;
continuousWeight = 5; continuousWeight = 5;
// 甘肃 97青海 98内蒙古 74 海南90 续重 6元 // 甘肃 97青海 98内蒙古 74 海南90 续重 6元
if(prov.equals("97") || prov.equals("98")|| prov.equals("74") || prov.equals("90")){ if (prov.equals("97") || prov.equals("98") || prov.equals("74") || prov.equals("90")) {
continuousWeight = 6; continuousWeight = 6;
} }
} }
// 首重二十元,续重二十元 // 首重二十元,续重二十元
if("100".equals(prov)){ if ("100".equals(prov)) {
amount = 20; amount = 20;
continuousWeight = 20; continuousWeight = 20;
} }
// 如果重量等于0 说明是包邮 // 如果重量等于0 说明是包邮
if(weight == 0){ if (weight == 0) {
return 0; return 0;
} else if(weight <= 1000){ } else if (weight <= 1000) {
return amount; return amount;
}else { } else {
return (int) (amount + (continuousWeight * Math.floor(weight / 1000))); return (int) (amount + (continuousWeight * Math.floor(weight / 1000)));
} }
} }

View File

@@ -6,17 +6,23 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.peanut.common.utils.PageUtils; import com.peanut.common.utils.PageUtils;
import com.peanut.common.utils.Query; import com.peanut.common.utils.Query;
import com.peanut.modules.book.dao.PayWechatOrderDao; import com.peanut.modules.book.dao.PayWechatOrderDao;
import com.peanut.modules.book.entity.BuyOrderEntity;
import com.peanut.modules.book.entity.PayWechatOrderEntity; import com.peanut.modules.book.entity.PayWechatOrderEntity;
import com.peanut.modules.book.service.BuyOrderService;
import com.peanut.modules.book.service.PayWechatOrderService; import com.peanut.modules.book.service.PayWechatOrderService;
import com.peanut.modules.book.service.PayZfbOrderService; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Map; import java.util.Map;
@Service("payWechatOrderService") @Service("payWechatOrderService")
public class PayWechatOrderServiceImpl extends ServiceImpl<PayWechatOrderDao, PayWechatOrderEntity> implements PayWechatOrderService { public class PayWechatOrderServiceImpl extends ServiceImpl<PayWechatOrderDao, PayWechatOrderEntity> implements PayWechatOrderService {
@Autowired
BuyOrderService buyOrderService;
@Override @Override
public PageUtils queryPage(Map<String, Object> params) { public PageUtils queryPage(Map<String, Object> params) {
IPage<PayWechatOrderEntity> page = this.page( IPage<PayWechatOrderEntity> page = this.page(
@@ -27,4 +33,21 @@ public class PayWechatOrderServiceImpl extends ServiceImpl<PayWechatOrderDao, Pa
return new PageUtils(page); return new PageUtils(page);
} }
@Override
public void add(String orderSn, String prepayId) {
QueryWrapper<BuyOrderEntity> wrapper = new QueryWrapper<>();
wrapper.eq("order_sn", orderSn);
BuyOrderEntity buyOrder = buyOrderService.getOne(wrapper);
PayWechatOrderEntity entity = new PayWechatOrderEntity();
entity.setCustomerId(buyOrder.getUserId());
entity.setCreateTime(new Date());
entity.setOrderSn(buyOrder.getOrderSn());
entity.setPrepayId(prepayId);
entity.setTotalAmount(buyOrder.getRealMoney());
entity.setSystemLog("预支付完成");
entity.setPayType(buyOrder.getOrderType());
entity.setOrderId(buyOrder.getOrderSn());
this.save(entity);
}
} }

View File

@@ -0,0 +1,32 @@
package com.peanut.modules.mq.Consumer;
import com.peanut.config.Constants;
import com.peanut.config.DelayQueueConfig;
import com.peanut.modules.book.entity.BuyOrderEntity;
import com.peanut.modules.book.service.BuyOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @Description: 消息超时取消死信队列消费者
* @Author: Cauchy
* @CreateTime: 2023/10/10
*/
@Component
public class OrderCancelConsumer {
@Autowired
BuyOrderService buyOrderService;
@RabbitListener(queues = DelayQueueConfig.ORDER_CANCEL_DEAD_LETTER_QUEUE)
public void orderConsumer(String orderId) {
BuyOrderEntity buyOrder = buyOrderService.getById(orderId);
if(buyOrder == null){
return;
}
if(Constants.ORDER_STATUS_TO_BE_PAID.equals(buyOrder.getOrderStatus())){
buyOrder.setOrderStatus(Constants.ORDER_STATUS_OUT_OF_TIME);
}
buyOrderService.updateById(buyOrder);
}
}

View File

@@ -1,6 +1,5 @@
package com.peanut.modules.pay.weChatPay.controller; package com.peanut.modules.pay.weChatPay.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@@ -8,26 +7,19 @@ import com.peanut.common.utils.R;
import com.peanut.modules.book.entity.*; import com.peanut.modules.book.entity.*;
import com.peanut.modules.book.service.*; import com.peanut.modules.book.service.*;
import com.peanut.modules.pay.weChatPay.config.WechatPayConfig; import com.peanut.modules.pay.weChatPay.config.WechatPayConfig;
import com.peanut.modules.pay.weChatPay.dto.WechatDto; import com.peanut.modules.pay.weChatPay.dto.WechatPaymentInfo;
import com.peanut.modules.pay.weChatPay.util.HttpUtils; import com.peanut.modules.pay.weChatPay.util.HttpUtils;
import com.peanut.modules.pay.weChatPay.util.WechatPayValidator; import com.peanut.modules.pay.weChatPay.util.WechatPayValidator;
import com.peanut.modules.pay.weChatPay.util.WxPayUtil; import com.peanut.modules.pay.weChatPay.util.WxPayUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.*; import java.util.*;
@@ -66,104 +58,46 @@ public class WeChatPayController {
@Autowired @Autowired
private UserEbookBuyService userEbookBuyService; private UserEbookBuyService userEbookBuyService;
//无需应答签名
@Autowired
private CloseableHttpClient wxPayClient;
@Autowired @Autowired
private WxPayUtil wxPayUtil; private WxPayUtil wxPayUtil;
/** /**
* 生成预订单 * 生成预订单
* *
* @param dto * @param paymentInfo 微信支付信息
* @return * @return
* @throws Exception * @throws Exception
*/ */
@RequestMapping(value = "/placeAnOrder/shoppingPay") @RequestMapping(value = "/placeAnOrder/shoppingPay")
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public R shoppingPay(@RequestBody WechatDto dto) throws Exception { public R newShoppingPay(@RequestBody WechatPaymentInfo paymentInfo) {
log.info("生成预订单");
QueryWrapper<BuyOrderEntity> queryWrapper = new QueryWrapper<>(); QueryWrapper<BuyOrderEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("order_sn", dto.getOrderSn()); queryWrapper.eq("order_sn", paymentInfo.getOrderSn());
BuyOrderEntity order = buyOrderService.getOne(queryWrapper); BuyOrderEntity order = buyOrderService.getOne(queryWrapper);
// 判断订单是否已经过期
Map<String, Object> paramMap = new HashMap<>(); if (order.getOrderStatus().equals("5")) {
paramMap.put("appid", wechatPayConfig.getAppId()); return R.error("订单支付超时");
paramMap.put("mchid", wechatPayConfig.getMchId()); }
paramMap.put("description", "微信支付");
// 订单编号
paramMap.put("out_trade_no", order.getOrderSn());
// 微信回调地址
paramMap.put("notify_url", wechatPayConfig.getNotifyUrl());
BigDecimal totalAmount = dto.getTotalAmount();
// 这里 * 100 单位为 ‘分’
BigDecimal hand = new BigDecimal("100");
totalAmount = totalAmount.multiply(hand);
Map<String, Object> amountMap = new HashMap<>();
amountMap.put("total", totalAmount);
amountMap.put("currency", "CNY");
paramMap.put("amount", amountMap);
JSONObject json = JSONObject.parseObject(JSON.toJSONString(paramMap));
log.info("请求参数:{}", paramMap);
JSONObject responseJson = wxPayUtil.doPostWexinV3(wechatPayConfig.getPayUrl(), json.toJSONString());
String prepayId = responseJson.getString("prepay_id");
// 传入参数 payUrl 发送post请求
HttpPost httpPost = new HttpPost(wechatPayConfig.getPayUrl());
// 将json数据转换成字符串
StringEntity entity = new StringEntity(json.toString(), "utf-8");
// 设置该请求的Content-Type为application/json 都是json格式
entity.setContentType("application/json");
// 将实体对象设置到HttpPost表示要传递该数据到服务器端。
httpPost.setEntity(entity);
// 设置请求头部的Accept属性为"application/json"表示客户端希望接收的为json。
httpPost.setHeader("Accept", "application/json");
CloseableHttpResponse response = wxPayClient.execute(httpPost);
// 向微信支付平台发送请求,处理响应结果,并将订单信息保存到数据库中。
String bodyAsString = EntityUtils.toString(response.getEntity());
// 时间戳
long timestamp = System.currentTimeMillis() / 1000;
// 随机串
String nonceStr = UUID.randomUUID().toString().replace("-", ""); String nonceStr = UUID.randomUUID().toString().replace("-", "");
String sign = wxPayUtil.getSign(wechatPayConfig.getAppId(), timestamp, nonceStr, prepayId); Map<String, Object> paramMap = new HashMap<>();
log.info("签名:{}", sign);
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("prepayid", prepayId); paramMap.put("appid", wechatPayConfig.getAppId());
map.put("timestamp", timestamp);
map.put("noncestr", nonceStr); map.put("noncestr", nonceStr);
map.put("sign", sign);
map.put("appid", wechatPayConfig.getAppId());
map.put("package", "Sign=WXPay"); map.put("package", "Sign=WXPay");
map.put("extData", "sign"); paramMap.put("mchid", wechatPayConfig.getMchId());
map.put("partnerid", wechatPayConfig.getMchId()); QueryWrapper<PayWechatOrderEntity> wechatOrderQueryWrapper = new QueryWrapper<>();
try { wechatOrderQueryWrapper.eq("order_sn", paymentInfo.getOrderSn());
int statusCode = response.getStatusLine().getStatusCode(); PayWechatOrderEntity payWechatOrder = payWechatOrderService.getOne(wechatOrderQueryWrapper);
if (statusCode == 200) { String prepayId = payWechatOrder.getPrepayId();
log.info("返回结果:{}", bodyAsString); map.put("prepayid", prepayId);
// 添加微信支付订单信息 long timestamp = System.currentTimeMillis() / 1000;
PayWechatOrderEntity wechat = new PayWechatOrderEntity(); map.put("timestamp", timestamp);
wechat.setCustomerId(order.getUserId()); String sign = wxPayUtil.getSign(wechatPayConfig.getAppId(), timestamp, nonceStr, prepayId);
wechat.setCreateTime(new Date()); map.put("sign", sign);
wechat.setOrderSn(order.getOrderSn()); Map<String, Object> result = new HashMap<>();
wechat.setPrepayId(prepayId); result.put("paramMap", paramMap);
wechat.setTotalAmount(order.getRealMoney()); result.put("Map", map);
wechat.setSystemLog(response.toString()); return R.ok(result);
wechat.setPayType(order.getOrderType());
wechat.setOrderId(order.getOrderSn());
wechat.setBuyOrderId(dto.getBuyOrderId());
this.payWechatOrderService.save(wechat);
} else if (statusCode == 204) { //处理成功无返回Body
log.info("支付成功");
} else {
log.error("下单失败,响应码为:{},返回结果:{}", statusCode, bodyAsString);
throw new IOException("request failed");
}
} finally {
response.close();
}
return R.ok().put("paramMap", paramMap).put("Map", map);
} }
/** /**

View File

@@ -6,7 +6,7 @@ import java.io.Serializable;
import java.math.BigDecimal; import java.math.BigDecimal;
@Data @Data
public class WechatDto implements Serializable { public class WechatPaymentInfo implements Serializable {
/** /**
* 订单号 * 订单号

View File

@@ -1,15 +1,17 @@
package com.peanut.modules.pay.weChatPay.service; package com.peanut.modules.pay.weChatPay.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.peanut.common.utils.R;
import com.peanut.modules.book.entity.PayWechatOrderEntity; import com.peanut.modules.book.entity.PayWechatOrderEntity;
import com.peanut.modules.pay.weChatPay.dto.WechatDto; import com.peanut.modules.pay.weChatPay.dto.WechatPaymentInfo;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import java.io.IOException;
import java.util.Map;
@Service @Service
public interface WxpayService extends IService<PayWechatOrderEntity> { public interface WxpayService extends IService<PayWechatOrderEntity> {
void prepay(WechatPaymentInfo wechatDto) throws IOException;
} }

View File

@@ -1,11 +1,63 @@
package com.peanut.modules.pay.weChatPay.service.impl; package com.peanut.modules.pay.weChatPay.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.peanut.modules.book.dao.PayWechatOrderDao; import com.peanut.modules.book.dao.PayWechatOrderDao;
import com.peanut.modules.book.entity.PayWechatOrderEntity; import com.peanut.modules.book.entity.PayWechatOrderEntity;
import com.peanut.modules.book.service.PayWechatOrderService;
import com.peanut.modules.pay.weChatPay.config.WechatPayConfig;
import com.peanut.modules.pay.weChatPay.dto.WechatPaymentInfo;
import com.peanut.modules.pay.weChatPay.service.WxpayService; import com.peanut.modules.pay.weChatPay.service.WxpayService;
import com.peanut.modules.pay.weChatPay.util.WxPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service @Service
public class WxpayServiceImpl extends ServiceImpl<PayWechatOrderDao ,PayWechatOrderEntity> implements WxpayService { public class WxpayServiceImpl extends ServiceImpl<PayWechatOrderDao, PayWechatOrderEntity> implements WxpayService {
@Autowired
private WxPayUtil wxPayUtil;
@Autowired
private WechatPayConfig wechatPayConfig;
@Autowired
private PayWechatOrderService payWechatOrderService;
@Override
public void prepay(WechatPaymentInfo paymentInfo) throws IOException {
Map<String, Object> paramMap = new HashMap<>();
// app id
paramMap.put("appid", wechatPayConfig.getAppId());
// 商户 id
paramMap.put("mchid", wechatPayConfig.getMchId());
// 描述
paramMap.put("description", "微信支付");
// 订单编号
paramMap.put("out_trade_no", paymentInfo.getOrderSn());
// 微信回调地址
paramMap.put("notify_url", wechatPayConfig.getNotifyUrl());
BigDecimal totalAmount = paymentInfo.getTotalAmount();
// 这里 * 100 单位为 ‘分’
BigDecimal hand = new BigDecimal("100");
totalAmount = totalAmount.multiply(hand);
Map<String, Object> amountMap = new HashMap<>();
amountMap.put("total", totalAmount.intValue());
amountMap.put("currency", "CNY");
paramMap.put("amount", amountMap);
JSONObject json = JSONObject.parseObject(JSON.toJSONString(paramMap));
log.info("请求参数:{}", paramMap);
JSONObject responseJson = wxPayUtil.doPostWexinV3(wechatPayConfig.getPayUrl(), json.toJSONString());
String prepayId = responseJson.getString("prepay_id");
payWechatOrderService.add(paymentInfo.getOrderSn(), prepayId);
}
} }

View File

@@ -11,7 +11,7 @@ connection-timeout: 6000000ms
spring: spring:
# 环境 dev|test|prod # 环境 dev|test|prod
profiles: profiles:
active: dev active: prod
# jackson时间格式化 # jackson时间格式化
jackson: jackson:
time-zone: GMT+8 time-zone: GMT+8

View File

@@ -12,6 +12,7 @@ wxpay.refundNotifyUrl:http://pjm6m9.natappfree.cc/pay/refundNotify
wxpay.keyPemPath:/usr/local/hs/peanut_book/target/classes/cent/apiclient_key.pem wxpay.keyPemPath:/usr/local/hs/peanut_book/target/classes/cent/apiclient_key.pem
#wxpay.keyPemPath:C:/Users/Cauchy/IdeaProjects/nuttyreading-java/src/main/resources/cent/apiclient_key.pem #wxpay.keyPemPath:C:/Users/Cauchy/IdeaProjects/nuttyreading-java/src/main/resources/cent/apiclient_key.pem
#wxpay.keyPemPath:D:/hs/nuttyreading-java/src/main/resources/cent/apiclient_key.pem #wxpay.keyPemPath:D:/hs/nuttyreading-java/src/main/resources/cent/apiclient_key.pem
#wxpay.keyPemPath:/usr/local/hs/peanut_book/target/classes/cent/apiclient_key.pem
# ??? # ???
wxpay.serialNo:679AECB2F7AC4183033F713828892BA640E4EEE3 wxpay.serialNo:679AECB2F7AC4183033F713828892BA640E4EEE3
# API v3 key # API v3 key