| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173 |
- 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.*;
- import com.izouma.nineth.dto.NFTAccount;
- 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 com.izouma.nineth.utils.SnowflakeIdWorker;
- import lombok.AllArgsConstructor;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.collections.MapUtils;
- import org.springframework.core.env.Environment;
- import org.springframework.data.domain.Page;
- import org.springframework.stereotype.Service;
- import org.springframework.ui.Model;
- import javax.transaction.Transactional;
- import java.math.BigDecimal;
- import java.time.LocalDateTime;
- import java.util.Arrays;
- import java.util.Map;
- import java.util.Optional;
- import java.util.UUID;
- @Service
- @AllArgsConstructor
- @Slf4j
- public class OrderService {
- private OrderRepo orderRepo;
- private CollectionRepo collectionRepo;
- private UserAddressRepo userAddressRepo;
- private UserRepo userRepo;
- private Environment env;
- private AlipayClient alipayClient;
- private AlipayProperties alipayProperties;
- private AssetService assetService;
- public Page<Order> 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("藏品不存在"));
- User minter = userRepo.findById(collection.getMinterId()).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);
- minter.setSales(minter.getSales() + 1);
- Order order = Order.builder()
- .userId(userId)
- .collectionId(collectionId)
- .name(collection.getName())
- .pic(collection.getPics())
- .minter(minter.getNickname())
- .minterAvatar(minter.getAvatar())
- .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 void payOrderAlipay(Long id, Model model) {
- try {
- Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
- if (order.getStatus() != OrderStatus.NOT_PAID) {
- throw new BusinessException("订单状态错误");
- }
- JSONObject bizContent = new JSONObject();
- bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
- bizContent.put("returnUrl", alipayProperties.getReturnUrl());
- bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
- 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 form = alipayClient.pageExecute(alipayRequest).getBody();
- model.addAttribute("form", form);
- } catch (BusinessException err) {
- model.addAttribute("errMsg", err.getError());
- } catch (Exception e) {
- model.addAttribute("errMsg", e.getMessage());
- }
- }
- public Object payOrderWeixin(Long id) {
- Order order = orderRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("订单不存在"));
- if (order.getStatus() != OrderStatus.NOT_PAID) {
- throw new BusinessException("订单状态错误");
- }
- return null;
- }
- public void notifyAlipay(Long orderId, Map<String, String> params) {
- Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
- if (order.getStatus() == OrderStatus.NOT_PAID) {
- Asset asset = null;
- try {
- asset = assetService.createAsset(order);
- order.setStatus(OrderStatus.PROCESSING);
- order.setPayTime(LocalDateTime.now());
- order.setTransactionId(MapUtils.getString(params, "trade_no"));
- order.setPayMethod(PayMethod.ALIPAY);
- orderRepo.save(order);
- if (asset != null) {
- order.setTxHash(asset.getTxHash());
- order.setGasUsed(asset.getGasUsed());
- order.setBlockNumber(asset.getBlockNumber());
- order.setStatus(OrderStatus.FINISH);
- orderRepo.save(order);
- }
- } catch (Exception e) {
- log.error("支付宝回调出错", e);
- }
- }
- }
- }
|