OrderService.java 16 KB

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