GiftOrderService.java 13 KB

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