OrderService.java 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alipay.api.AlipayApiException;
  5. import com.alipay.api.AlipayClient;
  6. import com.alipay.api.request.AlipayTradeWapPayRequest;
  7. import com.izouma.nineth.config.AlipayProperties;
  8. import com.izouma.nineth.domain.*;
  9. import com.izouma.nineth.dto.NFTAccount;
  10. import com.izouma.nineth.dto.PageQuery;
  11. import com.izouma.nineth.enums.OrderStatus;
  12. import com.izouma.nineth.enums.PayMethod;
  13. import com.izouma.nineth.exception.BusinessException;
  14. import com.izouma.nineth.repo.CollectionRepo;
  15. import com.izouma.nineth.repo.OrderRepo;
  16. import com.izouma.nineth.repo.UserAddressRepo;
  17. import com.izouma.nineth.repo.UserRepo;
  18. import com.izouma.nineth.utils.JpaUtils;
  19. import com.izouma.nineth.utils.SnowflakeIdWorker;
  20. import lombok.AllArgsConstructor;
  21. import lombok.extern.slf4j.Slf4j;
  22. import org.apache.commons.collections.MapUtils;
  23. import org.springframework.core.env.Environment;
  24. import org.springframework.data.domain.Page;
  25. import org.springframework.stereotype.Service;
  26. import org.springframework.ui.Model;
  27. import javax.transaction.Transactional;
  28. import java.math.BigDecimal;
  29. import java.time.LocalDateTime;
  30. import java.util.Arrays;
  31. import java.util.Map;
  32. import java.util.Optional;
  33. import java.util.UUID;
  34. @Service
  35. @AllArgsConstructor
  36. @Slf4j
  37. public class OrderService {
  38. private OrderRepo orderRepo;
  39. private CollectionRepo collectionRepo;
  40. private UserAddressRepo userAddressRepo;
  41. private UserRepo userRepo;
  42. private Environment env;
  43. private AlipayClient alipayClient;
  44. private AlipayProperties alipayProperties;
  45. private AssetService assetService;
  46. public Page<Order> all(PageQuery pageQuery) {
  47. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  48. }
  49. @Transactional
  50. public Order create(Long userId, Long collectionId, int qty, Long addressId) {
  51. if (qty <= 0) throw new BusinessException("数量必须大于0");
  52. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  53. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  54. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  55. if (!collection.isOnShelf()) {
  56. throw new BusinessException("藏品已下架");
  57. }
  58. if (qty > collection.getStock()) {
  59. throw new BusinessException("库存不足");
  60. }
  61. UserAddress userAddress = null;
  62. if (addressId != null) {
  63. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  64. }
  65. collection.setStock(collection.getStock() - qty);
  66. collection.setSale(collection.getSale() + qty);
  67. collectionRepo.save(collection);
  68. minter.setSales(minter.getSales() + 1);
  69. Order order = Order.builder()
  70. .userId(userId)
  71. .collectionId(collectionId)
  72. .name(collection.getName())
  73. .pic(collection.getPics())
  74. .minter(minter.getNickname())
  75. .minterAvatar(minter.getAvatar())
  76. .qty(qty)
  77. .price(collection.getPrice())
  78. .gasPrice(BigDecimal.valueOf(1))
  79. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(BigDecimal.valueOf(1)))
  80. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  81. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  82. .address(Optional.ofNullable(userAddress).map(u ->
  83. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  84. .orElse(null))
  85. .status(OrderStatus.NOT_PAID)
  86. .build();
  87. return orderRepo.save(order);
  88. }
  89. public void payOrderAlipay(Long id, Model model) {
  90. try {
  91. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  92. if (order.getStatus() != OrderStatus.NOT_PAID) {
  93. throw new BusinessException("订单状态错误");
  94. }
  95. JSONObject bizContent = new JSONObject();
  96. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  97. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  98. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  99. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  100. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  101. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  102. // 测试环境设为1分
  103. bizContent.put("total_amount", "0.01");
  104. }
  105. bizContent.put("subject", order.getName());
  106. bizContent.put("product_code", "QUICK_WAP_PAY");
  107. JSONObject body = new JSONObject();
  108. body.put("action", "payOrder");
  109. body.put("userId", order.getUserId());
  110. body.put("orderId", order.getId());
  111. bizContent.put("body", body.toJSONString());
  112. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  113. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  114. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  115. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  116. String form = alipayClient.pageExecute(alipayRequest).getBody();
  117. model.addAttribute("form", form);
  118. } catch (BusinessException err) {
  119. model.addAttribute("errMsg", err.getError());
  120. } catch (Exception e) {
  121. model.addAttribute("errMsg", e.getMessage());
  122. }
  123. }
  124. public Object payOrderWeixin(Long id) {
  125. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  126. if (order.getStatus() != OrderStatus.NOT_PAID) {
  127. throw new BusinessException("订单状态错误");
  128. }
  129. return null;
  130. }
  131. public void notifyAlipay(Long orderId, Map<String, String> params) {
  132. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  133. if (order.getStatus() == OrderStatus.NOT_PAID) {
  134. Asset asset = null;
  135. try {
  136. asset = assetService.createAsset(order);
  137. order.setStatus(OrderStatus.PROCESSING);
  138. order.setPayTime(LocalDateTime.now());
  139. order.setTransactionId(MapUtils.getString(params, "trade_no"));
  140. order.setPayMethod(PayMethod.ALIPAY);
  141. orderRepo.save(order);
  142. if (asset != null) {
  143. order.setTxHash(asset.getTxHash());
  144. order.setGasUsed(asset.getGasUsed());
  145. order.setBlockNumber(asset.getBlockNumber());
  146. order.setStatus(OrderStatus.FINISH);
  147. orderRepo.save(order);
  148. }
  149. } catch (Exception e) {
  150. log.error("支付宝回调出错", e);
  151. }
  152. }
  153. }
  154. }