GiftOrderService.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alibaba.fastjson.serializer.SerializerFeature;
  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.huifu.adapay.core.exception.BaseAdaPayException;
  14. import com.huifu.adapay.model.AdapayCommon;
  15. import com.huifu.adapay.model.Payment;
  16. import com.izouma.nineth.config.AdapayProperties;
  17. import com.izouma.nineth.config.AlipayProperties;
  18. import com.izouma.nineth.config.GeneralProperties;
  19. import com.izouma.nineth.config.WxPayProperties;
  20. import com.izouma.nineth.domain.Asset;
  21. import com.izouma.nineth.domain.GiftOrder;
  22. import com.izouma.nineth.domain.User;
  23. import com.izouma.nineth.enums.AssetStatus;
  24. import com.izouma.nineth.enums.OrderStatus;
  25. import com.izouma.nineth.enums.PayMethod;
  26. import com.izouma.nineth.exception.BusinessException;
  27. import com.izouma.nineth.repo.AssetRepo;
  28. import com.izouma.nineth.repo.GiftOrderRepo;
  29. import com.izouma.nineth.repo.UserRepo;
  30. import com.izouma.nineth.utils.SnowflakeIdWorker;
  31. import lombok.AllArgsConstructor;
  32. import lombok.extern.slf4j.Slf4j;
  33. import org.apache.commons.codec.EncoderException;
  34. import org.apache.commons.codec.net.URLCodec;
  35. import org.apache.commons.collections.MapUtils;
  36. import org.apache.commons.lang3.StringUtils;
  37. import org.springframework.core.env.Environment;
  38. import org.springframework.scheduling.annotation.Scheduled;
  39. import org.springframework.stereotype.Service;
  40. import org.springframework.ui.Model;
  41. import javax.transaction.Transactional;
  42. import java.math.BigDecimal;
  43. import java.math.RoundingMode;
  44. import java.time.LocalDateTime;
  45. import java.time.format.DateTimeFormatter;
  46. import java.time.temporal.ChronoUnit;
  47. import java.util.Arrays;
  48. import java.util.HashMap;
  49. import java.util.List;
  50. import java.util.Map;
  51. @Service
  52. @AllArgsConstructor
  53. @Slf4j
  54. public class GiftOrderService {
  55. private AssetRepo assetRepo;
  56. private UserRepo userRepo;
  57. private SysConfigService sysConfigService;
  58. private GiftOrderRepo giftOrderRepo;
  59. private AlipayProperties alipayProperties;
  60. private AlipayClient alipayClient;
  61. private WxPayProperties wxPayProperties;
  62. private WxPayService wxPayService;
  63. private Environment env;
  64. private AssetService assetService;
  65. private AdapayProperties adapayProperties;
  66. private GeneralProperties generalProperties;
  67. @Transactional
  68. public GiftOrder gift(Long userId, Long assetId, Long toUserId) {
  69. Asset asset = assetRepo.findById(assetId).orElseThrow(new BusinessException("资产不存在"));
  70. if (!asset.getUserId().equals(userId)) {
  71. throw new BusinessException("无权限");
  72. }
  73. int holdDays = sysConfigService.getInt("hold_days");
  74. if (ChronoUnit.DAYS.between(asset.getCreatedAt(), LocalDateTime.now()) < holdDays) {
  75. throw new BusinessException("需持有满" + holdDays + "天才能转赠");
  76. }
  77. if (toUserId.equals(userId)) {
  78. throw new BusinessException("不能送给自己");
  79. }
  80. if (!(asset.getStatus() == AssetStatus.NORMAL)) {
  81. throw new BusinessException("当前状态不可转赠");
  82. }
  83. if (asset.isConsignment()) {
  84. throw new BusinessException("请先取消寄售");
  85. }
  86. if (asset.isPublicShow()) {
  87. assetService.cancelPublic(asset);
  88. }
  89. asset.setStatus(AssetStatus.GIFTING);
  90. assetRepo.save(asset);
  91. GiftOrder giftOrder = GiftOrder.builder()
  92. .userId(userId)
  93. .assetId(assetId)
  94. .toUserId(toUserId)
  95. .gasPrice(sysConfigService.getBigDecimal("gas_fee"))
  96. .status(OrderStatus.NOT_PAID)
  97. .build();
  98. return giftOrderRepo.save(giftOrder);
  99. }
  100. @Transactional
  101. public void giftNotify(Long orderId, PayMethod payMethod, String transactionId) {
  102. GiftOrder giftOrder = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  103. Asset asset = assetRepo.findById(giftOrder.getAssetId()).orElseThrow(new BusinessException("资产不存在"));
  104. User newOwner = userRepo.findById(giftOrder.getToUserId()).orElseThrow(new BusinessException("用户不存在"));
  105. giftOrder.setPayMethod(payMethod);
  106. giftOrder.setStatus(OrderStatus.FINISH);
  107. giftOrder.setTransactionId(transactionId);
  108. giftOrder.setPayTime(LocalDateTime.now());
  109. giftOrder.setPayMethod(PayMethod.ALIPAY);
  110. assetService.transfer(asset, asset.getPrice(), newOwner, "转赠", null);
  111. }
  112. public void payOrderAlipay(Long id, Model model) {
  113. try {
  114. GiftOrder order = giftOrderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  115. if (order.getStatus() != OrderStatus.NOT_PAID) {
  116. throw new BusinessException("订单状态错误");
  117. }
  118. JSONObject bizContent = new JSONObject();
  119. bizContent.put("notifyUrl", alipayProperties.getNotifyUrl());
  120. bizContent.put("returnUrl", alipayProperties.getReturnUrl());
  121. bizContent.put("out_trade_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  122. bizContent.put("total_amount", order.getGasPrice().stripTrailingZeros().toPlainString());
  123. bizContent.put("disable_pay_channels", "pcredit,creditCard");
  124. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  125. // 测试环境设为1分
  126. bizContent.put("total_amount", "0.01");
  127. }
  128. bizContent.put("subject", "转赠GAS费");
  129. bizContent.put("product_code", "QUICK_WAP_PAY");
  130. JSONObject body = new JSONObject();
  131. body.put("action", "payGiftOrder");
  132. body.put("userId", order.getUserId());
  133. body.put("orderId", order.getId());
  134. bizContent.put("body", body.toJSONString());
  135. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
  136. alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
  137. alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
  138. alipayRequest.setBizContent(JSON.toJSONString(bizContent));
  139. String form = alipayClient.pageExecute(alipayRequest).getBody();
  140. model.addAttribute("form", form);
  141. } catch (BusinessException err) {
  142. model.addAttribute("errMsg", err.getError());
  143. } catch (Exception e) {
  144. model.addAttribute("errMsg", e.getMessage());
  145. }
  146. }
  147. public Object payOrderWeixin(Long id, String tradeType, String openId) throws WxPayException, EncoderException {
  148. GiftOrder order = giftOrderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  149. if (order.getStatus() != OrderStatus.NOT_PAID) {
  150. throw new BusinessException("订单状态错误");
  151. }
  152. WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
  153. request.setBody("转赠GAS费");
  154. request.setOutTradeNo(String.valueOf(new SnowflakeIdWorker(1, 1).nextId()));
  155. request.setTotalFee(order.getGasPrice().multiply(BigDecimal.valueOf(100)).intValue());
  156. if (Arrays.stream(env.getActiveProfiles()).noneMatch(s -> s.equals("prod"))) {
  157. // 测试环境设为1分
  158. // request.setTotalFee(1);
  159. }
  160. request.setSpbillCreateIp("180.102.110.170");
  161. request.setNotifyUrl(wxPayProperties.getNotifyUrl());
  162. request.setTradeType(tradeType);
  163. request.setOpenid(openId);
  164. request.setSignType("MD5");
  165. JSONObject body = new JSONObject();
  166. body.put("action", "payGiftOrder");
  167. body.put("userId", order.getUserId());
  168. body.put("orderId", order.getId());
  169. request.setAttach(body.toJSONString());
  170. if (WxPayConstants.TradeType.MWEB.equals(tradeType)) {
  171. WxPayMwebOrderResult result = wxPayService.createOrder(request);
  172. return result.getMwebUrl() + "&redirect_url=" + new URLCodec().encode(wxPayProperties.getReturnUrl());
  173. } else if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
  174. return wxPayService.<WxPayMpOrderResult>createOrder(request);
  175. }
  176. throw new BusinessException("不支持此付款方式");
  177. }
  178. public Object payAdapay(Long id, String payChannel, String openId) throws BaseAdaPayException {
  179. List<String> aliChannels = Arrays.asList("alipay", "alipay_qr", "alipay_wap");
  180. List<String> wxChannels = Arrays.asList("wx_pub", "wx_lite");
  181. if (!aliChannels.contains(payChannel) && !wxChannels.contains(payChannel)) {
  182. throw new BusinessException("不支持此渠道");
  183. }
  184. GiftOrder order = giftOrderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
  185. User invitor = null;
  186. if (order.getStatus() != OrderStatus.NOT_PAID) {
  187. throw new BusinessException("订单状态错误");
  188. }
  189. Map<String, Object> paymentParams = new HashMap<>();
  190. paymentParams.put("order_no", String.valueOf(new SnowflakeIdWorker(0, 0).nextId()));
  191. paymentParams.put("pay_amt", order.getGasPrice().setScale(2, RoundingMode.HALF_UP).toPlainString());
  192. paymentParams.put("app_id", adapayProperties.getAppId());
  193. paymentParams.put("pay_channel", payChannel);
  194. paymentParams.put("goods_title", "转赠GAS费");
  195. paymentParams.put("goods_desc", "转赠GAS费");
  196. paymentParams.put("time_expire", DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
  197. .format(LocalDateTime.now().plusMinutes(5)));
  198. paymentParams.put("notify_url", adapayProperties.getNotifyUrl() + "/giftOrder/" + order.getId());
  199. Map<String, Object> expend = new HashMap<>();
  200. paymentParams.put("expend", expend);
  201. if ("wx_pub".equals(payChannel)) {
  202. if (StringUtils.isBlank(openId)) {
  203. throw new BusinessException("缺少openId");
  204. }
  205. expend.put("open_id", openId);
  206. expend.put("limit_pay", "1");
  207. }
  208. Map<String, Object> response;
  209. if ("wx_lite".equals(payChannel)) {
  210. paymentParams.put("adapay_func_code", "wxpay.createOrder");
  211. paymentParams.put("callback_url", generalProperties.getHost() + "/9th/orders");
  212. response = AdapayCommon.requestAdapayUits(paymentParams);
  213. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  214. } else {
  215. response = Payment.create(paymentParams);
  216. log.info("createOrderResponse {}", JSON.toJSONString(response, SerializerFeature.PrettyFormat));
  217. AdapayService.checkSuccess(response);
  218. }
  219. switch (payChannel) {
  220. case "alipay_wap":
  221. case "alipay":
  222. return MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info");
  223. case "alipay_qr":
  224. return MapUtils.getString(MapUtils.getMap(response, "expend"), "qrcode_url");
  225. case "wx_pub":
  226. JSONObject payParams = JSON.parseObject(MapUtils.getString(MapUtils.getMap(response, "expend"), "pay_info"));
  227. payParams.put("timestamp", payParams.get("timeStamp"));
  228. payParams.remove("timeStamp");
  229. return payParams;
  230. default:
  231. return MapUtils.getMap(response, "expend");
  232. }
  233. }
  234. @Scheduled(fixedRate = 60000)
  235. public void batchCancel() {
  236. if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
  237. return;
  238. }
  239. List<GiftOrder> orders = giftOrderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
  240. LocalDateTime.now().minusMinutes(5));
  241. orders.forEach(o -> {
  242. try {
  243. cancel(o);
  244. } catch (Exception ignored) {
  245. }
  246. });
  247. }
  248. public void cancel(GiftOrder order) {
  249. if (order.getStatus() != OrderStatus.NOT_PAID) {
  250. throw new BusinessException("已支付订单无法取消");
  251. }
  252. Asset asset = assetRepo.findById(order.getAssetId()).orElseThrow(new BusinessException("藏品不存在"));
  253. asset.setStatus(AssetStatus.NORMAL);
  254. assetRepo.save(asset);
  255. order.setStatus(OrderStatus.CANCELLED);
  256. order.setCancelTime(LocalDateTime.now());
  257. giftOrderRepo.save(order);
  258. }
  259. }