OrderService.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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.dto.NFTAccount;
  17. import com.izouma.nineth.dto.PageQuery;
  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.CollectionRepo;
  22. import com.izouma.nineth.repo.OrderRepo;
  23. import com.izouma.nineth.repo.UserAddressRepo;
  24. import com.izouma.nineth.repo.UserRepo;
  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.http.client.utils.URLEncodedUtils;
  35. import org.springframework.core.env.Environment;
  36. import org.springframework.data.domain.Page;
  37. import org.springframework.stereotype.Service;
  38. import org.springframework.ui.Model;
  39. import javax.transaction.Transactional;
  40. import java.math.BigDecimal;
  41. import java.time.LocalDateTime;
  42. import java.util.Arrays;
  43. import java.util.Map;
  44. import java.util.Optional;
  45. import java.util.UUID;
  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. public Page<Order> all(PageQuery pageQuery) {
  61. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  62. }
  63. @Transactional
  64. public Order create(Long userId, Long collectionId, int qty, Long addressId) {
  65. if (qty <= 0) throw new BusinessException("数量必须大于0");
  66. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  67. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  68. User minter = userRepo.findById(collection.getMinterId()).orElseThrow(new BusinessException("铸造者不存在"));
  69. if (!collection.isOnShelf()) {
  70. throw new BusinessException("藏品已下架");
  71. }
  72. if (qty > collection.getStock()) {
  73. throw new BusinessException("库存不足");
  74. }
  75. UserAddress userAddress = null;
  76. if (addressId != null) {
  77. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  78. }
  79. collection.setStock(collection.getStock() - qty);
  80. collection.setSale(collection.getSale() + qty);
  81. collectionRepo.save(collection);
  82. minter.setSales(minter.getSales() + 1);
  83. Order order = Order.builder()
  84. .userId(userId)
  85. .collectionId(collectionId)
  86. .name(collection.getName())
  87. .pic(collection.getPics())
  88. .properties(collection.getProperties())
  89. .minter(minter.getNickname())
  90. .minterAvatar(minter.getAvatar())
  91. .qty(qty)
  92. .price(collection.getPrice())
  93. .gasPrice(BigDecimal.valueOf(1))
  94. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(BigDecimal.valueOf(1)))
  95. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  96. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  97. .address(Optional.ofNullable(userAddress).map(u ->
  98. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  99. .orElse(null))
  100. .status(OrderStatus.NOT_PAID)
  101. .build();
  102. return orderRepo.save(order);
  103. }
  104. public void payOrderAlipay(Long id, Model model) {
  105. try {
  106. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  107. if (order.getStatus() != OrderStatus.NOT_PAID) {
  108. throw new BusinessException("订单状态错误");
  109. }
  110. JSONObject bizContent = new JSONObject();
  111. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  112. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  113. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  114. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  115. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  116. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  117. // 测试环境设为1分
  118. bizContent.put("total_amount", "0.01");
  119. }
  120. bizContent.put("subject", order.getName());
  121. bizContent.put("product_code", "QUICK_WAP_PAY");
  122. JSONObject body = new JSONObject();
  123. body.put("action", "payOrder");
  124. body.put("userId", order.getUserId());
  125. body.put("orderId", order.getId());
  126. bizContent.put("body", body.toJSONString());
  127. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  128. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  129. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  130. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  131. String form = alipayClient.pageExecute(alipayRequest).getBody();
  132. model.addAttribute("form", form);
  133. } catch (BusinessException err) {
  134. model.addAttribute("errMsg", err.getError());
  135. } catch (Exception e) {
  136. model.addAttribute("errMsg", e.getMessage());
  137. }
  138. }
  139. public String payOrderWeixinH5(Long id) throws WxPayException, EncoderException {
  140. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  141. if (order.getStatus() != OrderStatus.NOT_PAID) {
  142. throw new BusinessException("订单状态错误");
  143. }
  144. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  145. request.setBody(order.getName());
  146. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  147. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  148. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  149. // 测试环境设为1分
  150. // request.setTotalFee(1);
  151. }
  152. request.setSpbillCreateIp("180.102.110.170");
  153. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  154. request.setTradeType(WxPayConstants.TradeType.MWEB);
  155. request.setSignType("MD5");
  156. JSONObject body = new JSONObject();
  157. body.put("action", "payOrder");
  158. body.put("userId", order.getUserId());
  159. body.put("orderId", order.getId());
  160. request.setAttach(body.toJSONString());
  161. WxPayMwebOrderResult result = wxPayService. createOrder(request);
  162. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  163. }
  164. public Object payOrderWeixin(Long id) throws WxPayException {
  165. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  166. if (order.getStatus() != OrderStatus.NOT_PAID) {
  167. throw new BusinessException("订单状态错误");
  168. }
  169. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  170. request.setBody(order.getName());
  171. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  172. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  173. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  174. // 测试环境设为1分
  175. // request.setTotalFee(1);
  176. }
  177. request.setSpbillCreateIp("180.102.110.170");
  178. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  179. request.setTradeType(WxPayConstants.TradeType.JSAPI);
  180. request.setOpenid(SecurityUtils.getAuthenticatedUser().getOpenId());
  181. request.setSignType("MD5");
  182. JSONObject body = new JSONObject();
  183. body.put("action", "payOrder");
  184. body.put("userId", order.getUserId());
  185. body.put("orderId", order.getId());
  186. request.setAttach(body.toJSONString());
  187. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  188. }
  189. public void notifyAlipay(Long orderId, Map<String, String> params) {
  190. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  191. if (order.getStatus() == OrderStatus.NOT_PAID) {
  192. Asset asset = null;
  193. try {
  194. asset = assetService.createAsset(order);
  195. order.setStatus(OrderStatus.PROCESSING);
  196. order.setPayTime(LocalDateTime.now());
  197. order.setTransactionId(MapUtils.getString(params, "trade_no"));
  198. order.setPayMethod(PayMethod.ALIPAY);
  199. orderRepo.save(order);
  200. if (asset != null) {
  201. order.setTxHash(asset.getTxHash());
  202. order.setGasUsed(asset.getGasUsed());
  203. order.setBlockNumber(asset.getBlockNumber());
  204. order.setStatus(OrderStatus.FINISH);
  205. orderRepo.save(order);
  206. }
  207. } catch (Exception e) {
  208. log.error("支付宝回调出错", e);
  209. }
  210. }
  211. }
  212. }