OrderService.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. .type(collection.getType())
  90. .minter(minter.getNickname())
  91. .minterAvatar(minter.getAvatar())
  92. .qty(qty)
  93. .price(collection.getPrice())
  94. .gasPrice(BigDecimal.valueOf(1))
  95. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(BigDecimal.valueOf(1)))
  96. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  97. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  98. .address(Optional.ofNullable(userAddress).map(u ->
  99. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  100. .orElse(null))
  101. .status(OrderStatus.NOT_PAID)
  102. .build();
  103. return orderRepo.save(order);
  104. }
  105. public void payOrderAlipay(Long id, Model model) {
  106. try {
  107. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  108. if (order.getStatus() != OrderStatus.NOT_PAID) {
  109. throw new BusinessException("订单状态错误");
  110. }
  111. JSONObject bizContent = new JSONObject();
  112. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  113. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  114. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  115. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  116. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  117. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  118. // 测试环境设为1分
  119. bizContent.put("total_amount", "0.01");
  120. }
  121. bizContent.put("subject", order.getName());
  122. bizContent.put("product_code", "QUICK_WAP_PAY");
  123. JSONObject body = new JSONObject();
  124. body.put("action", "payOrder");
  125. body.put("userId", order.getUserId());
  126. body.put("orderId", order.getId());
  127. bizContent.put("body", body.toJSONString());
  128. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  129. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  130. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  131. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  132. String form = alipayClient.pageExecute(alipayRequest).getBody();
  133. model.addAttribute("form", form);
  134. } catch (BusinessException err) {
  135. model.addAttribute("errMsg", err.getError());
  136. } catch (Exception e) {
  137. model.addAttribute("errMsg", e.getMessage());
  138. }
  139. }
  140. public String payOrderWeixinH5(Long id) throws WxPayException, EncoderException {
  141. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  142. if (order.getStatus() != OrderStatus.NOT_PAID) {
  143. throw new BusinessException("订单状态错误");
  144. }
  145. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  146. request.setBody(order.getName());
  147. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  148. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  149. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  150. // 测试环境设为1分
  151. // request.setTotalFee(1);
  152. }
  153. request.setSpbillCreateIp("180.102.110.170");
  154. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  155. request.setTradeType(WxPayConstants.TradeType.MWEB);
  156. request.setSignType("MD5");
  157. JSONObject body = new JSONObject();
  158. body.put("action", "payOrder");
  159. body.put("userId", order.getUserId());
  160. body.put("orderId", order.getId());
  161. request.setAttach(body.toJSONString());
  162. WxPayMwebOrderResult result = wxPayService. createOrder(request);
  163. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  164. }
  165. public Object payOrderWeixin(Long id) throws WxPayException {
  166. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  167. if (order.getStatus() != OrderStatus.NOT_PAID) {
  168. throw new BusinessException("订单状态错误");
  169. }
  170. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  171. request.setBody(order.getName());
  172. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  173. request.setTotalFee(order.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue());
  174. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  175. // 测试环境设为1分
  176. // request.setTotalFee(1);
  177. }
  178. request.setSpbillCreateIp("180.102.110.170");
  179. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  180. request.setTradeType(WxPayConstants.TradeType.JSAPI);
  181. request.setOpenid(SecurityUtils.getAuthenticatedUser().getOpenId());
  182. request.setSignType("MD5");
  183. JSONObject body = new JSONObject();
  184. body.put("action", "payOrder");
  185. body.put("userId", order.getUserId());
  186. body.put("orderId", order.getId());
  187. request.setAttach(body.toJSONString());
  188. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  189. }
  190. public void notifyAlipay(Long orderId, Map<String, String> params) {
  191. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  192. if (order.getStatus() == OrderStatus.NOT_PAID) {
  193. Asset asset = null;
  194. try {
  195. asset = assetService.createAsset(order);
  196. order.setStatus(OrderStatus.PROCESSING);
  197. order.setPayTime(LocalDateTime.now());
  198. order.setTransactionId(MapUtils.getString(params, "trade_no"));
  199. order.setPayMethod(PayMethod.ALIPAY);
  200. orderRepo.save(order);
  201. if (asset != null) {
  202. order.setTxHash(asset.getTxHash());
  203. order.setGasUsed(asset.getGasUsed());
  204. order.setBlockNumber(asset.getBlockNumber());
  205. order.setStatus(OrderStatus.FINISH);
  206. orderRepo.save(order);
  207. }
  208. } catch (Exception e) {
  209. log.error("支付宝回调出错", e);
  210. }
  211. }
  212. }
  213. }