OrderService.java 14 KB

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