GiftOrderService.java 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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.Asset;
  15. import com.izouma.nineth.domain.GiftOrder;
  16. import com.izouma.nineth.domain.User;
  17. import com.izouma.nineth.enums.AssetStatus;
  18. import com.izouma.nineth.enums.OrderStatus;
  19. import com.izouma.nineth.enums.PayMethod;
  20. import com.izouma.nineth.exception.BusinessException;
  21. import com.izouma.nineth.repo.*;
  22. import com.izouma.nineth.utils.SnowflakeIdWorker;
  23. import lombok.AllArgsConstructor;
  24. import org.apache.commons.codec.EncoderException;
  25. import org.apache.commons.codec.net.URLCodec;
  26. import org.springframework.context.ApplicationContext;
  27. import org.springframework.core.env.Environment;
  28. import org.springframework.scheduling.annotation.Scheduled;
  29. import org.springframework.stereotype.Service;
  30. import org.springframework.ui.Model;
  31. import javax.transaction.Transactional;
  32. import java.math.BigDecimal;
  33. import java.time.LocalDateTime;
  34. import java.util.Arrays;
  35. import java.util.List;
  36. @Service
  37. @AllArgsConstructor
  38. public class GiftOrderService {
  39. private AssetRepo assetRepo;
  40. private UserRepo userRepo;
  41. private NFTService nftService;
  42. private CollectionRepo collectionRepo;
  43. private ApplicationContext applicationContext;
  44. private OrderRepo orderRepo;
  45. private SysConfigService sysConfigService;
  46. private GiftOrderRepo giftOrderRepo;
  47. private TokenHistoryRepo tokenHistoryRepo;
  48. private AlipayProperties alipayProperties;
  49. private AlipayClient alipayClient;
  50. private WxPayProperties wxPayProperties;
  51. private WxPayService wxPayService;
  52. private Environment env;
  53. private AssetMintService assetMintService;
  54. private AssetService assetService;
  55. @Transactional
  56. public GiftOrder gift(Long userId, Long assetId, Long toUserId) {
  57. Asset asset = assetRepo.findById(assetId).orElseThrow(new BusinessException("资产不存在"));
  58. if (!(asset.getStatus() == AssetStatus.NORMAL)) {
  59. throw new BusinessException("当前状态不可转赠");
  60. }
  61. if (asset.isConsignment()) {
  62. throw new BusinessException("请先取消寄售");
  63. }
  64. if (asset.isPublicShow()) {
  65. assetService.cancelPublic(asset);
  66. }
  67. asset.setStatus(AssetStatus.GIFTING);
  68. assetRepo.save(asset);
  69. GiftOrder giftOrder = GiftOrder.builder()
  70. .userId(userId)
  71. .assetId(assetId)
  72. .toUserId(toUserId)
  73. .gasPrice(sysConfigService.getBigDecimal("gas_fee"))
  74. .status(OrderStatus.NOT_PAID)
  75. .build();
  76. return giftOrderRepo.save(giftOrder);
  77. }
  78. @Transactional
  79. public void giftNotify(Long orderId, PayMethod payMethod, String transactionId) {
  80. GiftOrder giftOrder = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  81. Asset asset = assetRepo.findById(giftOrder.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  82. User newOwner = userRepo.findById(giftOrder.getToUserId()).orElseThrow(new BusinessException("用户不存在"));
  83. giftOrder.setPayMethod(payMethod);
  84. giftOrder.setStatus(OrderStatus.FINISH);
  85. giftOrder.setTransactionId(transactionId);
  86. giftOrder.setPayTime(LocalDateTime.now());
  87. giftOrder.setPayMethod(PayMethod.ALIPAY);
  88. assetService.transfer(asset, asset.getPrice(), newOwner, "转赠", null);
  89. }
  90. public void payOrderAlipay(Long id, Model model) {
  91. try {
  92. GiftOrder order = giftOrderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  93. if (order.getStatus() != OrderStatus.NOT_PAID) {
  94. throw new BusinessException("订单状态错误");
  95. }
  96. JSONObject bizContent = new JSONObject();
  97. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  98. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  99. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  100. bizContent.put("total_amount", order.getGasPrice().stripTrailingZeros().toPlainString());
  101. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  102. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  103. // 测试环境设为1分
  104. bizContent.put("total_amount", "0.01");
  105. }
  106. bizContent.put("subject", "转赠GAS费");
  107. bizContent.put("product_code", "QUICK_WAP_PAY");
  108. JSONObject body = new JSONObject();
  109. body.put("action", "payGiftOrder");
  110. body.put("userId", order.getUserId());
  111. body.put("orderId", order.getId());
  112. bizContent.put("body", body.toJSONString());
  113. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  114. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  115. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  116. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  117. String form = alipayClient.pageExecute(alipayRequest).getBody();
  118. model.addAttribute("form", form);
  119. } catch (BusinessException err) {
  120. model.addAttribute("errMsg", err.getError());
  121. } catch (Exception e) {
  122. model.addAttribute("errMsg", e.getMessage());
  123. }
  124. }
  125. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  126. GiftOrder order = giftOrderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  127. if (order.getStatus() != OrderStatus.NOT_PAID) {
  128. throw new BusinessException("订单状态错误");
  129. }
  130. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  131. request.setBody("转赠GAS费");
  132. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  133. request.setTotalFee(order.getGasPrice().multiply(BigDecimal.valueOf(100)).intValue());
  134. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  135. // 测试环境设为1分
  136. // request.setTotalFee(1);
  137. }
  138. request.setSpbillCreateIp("180.102.110.170");
  139. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  140. request.setTradeType(tradeType);
  141. request.setOpenid(openId);
  142. request.setSignType("MD5");
  143. JSONObject body = new JSONObject();
  144. body.put("action", "payGiftOrder");
  145. body.put("userId", order.getUserId());
  146. body.put("orderId", order.getId());
  147. request.setAttach(body.toJSONString());
  148. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  149. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  150. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  151. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  152. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  153. }
  154. throw new BusinessException("不支持此付款方式");
  155. }
  156. @Scheduled(fixedRate = 60000)
  157. public void batchCancel() {
  158. List<GiftOrder> orders = giftOrderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  159. LocalDateTime.now().minusMinutes(5));
  160. orders.forEach(o -> {
  161. try {
  162. cancel(o);
  163. } catch (Exception ignored) {
  164. }
  165. });
  166. }
  167. public void cancel(GiftOrder order) {
  168. if (order.getStatus() != OrderStatus.NOT_PAID) {
  169. throw new BusinessException("已支付订单无法取消");
  170. }
  171. Asset asset = assetRepo.findById(order.getAssetId()).orElseThrow(new BusinessException("藏品不存在"));
  172. asset.setStatus(AssetStatus.NORMAL);
  173. assetRepo.save(asset);
  174. order.setStatus(OrderStatus.CANCELLED);
  175. order.setCancelTime(LocalDateTime.now());
  176. giftOrderRepo.save(order);
  177. }
  178. }