OrderService.java 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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.izouma.nineth.config.AlipayProperties;
  8. import com.izouma.nineth.domain.Collection;
  9. import com.izouma.nineth.domain.Order;
  10. import com.izouma.nineth.domain.User;
  11. import com.izouma.nineth.domain.UserAddress;
  12. import com.izouma.nineth.dto.PageQuery;
  13. import com.izouma.nineth.enums.OrderStatus;
  14. import com.izouma.nineth.enums.PayMethod;
  15. import com.izouma.nineth.exception.BusinessException;
  16. import com.izouma.nineth.repo.CollectionRepo;
  17. import com.izouma.nineth.repo.OrderRepo;
  18. import com.izouma.nineth.repo.UserAddressRepo;
  19. import com.izouma.nineth.repo.UserRepo;
  20. import com.izouma.nineth.utils.JpaUtils;
  21. import lombok.AllArgsConstructor;
  22. import org.springframework.core.env.Environment;
  23. import org.springframework.data.domain.Page;
  24. import org.springframework.stereotype.Service;
  25. import javax.transaction.Transactional;
  26. import java.math.BigDecimal;
  27. import java.util.Arrays;
  28. import java.util.Optional;
  29. import java.util.UUID;
  30. @Service
  31. @AllArgsConstructor
  32. public class OrderService {
  33. private OrderRepo orderRepo;
  34. private CollectionRepo collectionRepo;
  35. private UserAddressRepo userAddressRepo;
  36. private UserRepo userRepo;
  37. private Environment env;
  38. private AlipayClient alipayClient;
  39. private AlipayProperties alipayProperties;
  40. public Page<Order> all(PageQuery pageQuery) {
  41. return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery));
  42. }
  43. @Transactional
  44. public Order create(Long userId, Long collectionId, int qty, Long addressId) {
  45. if (qty <= 0) throw new BusinessException("数量必须大于0");
  46. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  47. Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在"));
  48. if (!collection.isOnShelf()) {
  49. throw new BusinessException("藏品已下架");
  50. }
  51. if (qty > collection.getStock()) {
  52. throw new BusinessException("库存不足");
  53. }
  54. UserAddress userAddress = null;
  55. if (addressId != null) {
  56. userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在"));
  57. }
  58. collection.setStock(collection.getStock() - qty);
  59. collection.setSale(collection.getSale() + qty);
  60. collectionRepo.save(collection);
  61. User minter = userRepo.findById(collection.getMinterId()).orElse(null);
  62. Order order = Order.builder()
  63. .userId(userId)
  64. .collectionId(collectionId)
  65. .name(collection.getName())
  66. .pic(collection.getPics())
  67. .minter(Optional.ofNullable(minter).map(User::getNickname).orElse(collection.getMinter()))
  68. .minterAvatar(Optional.ofNullable(minter).map(User::getAvatar).orElse(collection.getMinterAvatar()))
  69. .qty(qty)
  70. .price(collection.getPrice())
  71. .gasPrice(BigDecimal.valueOf(1))
  72. .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(BigDecimal.valueOf(1)))
  73. .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null))
  74. .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null))
  75. .address(Optional.ofNullable(userAddress).map(u ->
  76. u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress())
  77. .orElse(null))
  78. .status(OrderStatus.NOT_PAID)
  79. .build();
  80. return orderRepo.save(order);
  81. }
  82. public Object pay(Long id, PayMethod payMethod) throws AlipayApiException {
  83. Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
  84. if (order.getStatus() != OrderStatus.NOT_PAID) {
  85. throw new BusinessException("订单状态错误");
  86. }
  87. if (payMethod == PayMethod.ALIPAY) {
  88. JSONObject bizContent = new JSONObject();
  89. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  90. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  91. bizContent.put("out_trade_no", UUID.randomUUID().toString());
  92. bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString());
  93. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  94. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  95. // 测试环境设为1分
  96. bizContent.put("total_amount", "0.01");
  97. }
  98. bizContent.put("subject", order.getName());
  99. bizContent.put("product_code", "QUICK_WAP_PAY");
  100. JSONObject body = new JSONObject();
  101. body.put("action", "payOrder");
  102. body.put("userId", order.getUserId());
  103. body.put("orderId", order.getId());
  104. bizContent.put("body", body.toJSONString());
  105. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  106. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  107. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  108. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  109. String html = alipayClient.pageExecute(alipayRequest).getBody();
  110. return html;
  111. }
  112. return null;
  113. }
  114. }