OrderPayService.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.alipay.api.AlipayApiException;
  4. import com.alipay.api.AlipayClient;
  5. import com.alipay.api.request.AlipayTradePrecreateRequest;
  6. import com.alipay.api.response.AlipayTradePrecreateResponse;
  7. import com.izouma.nineth.config.AlipayProperties;
  8. import com.izouma.nineth.config.Constants;
  9. import com.izouma.nineth.config.GeneralProperties;
  10. import com.izouma.nineth.domain.*;
  11. import com.izouma.nineth.dto.PayQuery;
  12. import com.izouma.nineth.dto.UserBankCard;
  13. import com.izouma.nineth.enums.*;
  14. import com.izouma.nineth.event.OrderNotifyEvent;
  15. import com.izouma.nineth.exception.BusinessException;
  16. import com.izouma.nineth.repo.*;
  17. import com.izouma.nineth.utils.SnowflakeIdWorker;
  18. import lombok.AllArgsConstructor;
  19. import lombok.extern.slf4j.Slf4j;
  20. import org.apache.commons.lang3.StringUtils;
  21. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  22. import org.springframework.cache.annotation.Cacheable;
  23. import org.springframework.security.crypto.password.PasswordEncoder;
  24. import org.springframework.stereotype.Service;
  25. import org.springframework.web.context.request.RequestContextHolder;
  26. import org.springframework.web.context.request.ServletRequestAttributes;
  27. import java.math.BigDecimal;
  28. import java.net.URLEncoder;
  29. import java.nio.charset.StandardCharsets;
  30. import java.time.LocalDateTime;
  31. import java.util.Map;
  32. import java.util.Objects;
  33. import java.util.Optional;
  34. import java.util.stream.Stream;
  35. @Service
  36. @Slf4j
  37. @AllArgsConstructor
  38. public class OrderPayService {
  39. private static String PAY_CHANNEL = Constants.PayChannel.SAND;
  40. private final OrderService orderService;
  41. private final OrderRepo orderRepo;
  42. private final MintOrderRepo mintOrderRepo;
  43. private final GiftOrderRepo giftOrderRepo;
  44. private final SandPayService sandPayService;
  45. private final HMPayService hmPayService;
  46. private final GeneralProperties generalProperties;
  47. private final UserBalanceService userBalanceService;
  48. private final RocketMQTemplate rocketMQTemplate;
  49. private final GiftOrderService giftOrderService;
  50. private final MintOrderService mintOrderService;
  51. private final UserRepo userRepo;
  52. private final SnowflakeIdWorker snowflakeIdWorker;
  53. private final RechargeOrderRepo rechargeOrderRepo;
  54. private final SysConfigService sysConfigService;
  55. private final PasswordEncoder passwordEncoder;
  56. private final PayEaseService payEaseService;
  57. private final UserBankCardRepo userBankCardRepo;
  58. private final AuctionOrderRepo auctionOrderRepo;
  59. private final AuctionOrderService auctionOrderService;
  60. private final IdentityAuthRepo identityAuthRepo;
  61. private final AlipayClient alipayClient;
  62. private final AlipayProperties alipayProperties;
  63. public static void setPayChannel(String payChannel) {
  64. log.info("set pay channel {}", payChannel);
  65. if (Constants.PayChannel.HM.equals(payChannel) || Constants.PayChannel.SAND.equals(payChannel)) {
  66. PAY_CHANNEL = payChannel;
  67. }
  68. }
  69. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  70. public String payOrder(Long orderId) {
  71. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  72. if (order.getStatus() != OrderStatus.NOT_PAID) {
  73. throw new BusinessException("订单状态错误");
  74. }
  75. switch (PAY_CHANNEL) {
  76. case Constants.PayChannel.SAND:
  77. return sandPayService.pay(orderId + "", order.getName(), order.getTotalPrice(),
  78. order.getCreatedAt().plusMinutes(3), "order");
  79. case Constants.PayChannel.HM:
  80. return hmPayService.requestAlipay(orderId + "", order.getTotalPrice(), order.getName(),
  81. HMPayService.getTimeout(order.getCreatedAt(), 180), Constants.OrderNotifyType.ORDER,
  82. generalProperties.resolveFrontUrl(order.getCompanyId(), "/orderDetail?id=" + orderId));
  83. }
  84. throw new BusinessException(Constants.PAY_ERR_MSG);
  85. }
  86. private String aliRequest(Long orderId, BigDecimal amount, String subject, String type) {
  87. AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
  88. request.setNotifyUrl(alipayProperties.getNotifyUrl());
  89. JSONObject bizContent = new JSONObject();
  90. bizContent.put("out_trade_no", orderId + "");
  91. bizContent.put("total_amount", amount);
  92. bizContent.put("subject", subject);
  93. JSONObject body = new JSONObject();
  94. body.put("type", type);
  95. body.put("orderId", orderId);
  96. bizContent.put("body", body.toString());
  97. request.setBizContent(bizContent.toString());
  98. AlipayTradePrecreateResponse response = null;
  99. try {
  100. response = alipayClient.execute(request);
  101. } catch (AlipayApiException e) {
  102. e.printStackTrace();
  103. throw new BusinessException(Constants.PAY_ERR_MSG, e.getErrMsg());
  104. }
  105. if (response.isSuccess()) {
  106. return response.getQrCode();
  107. } else {
  108. throw new BusinessException(response.getSubMsg());
  109. }
  110. }
  111. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  112. public String payOrderAli(Long orderId) {
  113. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  114. if (order.getStatus() != OrderStatus.NOT_PAID) {
  115. throw new BusinessException("订单状态错误");
  116. }
  117. String qrCode = aliRequest(orderId, order.getTotalPrice(), order.getName(), Constants.OrderNotifyType.ORDER);
  118. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("User-Agent");
  119. if (ua.toLowerCase().contains("micromessenger")) {
  120. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder.encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  121. + "&orderId=" + orderId + "&type=order&returnUrl="
  122. + URLEncoder.encode(generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"), StandardCharsets.UTF_8);
  123. } else {
  124. return Constants.ALIPAY_URL_SCHEME + qrCode;
  125. }
  126. }
  127. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  128. public String payOrderQuick(Long orderId) {
  129. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  130. if (order.getStatus() != OrderStatus.NOT_PAID) {
  131. throw new BusinessException("订单状态错误");
  132. }
  133. return sandPayService.payQuick(orderId + "", order.getName(), order.getTotalPrice(),
  134. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.ORDER,
  135. generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"));
  136. }
  137. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  138. public String payOrderQuickBind(Long orderId) {
  139. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  140. if (order.getStatus() != OrderStatus.NOT_PAID) {
  141. throw new BusinessException("订单状态错误");
  142. }
  143. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  144. .orElseThrow(new BusinessException("请先完成实名认证"));
  145. return sandPayService.payQuickBind(orderId + "", order.getName(), order.getTotalPrice(),
  146. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.ORDER,
  147. generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"),
  148. order.getUserId(), identityAuth.getRealName(), identityAuth.getIdNo());
  149. }
  150. public void payOrderBalance(Long orderId, Long userId, String tradeCode) {
  151. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  152. if (order.getStatus() != OrderStatus.NOT_PAID) {
  153. throw new BusinessException("订单状态错误");
  154. }
  155. checkTradeCode(userId, tradeCode, order.getUserId());
  156. BalanceRecord record = userBalanceService.balancePay(order.getUserId(), order.getTotalPrice(), orderId, order.getName());
  157. rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
  158. new OrderNotifyEvent(orderId, PayMethod.BALANCE, record.getId().toString(),
  159. System.currentTimeMillis()));
  160. }
  161. @Cacheable(value = "payOrder", key = "'order#'+#orderId")
  162. public Map<String, Object> payOrderAgreement(Long orderId, String bindCardId) {
  163. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  164. if (order.getStatus() != OrderStatus.NOT_PAID) {
  165. throw new BusinessException("订单状态错误");
  166. }
  167. if (StringUtils.isEmpty(bindCardId)) {
  168. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  169. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  170. }
  171. if (StringUtils.isEmpty(bindCardId)) {
  172. throw new BusinessException("请先绑定银行卡");
  173. }
  174. return payEaseService.pay(order.getName(), orderId.toString(), order.getTotalPrice(),
  175. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.ORDER);
  176. }
  177. public void confirmOrderAgreement(String requestId, String paymentOrderId, String code) {
  178. try {
  179. payEaseService.payConfirm(requestId, paymentOrderId, code);
  180. } catch (BusinessException e) {
  181. try {
  182. new Thread(() -> {
  183. orderService.cancel(Long.parseLong(requestId));
  184. }).start();
  185. } catch (Exception ee) {
  186. }
  187. throw e;
  188. }
  189. }
  190. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  191. public String payGiftOrder(Long orderId) {
  192. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  193. if (order.getStatus() != OrderStatus.NOT_PAID) {
  194. throw new BusinessException("订单状态错误");
  195. }
  196. switch (PAY_CHANNEL) {
  197. case Constants.PayChannel.SAND:
  198. return sandPayService.pay(orderId + "", "转赠" + order.getAssetId(), order.getGasPrice(),
  199. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.GIFT);
  200. case Constants.PayChannel.HM:
  201. return hmPayService.requestAlipay(orderId + "", order.getGasPrice(),
  202. "转赠" + order.getAssetId(),
  203. HMPayService.getTimeout(order.getCreatedAt(), 180),
  204. Constants.OrderNotifyType.GIFT, generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"));
  205. }
  206. throw new BusinessException(Constants.PAY_ERR_MSG);
  207. }
  208. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  209. public String payGiftAli(Long orderId) {
  210. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  211. if (order.getStatus() != OrderStatus.NOT_PAID) {
  212. throw new BusinessException("订单状态错误");
  213. }
  214. String qrCode = aliRequest(orderId, order.getGasPrice(), "转赠", Constants.OrderNotifyType.GIFT);
  215. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("User-Agent");
  216. if (ua.toLowerCase().contains("micromessenger")) {
  217. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder.encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  218. + "&orderId=" + orderId + "&type=gift&returnUrl="
  219. + URLEncoder.encode(generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"), StandardCharsets.UTF_8);
  220. } else {
  221. return Constants.ALIPAY_URL_SCHEME + qrCode;
  222. }
  223. }
  224. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  225. public String payGiftQuick(Long orderId) {
  226. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  227. if (order.getStatus() != OrderStatus.NOT_PAID) {
  228. throw new BusinessException("订单状态错误");
  229. }
  230. return sandPayService.payQuick(orderId + "", "转赠" + order.getAssetId(), order.getGasPrice(),
  231. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.GIFT,
  232. generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"));
  233. }
  234. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  235. public String payGiftQuickBind(Long orderId) {
  236. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  237. if (order.getStatus() != OrderStatus.NOT_PAID) {
  238. throw new BusinessException("订单状态错误");
  239. }
  240. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  241. .orElseThrow(new BusinessException("请先完成实名认证"));
  242. return sandPayService.payQuickBind(orderId + "", "转赠" + order.getAssetId(), order.getGasPrice(),
  243. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.GIFT,
  244. generalProperties.resolveFrontUrl(order.getCompanyId(), "/store"),
  245. order.getUserId(), identityAuth.getRealName(), identityAuth.getIdNo());
  246. }
  247. public void payGiftBalance(Long orderId, Long userId, String tradeCode) {
  248. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  249. if (order.getStatus() != OrderStatus.NOT_PAID) {
  250. throw new BusinessException("订单状态错误");
  251. }
  252. checkTradeCode(userId, tradeCode, order.getUserId());
  253. BalanceRecord record = userBalanceService.balancePay(order.getUserId(), order.getGasPrice(), orderId, "转赠");
  254. giftOrderService.giftNotify(orderId, PayMethod.BALANCE, record.getId().toString());
  255. }
  256. @Cacheable(value = "payOrder", key = "'gift#'+#orderId")
  257. public Map<String, Object> payGiftOrderAgreement(Long orderId, String bindCardId) {
  258. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  259. if (order.getStatus() != OrderStatus.NOT_PAID) {
  260. throw new BusinessException("订单状态错误");
  261. }
  262. if (StringUtils.isEmpty(bindCardId)) {
  263. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  264. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  265. }
  266. if (StringUtils.isEmpty(bindCardId)) {
  267. throw new BusinessException("请先绑定银行卡");
  268. }
  269. return payEaseService.pay("转赠" + order.getAssetId(), orderId.toString(), order.getGasPrice(),
  270. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.GIFT);
  271. }
  272. @Cacheable(value = "payOrder", key = "'mintOrder#'+#orderId")
  273. public String payMintOrder(Long orderId) {
  274. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  275. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  276. throw new BusinessException("订单状态错误");
  277. }
  278. switch (PAY_CHANNEL) {
  279. case Constants.PayChannel.SAND:
  280. return sandPayService.pay(orderId + "", "铸造活动:" + order.getMintActivityId(),
  281. order.getGasPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.MINT);
  282. case Constants.PayChannel.HM:
  283. return hmPayService.requestAlipay(orderId + "", order.getGasPrice(),
  284. "铸造活动:" + order.getMintActivityId(),
  285. HMPayService.getTimeout(order.getCreatedAt(), 180),
  286. Constants.OrderNotifyType.MINT, generalProperties.resolveFrontUrl(order.getCompanyId(), "/home"));
  287. }
  288. throw new BusinessException("绿洲宇宙冷却系统已启动,请稍后支付");
  289. }
  290. @Cacheable(value = "payOrder", key = "'mintOrder#'+#orderId")
  291. public String payMintAli(Long orderId) {
  292. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  293. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  294. throw new BusinessException("订单状态错误");
  295. }
  296. String qrCode = aliRequest(orderId, order.getGasPrice(), "铸造活动:" + order.getMintActivityId(), Constants.OrderNotifyType.MINT);
  297. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("User-Agent");
  298. if (ua.toLowerCase().contains("micromessenger")) {
  299. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder.encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  300. + "&orderId=" + orderId + "&type=mintOrder&returnUrl="
  301. + URLEncoder.encode(generalProperties.resolveFrontUrl(order.getCompanyId(), "/home"), StandardCharsets.UTF_8);
  302. } else {
  303. return Constants.ALIPAY_URL_SCHEME + qrCode;
  304. }
  305. }
  306. @Cacheable(value = "payOrder", key = "'mintOrder#'+#orderId")
  307. public String payMintQuick(Long orderId) {
  308. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  309. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  310. throw new BusinessException("订单状态错误");
  311. }
  312. return sandPayService.payQuick(orderId + "", "铸造活动:" + order.getMintActivityId(),
  313. order.getGasPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.MINT,
  314. generalProperties.resolveFrontUrl(order.getCompanyId(), "/home"));
  315. }
  316. @Cacheable(value = "payOrder", key = "'mintOrder#'+#orderId")
  317. public String payMintQuickBind(Long orderId) {
  318. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  319. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  320. throw new BusinessException("订单状态错误");
  321. }
  322. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  323. .orElseThrow(new BusinessException("请先完成实名认证"));
  324. return sandPayService.payQuickBind(orderId + "", "铸造活动:" + order.getMintActivityId(),
  325. order.getGasPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.MINT,
  326. generalProperties.resolveFrontUrl(order.getCompanyId(), "/home"),
  327. order.getUserId(), identityAuth.getRealName(), identityAuth.getIdNo());
  328. }
  329. public void payMintOrderBalance(Long orderId, Long userId, String tradeCode) {
  330. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  331. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  332. throw new BusinessException("订单状态错误");
  333. }
  334. checkTradeCode(userId, tradeCode, order.getUserId());
  335. BalanceRecord record = userBalanceService.balancePay(order.getUserId(), order.getGasPrice(), orderId, "铸造活动");
  336. mintOrderService.mintNotify(orderId, PayMethod.BALANCE, record.getId().toString());
  337. }
  338. private void checkTradeCode(Long userId, String tradeCode, Long orderUserId) {
  339. if (!Objects.equals(orderUserId, userId)) {
  340. throw new BusinessException("订单不属于该用户");
  341. }
  342. String encodedPwd = userRepo.findTradeCode(userId);
  343. if (StringUtils.isEmpty(encodedPwd)) {
  344. throw new BusinessException("请先设置交易密码");
  345. }
  346. if (!passwordEncoder.matches(tradeCode, encodedPwd)) {
  347. throw new BusinessException("交易码错误");
  348. }
  349. }
  350. @Cacheable(value = "payOrder", key = "'mint#'+#orderId")
  351. public Map<String, Object> payMintOrderAgreement(Long orderId, String bindCardId) {
  352. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  353. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  354. throw new BusinessException("订单状态错误");
  355. }
  356. if (StringUtils.isEmpty(bindCardId)) {
  357. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  358. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  359. }
  360. if (StringUtils.isEmpty(bindCardId)) {
  361. throw new BusinessException("请先绑定银行卡");
  362. }
  363. return payEaseService.pay("铸造活动:" + order.getMintActivityId(), orderId.toString(), order.getGasPrice(),
  364. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.MINT);
  365. }
  366. private Long getCompanyId() {
  367. Long companyId = 1L;
  368. try {
  369. String hCompanyId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("companyId");
  370. if (StringUtils.isNotBlank(hCompanyId)) {
  371. companyId = Long.parseLong(hCompanyId);
  372. }
  373. } catch (Exception ignored) {
  374. }
  375. return companyId;
  376. }
  377. public String recharge(Long userId, BigDecimal amount) {
  378. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  379. if (amount.compareTo(minAmount) < 0) {
  380. throw new BusinessException("充值金额不能小于" + minAmount);
  381. }
  382. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  383. throw new BusinessException("充值金额不能大于50000");
  384. }
  385. RechargeOrder order = RechargeOrder.builder()
  386. .id(snowflakeIdWorker.nextId())
  387. .userId(userId)
  388. .amount(amount)
  389. .status(OrderStatus.NOT_PAID)
  390. .build();
  391. rechargeOrderRepo.save(order);
  392. switch (PAY_CHANNEL) {
  393. case Constants.PayChannel.SAND:
  394. return sandPayService.pay(order.getId() + "", "余额充值", order.getAmount(),
  395. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.RECHARGE);
  396. case Constants.PayChannel.HM:
  397. return hmPayService.requestAlipay(order.getId() + "", order.getAmount(),
  398. "余额充值",
  399. HMPayService.getTimeout(order.getCreatedAt(), 180),
  400. Constants.OrderNotifyType.RECHARGE, generalProperties.resolveFrontUrl(getCompanyId(), "/home"));
  401. }
  402. throw new BusinessException("绿洲宇宙冷却系统已启动,请稍后支付");
  403. }
  404. public String payRechargeAli(Long userId, BigDecimal amount) {
  405. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  406. if (amount.compareTo(minAmount) < 0) {
  407. throw new BusinessException("充值金额不能小于" + minAmount);
  408. }
  409. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  410. throw new BusinessException("充值金额不能大于50000");
  411. }
  412. RechargeOrder order = RechargeOrder.builder()
  413. .id(snowflakeIdWorker.nextId())
  414. .userId(userId)
  415. .amount(amount)
  416. .status(OrderStatus.NOT_PAID)
  417. .build();
  418. rechargeOrderRepo.save(order);
  419. String qrCode = aliRequest(order.getId(), order.getAmount(), "余额充值", Constants.OrderNotifyType.RECHARGE);
  420. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("User-Agent");
  421. if (ua.toLowerCase().contains("micromessenger")) {
  422. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder.encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  423. + "&orderId=" + order.getId() + "&type=recharge&returnUrl="
  424. + URLEncoder.encode(generalProperties.resolveFrontUrl(getCompanyId(), "/home"), StandardCharsets.UTF_8);
  425. } else {
  426. return Constants.ALIPAY_URL_SCHEME + qrCode;
  427. }
  428. }
  429. public Map<String, Object> rechargeAgreement(Long userId, BigDecimal amount, String bindCardId) {
  430. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  431. if (amount.compareTo(minAmount) < 0) {
  432. throw new BusinessException("充值金额不能小于" + minAmount);
  433. }
  434. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  435. throw new BusinessException("充值金额不能大于50000");
  436. }
  437. RechargeOrder order = RechargeOrder.builder()
  438. .id(snowflakeIdWorker.nextId())
  439. .userId(userId)
  440. .amount(amount)
  441. .status(OrderStatus.NOT_PAID)
  442. .build();
  443. rechargeOrderRepo.save(order);
  444. if (StringUtils.isEmpty(bindCardId)) {
  445. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  446. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  447. }
  448. if (StringUtils.isEmpty(bindCardId)) {
  449. throw new BusinessException("请先绑定银行卡");
  450. }
  451. return payEaseService.pay("余额充值", order.getId().toString(), order.getAmount(),
  452. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.RECHARGE);
  453. }
  454. public String rechargeQuick(Long userId, BigDecimal amount, Long companyId) {
  455. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  456. if (amount.compareTo(minAmount) < 0) {
  457. throw new BusinessException("充值金额不能小于" + minAmount);
  458. }
  459. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  460. throw new BusinessException("充值金额不能大于50000");
  461. }
  462. RechargeOrder order = RechargeOrder.builder()
  463. .id(snowflakeIdWorker.nextId())
  464. .userId(userId)
  465. .amount(amount)
  466. .status(OrderStatus.NOT_PAID)
  467. .build();
  468. rechargeOrderRepo.save(order);
  469. return sandPayService.payQuick(order.getId() + "", "余额充值",
  470. order.getAmount(), LocalDateTime.now().plusMinutes(3), Constants.OrderNotifyType.RECHARGE,
  471. generalProperties.resolveFrontUrl(companyId, "/home"));
  472. }
  473. public String rechargeQuickBind(Long userId, BigDecimal amount, Long companyId) {
  474. BigDecimal minAmount = sysConfigService.getBigDecimal("min_recharge_amount");
  475. if (amount.compareTo(minAmount) < 0) {
  476. throw new BusinessException("充值金额不能小于" + minAmount);
  477. }
  478. if (amount.compareTo(new BigDecimal("50000")) > 0) {
  479. throw new BusinessException("充值金额不能大于50000");
  480. }
  481. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
  482. .orElseThrow(new BusinessException("请先完成实名认证"));
  483. RechargeOrder order = RechargeOrder.builder()
  484. .id(snowflakeIdWorker.nextId())
  485. .userId(userId)
  486. .amount(amount)
  487. .status(OrderStatus.NOT_PAID)
  488. .build();
  489. rechargeOrderRepo.save(order);
  490. return sandPayService.payQuickBind(order.getId() + "", "余额充值",
  491. order.getAmount(), LocalDateTime.now().plusMinutes(3), Constants.OrderNotifyType.RECHARGE,
  492. generalProperties.resolveFrontUrl(companyId, "/home"),
  493. userId, identityAuth.getRealName(), identityAuth.getIdNo());
  494. }
  495. public JSONObject refund(String orderId, String transactionId, BigDecimal amount, String channel) {
  496. switch (channel) {
  497. case Constants.PayChannel.SAND: {
  498. JSONObject res = sandPayService.refund(orderId, amount);
  499. if (!"000000".equals(res.getJSONObject("head").getString("respCode"))) {
  500. String msg = res.getJSONObject("head").getString("respMsg");
  501. throw new BusinessException("退款失败:" + msg);
  502. }
  503. return res;
  504. }
  505. case Constants.PayChannel.HM: {
  506. JSONObject res = hmPayService.refund(orderId, amount);
  507. if (!"REFUND_SUCCESS".equals(res.getString("sub_code"))) {
  508. String msg = res.getString("msg");
  509. throw new BusinessException("退款失败:" + msg);
  510. }
  511. return res;
  512. }
  513. case Constants.PayChannel.PE: {
  514. JSONObject res = payEaseService.refund(orderId, transactionId, amount);
  515. String status = res.getString("status");
  516. if (!"SUCCESS".equals(status)) {
  517. String error = res.getString("error");
  518. String cause = res.getString("cause");
  519. throw new BusinessException("退款失败:" + error + ";" + cause);
  520. }
  521. return res;
  522. }
  523. }
  524. throw new BusinessException("退款失败");
  525. }
  526. public PayQuery query(String orderId) {
  527. return query(orderId, null);
  528. }
  529. public PayQuery query(String orderId, String channel) {
  530. if (StringUtils.isNotEmpty(channel)) {
  531. switch (channel) {
  532. case Constants.PayChannel.SAND:
  533. return sandPayService.payQuery(orderId);
  534. case Constants.PayChannel.HM:
  535. return hmPayService.payQuery(orderId);
  536. case Constants.PayChannel.PE:
  537. return payEaseService.payQuery(orderId);
  538. }
  539. }
  540. PayQuery query = sandPayService.payQuery(orderId);
  541. if (query == null || !query.isExist()) {
  542. query = hmPayService.payQuery(orderId);
  543. }
  544. if (query == null || !query.isExist()) {
  545. query = payEaseService.payQuery(orderId);
  546. }
  547. return Optional.ofNullable(query).orElse(PayQuery.builder().exist(false).build());
  548. }
  549. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  550. public String payAuctionOrder(Long orderId) {
  551. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  552. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  553. throw new BusinessException("订单状态错误");
  554. }
  555. switch (PAY_CHANNEL) {
  556. case Constants.PayChannel.SAND:
  557. return sandPayService.pay(orderId + "", "拍卖:" + order.getName(), order.getTotalPrice(),
  558. order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.AUCTION);
  559. case Constants.PayChannel.HM:
  560. return hmPayService.requestAlipay(orderId + "", order.getTotalPrice(),
  561. "拍卖:" + order.getName(), HMPayService.getTimeout(order.getCreatedAt(), 180),
  562. Constants.OrderNotifyType.AUCTION, generalProperties.resolveFrontUrl(getCompanyId(), "/home"));
  563. }
  564. throw new BusinessException("绿洲宇宙冷却系统已启动,请稍后支付");
  565. }
  566. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  567. public String payAuctionAli(Long orderId) {
  568. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  569. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  570. throw new BusinessException("订单状态错误");
  571. }
  572. String qrCode = aliRequest(orderId, order.getTotalPrice(), "拍卖:" + order.getName(), Constants.OrderNotifyType.AUCTION);
  573. String ua = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("User-Agent");
  574. if (ua.toLowerCase().contains("micromessenger")) {
  575. return "/static/wx_alipay_bridge.html?payUrl=" + URLEncoder.encode(Constants.ALIPAY_URL_SCHEME + qrCode, StandardCharsets.UTF_8)
  576. + "&orderId=" + orderId + "&type=auctionOrder&returnUrl="
  577. + URLEncoder.encode(generalProperties.resolveFrontUrl(getCompanyId(), "/home"), StandardCharsets.UTF_8);
  578. } else {
  579. return Constants.ALIPAY_URL_SCHEME + qrCode;
  580. }
  581. }
  582. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  583. public String payAuctionQuick(Long orderId) {
  584. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  585. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  586. throw new BusinessException("订单状态错误");
  587. }
  588. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  589. .orElseThrow(new BusinessException("请先完成实名认证"));
  590. return sandPayService.payQuick(orderId + "", "拍卖:" + order.getName(),
  591. order.getTotalPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.AUCTION,
  592. generalProperties.resolveFrontUrl(getCompanyId(), "/home"));
  593. }
  594. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  595. public String payAuctionQuickBind(Long orderId) {
  596. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  597. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  598. throw new BusinessException("订单状态错误");
  599. }
  600. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(order.getUserId(), AuthStatus.SUCCESS)
  601. .orElseThrow(new BusinessException("请先完成实名认证"));
  602. return sandPayService.payQuickBind(orderId + "", "拍卖:" + order.getName(),
  603. order.getTotalPrice(), order.getCreatedAt().plusMinutes(3), Constants.OrderNotifyType.AUCTION,
  604. generalProperties.resolveFrontUrl(getCompanyId(), "/home"),
  605. order.getUserId(), identityAuth.getRealName(), identityAuth.getIdNo());
  606. }
  607. public void payAuctionOrderBalance(Long orderId, Long userId, String tradeCode) {
  608. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  609. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  610. throw new BusinessException("订单状态错误");
  611. }
  612. checkTradeCode(userId, tradeCode, order.getUserId());
  613. BalanceRecord record = userBalanceService.balancePay(order.getUserId(), order.getTotalPrice(), orderId, "拍卖");
  614. auctionOrderService.notify(orderId, PayMethod.BALANCE, record.getId().toString());
  615. }
  616. @Cacheable(value = "payOrder", key = "'auctionOrder#'+#orderId")
  617. public Map<String, Object> payAuctionOrderAgreement(Long orderId, String bindCardId) {
  618. AuctionOrder order = auctionOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  619. if (order.getStatus() != AuctionOrderStatus.NOT_PAID) {
  620. throw new BusinessException("订单状态错误");
  621. }
  622. if (StringUtils.isEmpty(bindCardId)) {
  623. bindCardId = userBankCardRepo.findByUserId(order.getUserId())
  624. .stream().map(UserBankCard::getBindCardId).findFirst().orElse(null);
  625. }
  626. if (StringUtils.isEmpty(bindCardId)) {
  627. throw new BusinessException("请先绑定银行卡");
  628. }
  629. return payEaseService.pay("拍卖:" + order.getAuctionId(), orderId.toString(), order.getTotalPrice(),
  630. order.getUserId().toString(), bindCardId, Constants.OrderNotifyType.AUCTION);
  631. }
  632. }