GiftOrderService.java 14 KB

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