GiftOrderService.java 17 KB

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