package com.izouma.nineth.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.request.AlipayTradeWapPayRequest; import com.izouma.nineth.config.AlipayProperties; import com.izouma.nineth.domain.Collection; import com.izouma.nineth.domain.Order; import com.izouma.nineth.domain.User; import com.izouma.nineth.domain.UserAddress; import com.izouma.nineth.dto.PageQuery; import com.izouma.nineth.enums.OrderStatus; import com.izouma.nineth.enums.PayMethod; import com.izouma.nineth.exception.BusinessException; import com.izouma.nineth.repo.CollectionRepo; import com.izouma.nineth.repo.OrderRepo; import com.izouma.nineth.repo.UserAddressRepo; import com.izouma.nineth.repo.UserRepo; import com.izouma.nineth.utils.JpaUtils; import lombok.AllArgsConstructor; import org.springframework.core.env.Environment; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.math.BigDecimal; import java.util.Arrays; import java.util.Optional; import java.util.UUID; @Service @AllArgsConstructor public class OrderService { private OrderRepo orderRepo; private CollectionRepo collectionRepo; private UserAddressRepo userAddressRepo; private UserRepo userRepo; private Environment env; private AlipayClient alipayClient; private AlipayProperties alipayProperties; public Page all(PageQuery pageQuery) { return orderRepo.findAll(JpaUtils.toSpecification(pageQuery, Order.class), JpaUtils.toPageRequest(pageQuery)); } @Transactional public Order create(Long userId, Long collectionId, int qty, Long addressId) { if (qty <= 0) throw new BusinessException("数量必须大于0"); User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在")); Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品不存在")); if (!collection.isOnShelf()) { throw new BusinessException("藏品已下架"); } if (qty > collection.getStock()) { throw new BusinessException("库存不足"); } UserAddress userAddress = null; if (addressId != null) { userAddress = userAddressRepo.findById(addressId).orElseThrow(new BusinessException("地址信息不存在")); } collection.setStock(collection.getStock() - qty); collection.setSale(collection.getSale() + qty); collectionRepo.save(collection); User minter = userRepo.findById(collection.getMinterId()).orElse(null); Order order = Order.builder() .userId(userId) .collectionId(collectionId) .name(collection.getName()) .pic(collection.getPics()) .minter(Optional.ofNullable(minter).map(User::getNickname).orElse(collection.getMinter())) .minterAvatar(Optional.ofNullable(minter).map(User::getAvatar).orElse(collection.getMinterAvatar())) .qty(qty) .price(collection.getPrice()) .gasPrice(BigDecimal.valueOf(1)) .totalPrice(collection.getPrice().multiply(BigDecimal.valueOf(qty)).add(BigDecimal.valueOf(1))) .contactName(Optional.ofNullable(userAddress).map(UserAddress::getName).orElse(null)) .contactPhone(Optional.ofNullable(userAddress).map(UserAddress::getPhone).orElse(null)) .address(Optional.ofNullable(userAddress).map(u -> u.getProvinceId() + " " + u.getCityId() + " " + u.getDistrictId() + " " + u.getAddress()) .orElse(null)) .status(OrderStatus.NOT_PAID) .build(); return orderRepo.save(order); } public Object pay(Long id, PayMethod payMethod) throws AlipayApiException { Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在")); if (order.getStatus() != OrderStatus.NOT_PAID) { throw new BusinessException("订单状态错误"); } if (payMethod == PayMethod.ALIPAY) { JSONObject bizContent = new JSONObject(); bizContent.put("notifyUrl", alipayProperties.getNotifyUrl()); bizContent.put("returnUrl", alipayProperties.getReturnUrl()); bizContent.put("out_trade_no", UUID.randomUUID().toString()); bizContent.put("total_amount", order.getTotalPrice().stripTrailingZeros().toPlainString()); bizContent.put("disable_pay_channels", "pcredit,creditCard"); if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) { // 测试环境设为1分 bizContent.put("total_amount", "0.01"); } bizContent.put("subject", order.getName()); bizContent.put("product_code", "QUICK_WAP_PAY"); JSONObject body = new JSONObject(); body.put("action", "payOrder"); body.put("userId", order.getUserId()); body.put("orderId", order.getId()); bizContent.put("body", body.toJSONString()); AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest(); alipayRequest.setReturnUrl(alipayProperties.getReturnUrl()); alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl()); alipayRequest.setBizContent(JSON.toJSONString(bizContent)); String html = alipayClient.pageExecute(alipayRequest).getBody(); return html; } return null; } }