OrderService.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alipay.api.AlipayClient;
  5. import com.alipay.api.request.AlipayTradeWapPayRequest;
  6. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  7. import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
  8. import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
  9. import com.github.binarywang.wxpay.constant.WxPayConstants;
  10. import com.github.binarywang.wxpay.exception.WxPayException;
  11. import com.github.binarywang.wxpay.service.WxPayService;
  12. import com.izouma.nineth.config.AlipayProperties;
  13. import com.izouma.nineth.config.WxPayProperties;
  14. import com.izouma.nineth.domain.Collection;
  15. import com.izouma.nineth.domain.*;
  16. import com.izouma.nineth.dto.PageQuery;
  17. import com.izouma.nineth.enums.CollectionType;
  18. import com.izouma.nineth.enums.OrderStatus;
  19. import com.izouma.nineth.enums.PayMethod;
  20. import com.izouma.nineth.event.CreateAssetEvent;
  21. import com.izouma.nineth.exception.BusinessException;
  22. import com.izouma.nineth.repo.*;
  23. import com.izouma.nineth.utils.JpaUtils;
  24. import com.izouma.nineth.utils.SnowflakeIdWorker;
  25. import lombok.AllArgsConstructor;
  26. import lombok.extern.slf4j.Slf4j;
  27. import org.apache.commons.codec.EncoderException;
  28. import org.apache.commons.codec.net.URLCodec;
  29. import org.apache.commons.lang3.RandomUtils;
  30. import org.apache.commons.lang3.Range;
  31. import org.springframework.context.event.EventListener;
  32. import org.springframework.core.env.Environment;
  33. import org.springframework.data.domain.Page;
  34. import org.springframework.scheduling.annotation.Scheduled;
  35. import org.springframework.stereotype.Service;
  36. import org.springframework.ui.Model;
  37. import javax.transaction.Transactional;
  38. import java.math.BigDecimal;
  39. import java.time.LocalDateTime;
  40. import java.util.*;
  41. @Service
  42. @AllArgsConstructor
  43. @Slf4j
  44. public class OrderService {
  45. private OrderRepo orderRepo;
  46. private CollectionRepo collectionRepo;
  47. private UserAddressRepo userAddressRepo;
  48. private UserRepo userRepo;
  49. private Environment env;
  50. private AlipayClient alipayClient;
  51. private AlipayProperties alipayProperties;
  52. private WxPayService wxPayService;
  53. private WxPayProperties wxPayProperties;
  54. private AssetService assetService;
  55. private SysConfigService sysConfigService;
  56. private BlindBoxItemRepo blindBoxItemRepo;
  57. public Page<Order> all(PageQuery pageQuery) {
  58. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  59. }
  60. @Transactional
  61. public Order create(Long userId, Long collectionId, int qty, Long addressId) {
  62. if (qty <= 0) throw new BusinessException("数量必须大于0");
  63. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  64. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  65. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  66. if (!collection.isOnShelf()) {
  67. throw new BusinessException("藏品已下架");
  68. }
  69. if (qty > collection.getStock()) {
  70. throw new BusinessException("库存不足");
  71. }
  72. if (!collection.isSalable()) {
  73. throw new BusinessException("该藏品当前不可购买");
  74. }
  75. if (collection.getType() == CollectionType.BLIND_BOX) {
  76. if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  77. throw new BusinessException("盲盒未开售");
  78. }
  79. }
  80. UserAddress userAddress = null;
  81. if (addressId != null) {
  82. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  83. }
  84. collection.setStock(collection.getStock() - qty);
  85. collection.setSale(collection.getSale() + qty);
  86. collectionRepo.save(collection);
  87. minter.setSales(minter.getSales() + 1);
  88. BigDecimal gasFee = sysConfigService.getBigDecimal("gas_fee");
  89. Order order = Order.builder()
  90. .userId(userId)
  91. .collectionId(collectionId)
  92. .name(collection.getName())
  93. .pic(collection.getPics())
  94. .detail(collection.getDetail())
  95. .properties(collection.getProperties())
  96. .category(collection.getCategory())
  97. .canResale(collection.isCanResale())
  98. .royalties(collection.getRoyalties())
  99. .serviceCharge(collection.getServiceCharge())
  100. .type(collection.getType())
  101. .minterId(collection.getMinterId())
  102. .minter(minter.getNickname())
  103. .minterAvatar(minter.getAvatar())
  104. .qty(qty)
  105. .price(collection.getPrice())
  106. .gasPrice(gasFee)
  107. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(gasFee))
  108. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  109. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  110. .address(Optional.ofNullable(userAddress).map(u ->
  111. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  112. .orElse(null))
  113. .status(OrderStatus.NOT_PAID)
  114. .build();
  115. return orderRepo.save(order);
  116. }
  117. public void payOrderAlipay(Long id, Model model) {
  118. try {
  119. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  120. if (order.getStatus() != OrderStatus.NOT_PAID) {
  121. throw new BusinessException("订单状态错误");
  122. }
  123. JSONObject bizContent = new JSONObject();
  124. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  125. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  126. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  127. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  128. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  129. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  130. // 测试环境设为1分
  131. bizContent.put("total_amount", "0.01");
  132. }
  133. bizContent.put("subject", order.getName());
  134. bizContent.put("product_code", "QUICK_WAP_PAY");
  135. JSONObject body = new JSONObject();
  136. body.put("action", "payOrder");
  137. body.put("userId", order.getUserId());
  138. body.put("orderId", order.getId());
  139. bizContent.put("body", body.toJSONString());
  140. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  141. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  142. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  143. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  144. String form = alipayClient.pageExecute(alipayRequest).getBody();
  145. model.addAttribute("form", form);
  146. } catch (BusinessException err) {
  147. model.addAttribute("errMsg", err.getError());
  148. } catch (Exception e) {
  149. model.addAttribute("errMsg", e.getMessage());
  150. }
  151. }
  152. public String payOrderWeixinH5(Long id) throws WxPayException, EncoderException {
  153. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  154. if (order.getStatus() != OrderStatus.NOT_PAID) {
  155. throw new BusinessException("订单状态错误");
  156. }
  157. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  158. request.setBody(order.getName());
  159. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  160. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  161. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  162. // 测试环境设为1分
  163. // request.setTotalFee(1);
  164. }
  165. request.setSpbillCreateIp("180.102.110.170");
  166. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  167. request.setTradeType(WxPayConstants.TradeType.MWEB);
  168. request.setSignType("MD5");
  169. JSONObject body = new JSONObject();
  170. body.put("action", "payOrder");
  171. body.put("userId", order.getUserId());
  172. body.put("orderId", order.getId());
  173. request.setAttach(body.toJSONString());
  174. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  175. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  176. }
  177. public Object payOrderWeixin(Long id, String openId) throws WxPayException {
  178. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  179. if (order.getStatus() != OrderStatus.NOT_PAID) {
  180. throw new BusinessException("订单状态错误");
  181. }
  182. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  183. request.setBody(order.getName());
  184. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  185. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  186. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  187. // 测试环境设为1分
  188. // request.setTotalFee(1);
  189. }
  190. request.setSpbillCreateIp("180.102.110.170");
  191. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  192. request.setTradeType(WxPayConstants.TradeType.JSAPI);
  193. request.setOpenid(openId);
  194. request.setSignType("MD5");
  195. JSONObject body = new JSONObject();
  196. body.put("action", "payOrder");
  197. body.put("userId", order.getUserId());
  198. body.put("orderId", order.getId());
  199. request.setAttach(body.toJSONString());
  200. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  201. }
  202. public void notifyAlipay(Long orderId, PayMethod payMethod, String transactionId) {
  203. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  204. if (order.getStatus() == OrderStatus.NOT_PAID) {
  205. if (order.getType() == CollectionType.BLIND_BOX) {
  206. List<BlindBoxItem> items = blindBoxItemRepo.findByBlindBoxId(order.getCollectionId());
  207. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  208. int c = 0, sum = 0;
  209. for (BlindBoxItem item : items) {
  210. randomRange.put(item, Range.between(c, c + item.getStock()));
  211. c += item.getStock();
  212. sum += item.getStock();
  213. }
  214. int retry = 0;
  215. BlindBoxItem winItem = null;
  216. while (winItem == null) {
  217. retry++;
  218. int rand = RandomUtils.nextInt(0, sum + 1);
  219. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  220. BlindBoxItem item = entry.getKey();
  221. Range<Integer> range = entry.getValue();
  222. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  223. int total = items.stream().filter(i -> !i.isRare())
  224. .mapToInt(BlindBoxItem::getTotal).sum();
  225. int stock = items.stream().filter(i -> !i.isRare())
  226. .mapToInt(BlindBoxItem::getStock).sum();
  227. if (item.isRare()) {
  228. double nRate = stock / (double) total;
  229. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  230. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  231. if (!(nRate > 0.1 && item.getStock() == 1)) {
  232. winItem = item;
  233. }
  234. }
  235. } else {
  236. double nRate = (stock - 1) / (double) total;
  237. double rRate = item.getStock() / (double) item.getTotal();
  238. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  239. winItem = item;
  240. }
  241. }
  242. }
  243. }
  244. if (retry > 100 && winItem == null) {
  245. throw new BusinessException("盲盒抽卡失败");
  246. }
  247. }
  248. winItem.setStock(winItem.getStock() - 1);
  249. winItem.setSale(winItem.getSale() + 1);
  250. order.setStatus(OrderStatus.PROCESSING);
  251. order.setPayTime(LocalDateTime.now());
  252. order.setTransactionId(transactionId);
  253. order.setPayMethod(payMethod);
  254. orderRepo.save(order);
  255. assetService.createAsset(order, winItem);
  256. } else {
  257. order.setStatus(OrderStatus.PROCESSING);
  258. order.setPayTime(LocalDateTime.now());
  259. order.setTransactionId(transactionId);
  260. order.setPayMethod(payMethod);
  261. orderRepo.save(order);
  262. assetService.createAsset(order);
  263. }
  264. } else if (order.getStatus() == OrderStatus.CANCELLED) {
  265. }
  266. }
  267. @EventListener
  268. public void onCreateAsset(CreateAssetEvent event) {
  269. Order order = event.getOrder();
  270. Asset asset = event.getAsset();
  271. if (event.isSuccess()) {
  272. order.setTxHash(asset.getTxHash());
  273. order.setGasUsed(asset.getGasUsed());
  274. order.setBlockNumber(asset.getBlockNumber());
  275. order.setStatus(OrderStatus.FINISH);
  276. orderRepo.save(order);
  277. } else {
  278. log.error("创建asset失败");
  279. }
  280. }
  281. public void cancel(Long id) {
  282. Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  283. cancel(order);
  284. }
  285. public void cancel(Order order) {
  286. if (order.getStatus() != OrderStatus.NOT_PAID) {
  287. throw new BusinessException("已支付订单无法取消");
  288. }
  289. Collection collection = collectionRepo.findById(order.getCollectionId())
  290. .orElseThrow(new BusinessException("藏品不存在"));
  291. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  292. collection.setSale(collection.getSale() - 1);
  293. collection.setStock(collection.getStock() + 1);
  294. collectionRepo.save(collection);
  295. minter.setSales(minter.getSales() - 1);
  296. userRepo.save(minter);
  297. order.setStatus(OrderStatus.CANCELLED);
  298. order.setCancelTime(LocalDateTime.now());
  299. orderRepo.save(order);
  300. }
  301. @Scheduled(fixedRate = 60000)
  302. public void batchCancel() {
  303. List<Order> orders = orderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  304. LocalDateTime.now().minusMinutes(5));
  305. orders.stream().parallel().forEach(this::cancel);
  306. }
  307. public void refundCancelled(Order order) {
  308. }
  309. }