GiftOrderService.java 12 KB

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