GiftOrderService.java 13 KB

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