OrderController.java 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. package com.cyksj.web.controller.payment;
  2. import cn.hutool.core.codec.Base64;
  3. import cn.hutool.core.collection.CollUtil;
  4. import cn.hutool.core.collection.CollectionUtil;
  5. import cn.hutool.core.util.StrUtil;
  6. import cn.hutool.extra.qrcode.QrCodeUtil;
  7. import cn.hutool.extra.qrcode.QrConfig;
  8. import cn.hutool.extra.servlet.ServletUtil;
  9. import cn.hutool.json.JSONObject;
  10. import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
  11. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  12. import com.cyksj.common.constant.Constant;
  13. import com.cyksj.common.exception.BusinessRuntimeException;
  14. import com.cyksj.common.util.IoKit;
  15. import com.cyksj.common.util.Jsons;
  16. import com.cyksj.common.util.StringUtil;
  17. import com.cyksj.common.util.Xmls;
  18. import com.cyksj.config.zfb.BaseZfbConfig;
  19. import com.cyksj.config.zfb.ZfbProductCode;
  20. import com.cyksj.dto.Result;
  21. import com.cyksj.enums.GatewayApiCode;
  22. import com.cyksj.enums.GatewayResponse;
  23. import com.cyksj.mapper.*;
  24. import com.cyksj.mapper.channel.UserPayEquipmentAvailableBenefitsMapper;
  25. import com.cyksj.mapper.market.task.UserBindDetailMapper;
  26. import com.cyksj.model.dto.AliPayParams;
  27. import com.cyksj.model.dto.H5JsPayParams;
  28. import com.cyksj.model.entity.*;
  29. import com.cyksj.model.manage.views.*;
  30. import com.cyksj.model.request.AlipayOrderDonReq;
  31. import com.cyksj.model.request.OrderPayRequest;
  32. import com.cyksj.model.response.AliPayTradeStatus;
  33. import com.cyksj.model.views.GoodsDonSkuView;
  34. import com.cyksj.model.views.LumaUserView;
  35. import com.cyksj.model.views.MidjourneyUserView;
  36. import com.cyksj.model.views.OrderCommentView;
  37. import com.cyksj.service.luma.LumaService;
  38. import com.cyksj.service.midjourney.MidjourneyAccountService;
  39. import com.cyksj.service.order.OrderDonService;
  40. import com.cyksj.service.paypal.PayPalService;
  41. import com.cyksj.service.paypal.PaypalPayConfigService;
  42. import com.cyksj.service.paypal.PaypalV2Service;
  43. import com.cyksj.service.stripe.StripePayConfigService;
  44. import com.cyksj.service.stripe.StripeService;
  45. import com.cyksj.service.translations.BackInfoTranslationsFrontService;
  46. import com.cyksj.service.user.UserBindRelationService;
  47. import com.cyksj.web.util.StpUserUtil;
  48. import com.ejlchina.searcher.BeanSearcher;
  49. import com.ejlchina.searcher.SearchResult;
  50. import com.ejlchina.searcher.param.Operator;
  51. import com.ejlchina.searcher.util.MapBuilder;
  52. import com.ejlchina.searcher.util.MapUtils;
  53. import com.google.gson.JsonSyntaxException;
  54. import com.paypal.api.payments.Links;
  55. import com.paypal.api.payments.Payment;
  56. import com.stripe.exception.SignatureVerificationException;
  57. import com.stripe.model.*;
  58. import com.stripe.model.checkout.Session;
  59. import com.stripe.net.Webhook;
  60. import lombok.extern.slf4j.Slf4j;
  61. import org.apache.commons.lang3.StringUtils;
  62. import org.springframework.beans.BeanUtils;
  63. import org.springframework.beans.factory.annotation.Autowired;
  64. import org.springframework.validation.annotation.Validated;
  65. import org.springframework.web.bind.annotation.*;
  66. import javax.annotation.Resource;
  67. import javax.servlet.http.Cookie;
  68. import javax.servlet.http.HttpServletRequest;
  69. import javax.servlet.http.HttpServletResponse;
  70. import java.io.InputStream;
  71. import java.io.OutputStream;
  72. import java.math.BigDecimal;
  73. import java.math.RoundingMode;
  74. import java.nio.charset.StandardCharsets;
  75. import java.util.*;
  76. import java.util.stream.Collectors;
  77. /**
  78. * @author chan
  79. * @date 2021/10/11 下午3:50
  80. */
  81. @Slf4j
  82. @RequestMapping("/applets/order")
  83. @RestController
  84. public class OrderController {
  85. @Autowired
  86. private OrderDonService orderDonService;
  87. @Resource
  88. private BeanSearcher beanSearcher;
  89. @Resource
  90. private HttpServletRequest request;
  91. @Resource
  92. private HttpServletResponse response;
  93. @Autowired
  94. private UserBindDetailMapper userBindDetailMapper;
  95. @Autowired
  96. private UserMapper userMapper;
  97. @Autowired
  98. private UserPayEquipmentAvailableBenefitsMapper availableBenefitsMapper;
  99. @Autowired
  100. private OrderDonWaybillMapper waybillMapper;
  101. @Autowired
  102. private UserBindRelationService UserBindRelationService;
  103. @Autowired
  104. private PaypalPayConfigService paypalPayConfigService;
  105. @Autowired
  106. private PayPalService payPalService;
  107. @Autowired
  108. private PaypalV2Service paypalV2Service;
  109. @Autowired
  110. private StripePayConfigService stripePayConfigService;
  111. @Autowired
  112. private StripeService stripeService;
  113. @Autowired
  114. private MidjourneyAccountService midjourneyAccountService;
  115. @Autowired
  116. private GoodsDonSkuMapper skuMapper;
  117. @Autowired
  118. private OrderDonRenewRecordMapper orderDonRenewRecordMapper;
  119. @Autowired
  120. private LumaService lumaService;
  121. @Autowired
  122. private UserBindRelationService userBindRelationService;
  123. @Autowired
  124. private GroupsRelationMapper relationMapper;
  125. @Autowired
  126. private BackInfoTranslationsFrontService backInfoTranslationsFrontService;
  127. @Autowired
  128. private UpgradePackageMapper upgradePackageMapper;
  129. @Autowired
  130. private OrderDonMapper orderDonMapper;
  131. /**
  132. * 支付
  133. * @author chan
  134. * @date 2021-10-11 下午4:56
  135. */
  136. @PostMapping("/post/submit")
  137. public Result<OrderDon> submit(@Validated @RequestBody OrderPayRequest payRequest, HttpServletResponse response) throws Exception {
  138. final String methodName = "吊起微信支付";
  139. Long userId = StpUserUtil.getLoginIdAsLong();
  140. validateOrderPhone(payRequest, userId);
  141. payRequest.setIsNoLogin(false);
  142. payRequest.setUserId(userId);
  143. log.info("{}[start] params:{}", methodName, payRequest);
  144. String ip = ServletUtil.getClientIP(request);
  145. String address = StringUtil.getNewInternalAddressByIp(ip);
  146. //address.contains("柬埔寨") ||
  147. if (address != null && (address.contains("缅甸") || address.contains("柬埔寨"))) {
  148. throw BusinessRuntimeException.getInstance("用户异常");
  149. }
  150. payRequest.setIp(ip);
  151. //非推广 免登录
  152. if (payRequest.getPopularizeId() == null && payRequest.getIsNoLogin()) {
  153. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  154. }
  155. OrderDon orderDon = orderDonService.submit(payRequest);
  156. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  157. }
  158. /**
  159. * 套餐提交支付
  160. */
  161. @PostMapping("/post/upgrade/submit")
  162. public Result<UpgradeOrderDon> submitUpgrade(@Validated @RequestBody OrderPayRequest payRequest) throws Exception {
  163. final String methodName = "套餐吊起支付";
  164. //无需免登录
  165. Long userId = StpUserUtil.getLoginIdAsLong();
  166. validateOrderPhone(payRequest, userId);
  167. payRequest.setIsNoLogin(false);
  168. payRequest.setUserId(userId);
  169. log.info("{}[start] params:{}", methodName, payRequest);
  170. String ip = ServletUtil.getClientIP(request);
  171. payRequest.setIp(ip);
  172. UpgradeOrderDon orderDon = orderDonService.submitUpgrade(payRequest);
  173. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  174. }
  175. /**
  176. * 0元订单确认
  177. */
  178. @PostMapping("/post/order/status/{orderId}")
  179. @Deprecated
  180. public Result<String> zeroOrderConfirm(@PathVariable Long orderId) {
  181. authorizePayment(orderId, false);
  182. orderDonService.zeroOrderConfirm(orderId);
  183. return GatewayResponse.SUCCESS.newBuilder().toResult();
  184. }
  185. /**
  186. * 套餐0元订单确认
  187. */
  188. @PostMapping("/post/upgrade/order/status/{orderId}")
  189. @Deprecated
  190. public Result<String> zeroUpgradeOrderConfirm(@PathVariable Long orderId) {
  191. authorizePayment(orderId, true);
  192. orderDonService.zeroUpgradeOrderConfirm(orderId);
  193. return GatewayResponse.SUCCESS.newBuilder().toResult();
  194. }
  195. /**
  196. * 支付
  197. * @author chan
  198. * @date 2021-10-11 下午4:56
  199. */
  200. @org.springframework.beans.factory.annotation.Autowired
  201. private com.cyksj.redis.RedisService paymentGuardRedis;
  202. @org.springframework.beans.factory.annotation.Autowired
  203. private com.cyksj.mapper.UpgradeOrderDonMapper paymentUpgradeMapper;
  204. private void validateOrderPhone(OrderPayRequest req, Long userId) {
  205. if (StrUtil.isBlank(req.getPhone())) return;
  206. User user = userMapper.selectById(userId);
  207. if (user == null || !java.util.Objects.equals(user.getLoginPhone(), req.getPhone())) {
  208. throw BusinessRuntimeException.getInstance("下单手机号必须与当前登录账号一致");
  209. }
  210. }
  211. @FunctionalInterface
  212. private interface PaymentCall<T> { T run() throws Exception; }
  213. private <T> T invokePayment(Long orderId, PaymentCall<T> call) {
  214. try {
  215. return call.run();
  216. } catch (Exception error) {
  217. String reference = java.util.UUID.randomUUID().toString();
  218. // Do not echo provider payloads / merchant configuration to clients.
  219. log.error("Prepay failed orderId:{} reference:{} errorType:{}", orderId, reference,
  220. error.getClass().getName());
  221. throw BusinessRuntimeException.getInstance("支付发起失败,请稍后重试,错误编号:" + reference);
  222. }
  223. }
  224. private void authorizePayment(Long orderId, boolean upgrade) {
  225. long userId = StpUserUtil.getLoginIdAsLong();
  226. if (orderId == null || orderId <= 0) throw BusinessRuntimeException.getInstance("订单不存在或无权操作");
  227. boolean payable;
  228. if (upgrade) {
  229. UpgradeOrderDon order = paymentUpgradeMapper.selectById(orderId);
  230. if (order == null || !java.util.Objects.equals(order.getUserId(), userId))
  231. throw BusinessRuntimeException.getInstance("订单不存在或无权操作");
  232. payable = order.getStatus() == UpgradeOrderDon.Status.noPayment;
  233. } else {
  234. OrderDon order = orderDonMapper.selectById(orderId);
  235. if (order == null || !java.util.Objects.equals(order.getUserId(), userId))
  236. throw BusinessRuntimeException.getInstance("订单不存在或无权操作");
  237. payable = order.getStatus() == OrderDon.Status.noPayment;
  238. }
  239. if (!payable) throw BusinessRuntimeException.getInstance("订单已处理,请勿重复支付");
  240. if (!paymentGuardRedis.setNx("security:prepay:" + upgrade + ":" + orderId, "1", 5L))
  241. throw BusinessRuntimeException.getInstance("支付请求过于频繁,请稍后重试");
  242. }
  243. @PostMapping("/post/pay/{orderId}")
  244. public Result<H5JsPayParams> pay(@PathVariable Long orderId) throws Exception {
  245. authorizePayment(orderId, false);
  246. final String methodName = "吊起微信支付";
  247. log.info("{}[start] orderId:{}",methodName,orderId);
  248. H5JsPayParams payParams = invokePayment(orderId, () -> orderDonService.pay(orderId, "JSAPI"));
  249. return GatewayResponse.SUCCESS.newBuilder().toResult(payParams);
  250. }
  251. /**
  252. * 调用生成订单之后
  253. * 微信网页预下单获取交易链接生成二维码
  254. */
  255. @PostMapping("/get/wx/orderQrCode/{orderId}")
  256. public Result<String> createUnifiedOrderQr(@PathVariable Long orderId) throws Exception {
  257. authorizePayment(orderId, false);
  258. //预下单
  259. H5JsPayParams payParams = invokePayment(orderId, () -> orderDonService.wxPcWebPay(orderId, "NATIVE"));
  260. //获取二维码链接code_url
  261. String codeUrl = payParams.getCodeUrl();
  262. QrConfig qrConfig = new QrConfig(300, 300);
  263. return GatewayResponse.SUCCESS.newBuilder().toResult(QrCodeUtil.generateAsBase64(codeUrl, qrConfig, "png"));
  264. }
  265. /**
  266. * 微信支付回调
  267. * @author chan
  268. * @date 2021-10-11 下午5:42
  269. */
  270. @PostMapping("/prepay/notify")
  271. public void prepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  272. String xml = IoKit.toString(request.getInputStream());
  273. log.info("=== 微信支付成功的回调: \n {}", xml);
  274. // 解析xml
  275. Map<String, String> map = Xmls.toMap(xml);
  276. // 支付失败
  277. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  278. throw BusinessRuntimeException.getInstance("支付失败.");
  279. }
  280. orderDonService.prepayNotify(map);
  281. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  282. OutputStream out = null;
  283. try {
  284. out = response.getOutputStream();
  285. IoKit.write(toWeChatXmlResponse, out);
  286. } catch (Exception e) {
  287. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  288. } finally {
  289. IoKit.close(out);
  290. }
  291. }
  292. /**
  293. * pc端微信支付回调
  294. * @author chan
  295. * @date 2021-10-11 下午5:42
  296. */
  297. @PostMapping("/pc/prepay/notify")
  298. public void pcPrepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  299. String xml = IoKit.toString(request.getInputStream());
  300. log.info("=== 微信pc端分发支付成功的回调: \n {}", xml);
  301. // 解析xml
  302. Map<String, String> map = Xmls.toMap(xml);
  303. // 支付失败
  304. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  305. throw BusinessRuntimeException.getInstance("支付失败.");
  306. }
  307. orderDonService.prepayNotify(map);
  308. log.info("pc端微信支付回调修改订单状态成功");
  309. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  310. OutputStream out = null;
  311. try {
  312. out = response.getOutputStream();
  313. IoKit.write(toWeChatXmlResponse, out);
  314. } catch (Exception e) {
  315. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  316. } finally {
  317. IoKit.close(out);
  318. }
  319. }
  320. /**
  321. * 支付宝表单支付
  322. * 支付宝调起支付宝表单
  323. * 手机支付
  324. */
  325. @PostMapping("/post/pay/zfb")
  326. public Result<String> aliPay(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  327. authorizePayment(re.getOrderId(), false);
  328. AliPayParams aliPayParams = invokePayment(re.getOrderId(), () -> orderDonService.aliPay(re, ZfbProductCode.MOBILE_WEB.getProductCode(), null));
  329. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  330. //直接将完整的表单html输出到页面
  331. // response.getWriter().write(aliPayParams.getBody());
  332. // response.getWriter().flush();
  333. // response.getWriter().close();
  334. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  335. }
  336. /**
  337. * 套餐支付宝支付
  338. */
  339. @PostMapping("/post/pay/upgrade/zfb")
  340. public Result<String> aliPayUpgrade(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  341. authorizePayment(re.getOrderId(), true);
  342. AliPayParams aliPayParams = invokePayment(re.getOrderId(), () -> orderDonService.aliPayUpgrade(re, ZfbProductCode.MOBILE_WEB.getProductCode(),null));
  343. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  344. }
  345. /**
  346. * 支付宝web支付
  347. * pc网页内嵌二维码
  348. */
  349. @PostMapping("/get/zfb/orderQrCode")
  350. public Result<String> zfbWebQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  351. authorizePayment(re.getOrderId(), false);
  352. AliPayParams aliPayParams = invokePayment(re.getOrderId(), () -> orderDonService.aliPay(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_orderCode));
  353. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  354. //直接将完整的表单html输出到页面
  355. // response.getWriter().write(aliPayParams.getBody());
  356. // response.getWriter().flush();
  357. // response.getWriter().close();
  358. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  359. }
  360. /**
  361. * 支付宝web支付
  362. * pc网页内嵌二维码
  363. */
  364. @PostMapping("/get/zfb/upgrade/orderQrCode")
  365. public Result<String> zfbWebQrCodeUpgrade(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  366. authorizePayment(re.getOrderId(), true);
  367. AliPayParams aliPayParams = invokePayment(re.getOrderId(), () -> orderDonService.aliPayUpgrade(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_orderCode));
  368. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  369. //直接将完整的表单html输出到页面
  370. // response.getWriter().write(aliPayParams.getBody());
  371. // response.getWriter().flush();
  372. // response.getWriter().close();
  373. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  374. }
  375. /**
  376. * 支付宝web支付
  377. * pc网页跳转二维码
  378. */
  379. @PostMapping("/get/zfb/orderRedirect")
  380. public Result<String> zfbWebRedirectQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  381. authorizePayment(re.getOrderId(), false);
  382. AliPayParams aliPayParams = invokePayment(re.getOrderId(), () -> orderDonService.aliPay(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_redirect));
  383. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  384. }
  385. /**
  386. * 支付宝回调
  387. */
  388. @PostMapping("/prepay/zfb/notify")
  389. public String aliPayNotify(HttpServletRequest request) throws Exception {
  390. ////将异步通知中收到的所有参数都存放到map中
  391. Map<String, String> params = convertRequestParamsToMap(request);
  392. String tradeStatus = params.get("trade_status");
  393. String orderNo = params.get("out_trade_no");
  394. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  395. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  396. orderDonService.aliPayNotify(params);
  397. } else {
  398. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  399. return "fail";
  400. }
  401. return "success";
  402. }
  403. /**
  404. * 支付宝套餐包回调
  405. */
  406. @PostMapping("/prepay/zfb/upgrade/notify")
  407. public String aliPayUpgradeNotify(HttpServletRequest request) throws Exception {
  408. ////将异步通知中收到的所有参数都存放到map中
  409. Map<String, String> params = convertRequestParamsToMap(request);
  410. String tradeStatus = params.get("trade_status");
  411. String orderNo = params.get("out_trade_no");
  412. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  413. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  414. orderDonService.aliPayUpgradeNotify(params);
  415. } else {
  416. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  417. return "fail";
  418. }
  419. return "success";
  420. }
  421. /**
  422. * 支付宝转账
  423. */
  424. // @PostMapping("/zfb/transfer/accounts")
  425. // @NoSubmit
  426. // public Result<String> zfbTransferAccounts(@RequestBody @Validated TransferAccountsReq transferAccountsReq) throws Exception {
  427. // long userId = StpUserUtil.getLoginIdAsLong();
  428. // transferAccountsReq.setUserId(userId);
  429. // orderDonService.transferAccounts(transferAccountsReq);
  430. // return GatewayResponse.SUCCESS.newBuilder().toResult("转账成功");
  431. // }
  432. /**
  433. * 查询支付宝转账状态
  434. */
  435. @GetMapping("/zfb/transfer/status")
  436. public Result<String> getTransFerStatusByTid(String translationId) throws Exception {
  437. AlipayFundTransCommonQueryResponse response = orderDonService.getTransFerStatusByTid(translationId);
  438. if (response.isSuccess()) {
  439. if (!Constant.SUCCESS.equals(response.getStatus())) {
  440. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getFailReason());
  441. }
  442. return GatewayResponse.SUCCESS.newBuilder().toResult("该红包已转账成功");
  443. }
  444. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getSubMsg());
  445. }
  446. /**
  447. * 获取订单列表
  448. */
  449. @GetMapping("/get")
  450. public Result<SearchResult<OrderDonView>> list(String customId){
  451. long userId = StpUserUtil.getLoginIdAsLong();
  452. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  453. //Long yhsId = yhShopFrontService.getYhsIdByCustomId(customId);
  454. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  455. SearchResult<OrderDonView> search = beanSearcher.search(OrderDonView.class, builder
  456. //.field(OrderDonView::getYhsId, yhsId)
  457. .field(OrderDonView::getUserId, userIds).op(Operator.InList)
  458. .orderBy(OrderDonView::getId).desc()
  459. .build());
  460. String lang = request.getHeader("lang");
  461. search.getDataList().forEach(data->{
  462. Integer count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  463. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, data.getId())
  464. .eq(UserPayEquipmentAvailableBenefits::getDeleted, true));
  465. data.setIsHasBenefits(count > 0 ? true : false);
  466. if (data.getIsBenefits() != null && data.getIsBenefits()) {
  467. String benefitsList = data.getBenefitsList();
  468. if (StrUtil.isNotBlank(benefitsList)) {
  469. try {
  470. List<Long> skuIds = Jsons.parseList(benefitsList, GoodsDonSku.class).stream().map(GoodsDonSku::getId).collect(Collectors.toList());
  471. if (CollUtil.isNotEmpty(skuIds)) {
  472. data.setBenefitsViews(beanSearcher.searchAll(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuIds).op(Operator.InList).build()));
  473. }
  474. } catch (Exception e) {
  475. }
  476. }
  477. }
  478. if (data.getRelationId() == 0) {
  479. if (data.getGoodsDonType() == null || data.getGoodsDonType() != 5) {
  480. data.setWaybill(waybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, data.getId()).last("limit 1")));
  481. }
  482. }
  483. if (data.getOrderType() != null && data.getOrderType() == 2) {
  484. OrderDonRenewRecord orderDonRenewRecord = orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  485. .eq(OrderDonRenewRecord::getOrderId, data.getId())
  486. .last("limit 1"));
  487. data.setIsRenewPackage(orderDonRenewRecord != null ? true : false);
  488. }
  489. if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
  490. String languagePayTitle = backInfoTranslationsFrontService.getLanguagePayTitle(data.getGoodsId(), data.getSkuId(), lang);
  491. if (StrUtil.isNotBlank(languagePayTitle)) {
  492. data.setPayTitle(languagePayTitle);
  493. }
  494. String languageSpecVal = backInfoTranslationsFrontService.getLanguageSpecVal(data.getSkuId(), lang);
  495. if (StrUtil.isNotBlank(languageSpecVal)) {
  496. data.setSpecVal(languageSpecVal);
  497. }
  498. }
  499. });
  500. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  501. }
  502. /**
  503. * 获取订单详情
  504. */
  505. @GetMapping("/get/{orderId}")
  506. public Result<OrderDetailView> detail(@PathVariable Long orderId, Boolean isNoLogin) {
  507. Long userId = StpUserUtil.getLoginIdAsLong();
  508. OrderDetailView detail = orderDonService.getDetail(orderId, userId);
  509. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  510. }
  511. /**
  512. * 取消订单
  513. */
  514. @GetMapping("/get/close/{orderId}")
  515. public Result<String> closeOrder(@PathVariable Long orderId) {
  516. long userId = StpUserUtil.getLoginIdAsLong();
  517. orderDonService.closeOrder(orderId, userId);
  518. return GatewayResponse.SUCCESS.newBuilder().toResult();
  519. }
  520. @GetMapping("/get/order/status/{orderId}")
  521. public Result<OrderDonSearchView> getOrderStatusById(@PathVariable Long orderId) {
  522. long userId = StpUserUtil.getLoginIdAsLong();
  523. if (orderId < 1) {
  524. throw BusinessRuntimeException.getInstance("订单不存在");
  525. }
  526. OrderDonSearchView orderDonView = beanSearcher.searchFirst(OrderDonSearchView.class, MapUtils.builder()
  527. .put("orderId", String.format("where id = %s and user_id = %s", orderId, userId))
  528. .build());
  529. if (orderDonView == null) {
  530. throw BusinessRuntimeException.getInstance("订单不存在");
  531. }
  532. if (orderDonView.getOrderType() == 2 && orderDonView.getIsMirror()) {
  533. Optional.ofNullable(orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  534. .eq(OrderDonRenewRecord::getOrderId, orderId)
  535. .last("limit 1")))
  536. .ifPresent(renew -> {
  537. GoodsDonSku sku = skuMapper.selectById(renew.getOriSkuId());
  538. orderDonView.setOriSpecVal(sku.getSpecVal());
  539. });
  540. }
  541. String lang = request.getHeader("lang");
  542. if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
  543. String languagePayTitle = backInfoTranslationsFrontService.getLanguagePayTitle(orderDonView.getGoodsId(), orderDonView.getSkuId(), lang);
  544. if (StrUtil.isNotBlank(languagePayTitle)) {
  545. orderDonView.setPayTitle(languagePayTitle);
  546. }
  547. String languageSpecVal = backInfoTranslationsFrontService.getLanguageSpecVal(orderDonView.getSkuId(), lang);
  548. if (StrUtil.isNotBlank(languageSpecVal)) {
  549. orderDonView.setSpecVal(languageSpecVal);
  550. }
  551. String languagePayDesc = backInfoTranslationsFrontService.getLanguagePayDesc(orderDonView.getGoodsId(), lang);
  552. if (StrUtil.isNotBlank(languagePayDesc)) {
  553. orderDonView.setPayDesc(languagePayDesc);
  554. }
  555. }
  556. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  557. }
  558. /**
  559. * 查询套餐订单支付状态
  560. */
  561. @GetMapping("/get/upgrade/order/status/{orderId}")
  562. public Result<UpgradeOrderDonSearchView> getUpgradeOrderStatusById(@PathVariable Long orderId) {
  563. long userId = StpUserUtil.getLoginIdAsLong();
  564. if (orderId < 1) {
  565. throw BusinessRuntimeException.getInstance("订单不存在");
  566. }
  567. UpgradeOrderDonSearchView orderDonView = beanSearcher.searchFirst(UpgradeOrderDonSearchView.class, MapUtils.builder()
  568. .put("orderId", String.format("where id = %s and user_id = %s", orderId, userId))
  569. .build());
  570. if (orderDonView == null) {
  571. throw BusinessRuntimeException.getInstance("订单不存在");
  572. }
  573. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  574. }
  575. @PostMapping("/get/noLogin/order")
  576. public Result<List<OrderDonView>> getSearchResult(@RequestBody List<Long> orderIds) {
  577. List<OrderDonView> orderDonViews = beanSearcher.searchAll(OrderDonView.class, MapUtils.builder()
  578. .field(OrderDonView::getId, orderIds).op(Operator.InList)
  579. .orderBy(OrderDonView::getId).desc().build());
  580. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonViews);
  581. }
  582. /**
  583. * 平台评论列表
  584. */
  585. @GetMapping("/get/orderComment")
  586. public Result<SearchResult<OrderCommentView>> getOrderCommentView() {
  587. SearchResult<OrderCommentView> search = beanSearcher.search(OrderCommentView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  588. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  589. }
  590. /**
  591. * 电脑端手机号注册 购买车票是否绑定了微信用户
  592. */
  593. @GetMapping("/isBindWx")
  594. public Result<Boolean> isBindWx() {
  595. Long userId = StpUserUtil.getLoginIdAsLong();
  596. User user = userMapper.selectById(userId);
  597. if (user == null) {
  598. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  599. }
  600. if (StrUtil.isEmpty(user.getLoginPhone())) {
  601. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  602. }
  603. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  604. .eq(UserBindDetail::getPhone, user.getLoginPhone()));
  605. if (userBindDetail == null || userBindDetail.getUserId() == null) {
  606. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  607. }
  608. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  609. }
  610. /**
  611. * 是否绑定了邮箱或手机号
  612. */
  613. @GetMapping("/isBind")
  614. public Result<Boolean> isBindPhoneOrEmail(@RequestParam(defaultValue = "1") Boolean fip) {
  615. Long userId = StpUserUtil.getLoginIdAsLong();
  616. User user = userMapper.selectById(userId);
  617. if (user == null) {
  618. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  619. }
  620. //手机号注册 无需绑定
  621. if (StrUtil.isNotEmpty(user.getLoginPhone())) {
  622. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  623. }
  624. //是否绑定了手机号
  625. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  626. .eq(StrUtil.isNotEmpty(user.getUnionid()), UserBindDetail::getUserId, userId)
  627. .eq(StrUtil.isNotEmpty(user.getEmail()), UserBindDetail::getEmailUserId, userId).last("limit 1"));
  628. if (fip) {
  629. //台湾ip
  630. String address = StringUtil.getNewInternalAddressByIp(ServletUtil.getClientIP(request));
  631. if (address.contains("台湾") || !address.contains("中国")) {
  632. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  633. }
  634. }
  635. if (userBindDetail == null || StrUtil.isEmpty(userBindDetail.getPhone())) {
  636. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  637. }
  638. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  639. }
  640. /**
  641. * 获取支付宝回调参数
  642. */
  643. private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
  644. Map<String, String> retMap = new HashMap<>();
  645. Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
  646. for (Map.Entry<String, String[]> entry : entrySet) {
  647. String name = entry.getKey();
  648. String[] values = entry.getValue();
  649. int valLen = values.length;
  650. if (valLen == 1) {
  651. retMap.put(name, values[0]);
  652. } else if (valLen > 1) {
  653. StringBuilder sb = new StringBuilder();
  654. for (String val : values) {
  655. sb.append(",").append(val);
  656. }
  657. retMap.put(name, sb.substring(1));
  658. } else {
  659. retMap.put(name, "");
  660. }
  661. }
  662. return retMap;
  663. }
  664. /**
  665. * paypal支付
  666. */
  667. @PostMapping("/paypal/pay/{orderId}")
  668. public Result<String> paypalPay(@PathVariable Long orderId,String successUrl) throws Exception {
  669. authorizePayment(orderId, false);
  670. final String methodName = "paypal支付";
  671. log.info("{}[start] orderId:{}",methodName,orderId);
  672. Payment payment = invokePayment(orderId, () -> payPalService.createPayment(orderId, successUrl));
  673. String payUrl = "/";
  674. log.info("paypal links:{}",payment.getLinks());
  675. for(Links links : payment.getLinks()){
  676. if("approval_url".equals(links.getRel())){
  677. // 客户付款登陆地址
  678. String payPalUrl = links.getHref();
  679. log.info("PayPal调起支付成功[end]:{}", orderId);
  680. payUrl = payPalUrl;
  681. }
  682. }
  683. log.info("paypal支付成功[end]");
  684. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  685. }
  686. /**
  687. * stripe支付
  688. */
  689. @PostMapping("/stripe/pay/{orderId}")
  690. public Result<String> stripePay(@PathVariable Long orderId,String successUrl) throws Exception {
  691. final String methodName = "stripe支付";
  692. authorizePayment(orderId, false);
  693. log.info("{}[start] orderId:{}",methodName,orderId);
  694. String payUrl = invokePayment(orderId, () -> stripeService.checkOutStripe(orderId, successUrl));
  695. log.info("Stripe支付成功 result:{}[end]",payUrl);
  696. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  697. }
  698. /**
  699. * paypal支付回调
  700. */
  701. @RequestMapping(value = "/paypal/notify")
  702. public void successPay(@RequestParam(value = "paymentId") String paymentId, @RequestParam(value = "PayerID") String PayerID) throws Exception {
  703. PaypalPayConfig paypalPayConfig = paypalPayConfigService.getById(1);
  704. response.sendRedirect(payPalService.successPayment(paymentId,PayerID,paypalPayConfig));
  705. }
  706. /**
  707. * stripe支付回调
  708. */
  709. @PostMapping("/stripe/notify")
  710. @ResponseBody
  711. public String webhooks() throws Exception {
  712. InputStream inputStream = request.getInputStream();
  713. byte[] bytes = IoKit.toBytes(inputStream);
  714. String payload = new String(bytes, StandardCharsets.UTF_8);
  715. String sigHeader = request.getHeader("Stripe-Signature");
  716. StripePayConfig stripePayConfig = stripePayConfigService.getById(1);
  717. Event event = null;
  718. try {
  719. event = Webhook.constructEvent(
  720. payload, sigHeader, stripePayConfig.getWebhookSecret()
  721. );
  722. } catch (JsonSyntaxException | SignatureVerificationException e) {
  723. response.setStatus(400);
  724. return "";
  725. }
  726. // Deserialize the nested object inside the event
  727. EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer();
  728. StripeObject stripeObject = null;
  729. if (dataObjectDeserializer.getObject().isPresent()) {
  730. stripeObject = dataObjectDeserializer.getObject().orElse(null);
  731. } else {
  732. // Deserialization failed, probably due to an API version mismatch.
  733. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for
  734. // instructions on how to handle this case, or return an error here.
  735. }
  736. // Handle the event
  737. switch (event.getType()) {
  738. case "payment_intent.succeeded":
  739. PaymentIntent paymentIntent = (PaymentIntent) stripeObject;
  740. response.setStatus(200);
  741. break;
  742. case "charge.succeeded":
  743. //使用token支付成功回调
  744. Charge charge = (Charge) stripeObject;
  745. //TODO 此时根据charge ID 查询出关联的订单并处理支付成功业务代码
  746. response.setStatus(200);
  747. break;
  748. case "checkout.session.completed":
  749. //使用checkout支付成功回调
  750. Session session = (Session) stripeObject;
  751. String clientReferenceId = session.getClientReferenceId();
  752. if (clientReferenceId.contains("vip_")){
  753. stripeService.fulfillOrderVip(session);
  754. }else {
  755. stripeService.fulfillOrder(session);
  756. }
  757. response.setStatus(200);
  758. break;
  759. default:
  760. response.setStatus(400);
  761. return "";
  762. }
  763. response.setStatus(200);
  764. return "";
  765. }
  766. /**
  767. * 余额明细
  768. */
  769. @GetMapping("/get/balance/detail")
  770. public Result<SearchResult<UserBalanceSourceRecord>> getUserBalanceSourceRecord() {
  771. long userId = StpUserUtil.getLoginIdAsLong();
  772. SearchResult<UserBalanceSourceRecord> search = beanSearcher.search(UserBalanceSourceRecord.class, MapUtils.flatBuilder(request.getParameterMap())
  773. .field(UserBalanceSourceRecord::getUserId, userId)
  774. .field(UserBalanceSourceRecord::getDetail).op(Operator.NotNull)
  775. .orderBy(UserBalanceSourceRecord::getId).desc()
  776. .onlySelect(UserBalanceSourceRecord::getBalance, UserBalanceSourceRecord::getDetail, UserBalanceSourceRecord::getCreatedTime)
  777. .build());
  778. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  779. }
  780. /**
  781. * 获取套餐订单列表
  782. */
  783. @GetMapping("/upgrade/get")
  784. public Result<SearchResult<UpgradeOrderDonView>> listUpgradeOrder(){
  785. long userId = StpUserUtil.getLoginIdAsLong();
  786. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  787. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  788. SearchResult<UpgradeOrderDonView> search = beanSearcher.search(UpgradeOrderDonView.class, builder
  789. .field(UpgradeOrderDonView::getUserId, userIds).op(Operator.InList)
  790. .orderBy(UpgradeOrderDonView::getId).desc()
  791. .build());
  792. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  793. }
  794. /**
  795. * 获取套餐订单详情
  796. */
  797. @GetMapping("/get/upgrade/{orderId}")
  798. public Result<UpgradeOrderDetailView> upgradeOrderDetail(@PathVariable Long orderId) {
  799. Long userId = StpUserUtil.getUserIdAfterLogin();
  800. UpgradeOrderDetailView detail = orderDonService.getUpgradeOrderDetail(orderId, userId);
  801. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  802. }
  803. /**
  804. * 取消套餐订单
  805. */
  806. @GetMapping("/get/close/upgrade/{orderId}")
  807. public Result<String> closeUpgradeOrder(@PathVariable Long orderId) {
  808. long userId = StpUserUtil.getLoginIdAsLong();
  809. orderDonService.closeUpgradeOrder(orderId, userId);
  810. return GatewayResponse.SUCCESS.newBuilder().toResult();
  811. }
  812. /**
  813. * midjourney查询订单用户账号剩余次数
  814. */
  815. @GetMapping("/get/midjourney/user")
  816. public Result<MidjourneyUserView> getMidjourneyUser(Long relationId) {
  817. long userId = StpUserUtil.getLoginIdAsLong();
  818. // 归属校验:只允许查询当前登录用户(含绑定关系)名下的车票,避免通过 relationId 越权读取他人付费记录
  819. List<Long> userIds = userBindRelationService.getRelationUserIdList(userId, null);
  820. if (relationId == null || CollUtil.isEmpty(userIds)) {
  821. throw BusinessRuntimeException.getInstance("车票不存在");
  822. }
  823. GroupsRelation relation = relationMapper.selectById(relationId);
  824. if (relation == null || !userIds.contains(relation.getUserId())) {
  825. throw BusinessRuntimeException.getInstance("车票不存在");
  826. }
  827. // 只使用显式条件,不再透传 request 参数,防止参数注入(如 ?userId=xxx)绕过归属校验
  828. MidjourneyUserView search = beanSearcher.searchFirst(MidjourneyUserView.class, MapUtils.builder()
  829. .field(MidjourneyUserView::getRelationId, relationId)
  830. .field(MidjourneyUserView::getUserId, userIds).op(Operator.InList)
  831. .build());
  832. if (search == null) {
  833. MidjourneyUser midjourneyUser = midjourneyAccountService.getMidjourneyUserToken(userId, relationId);
  834. search = new MidjourneyUserView();
  835. BeanUtils.copyProperties(midjourneyUser, search);
  836. } else {
  837. List<UpgradePackage> upgradePackages = upgradePackageMapper.selectList(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + search.getSkuId() + "\"')").eq(UpgradePackage::getStatus, Boolean.TRUE).eq(UpgradePackage::getDeleted, Boolean.TRUE));
  838. if (CollectionUtil.isNotEmpty(upgradePackages)) {
  839. upgradePackages.stream().map(e -> e.getPrice().divide(BigDecimal.valueOf(e.getNum()), 2, RoundingMode.HALF_UP)).min(BigDecimal::compareTo).ifPresent(search::setMjPackagePrice);
  840. }
  841. }
  842. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  843. }
  844. /**
  845. * 续费升级提交支付
  846. */
  847. @PostMapping("/post/renew/upgrade/submit")
  848. public Result<OrderDon> submitRenewUpgrade(@Validated @RequestBody OrderPayRequest payRequest) throws Exception {
  849. final String methodName = "续费升级吊起支付";
  850. //无需免登录
  851. Long userId = StpUserUtil.getLoginIdAsLong();
  852. payRequest.setUserId(userId);
  853. log.info("{}[start] params:{}", methodName, payRequest);
  854. String ip = ServletUtil.getClientIP(request);
  855. payRequest.setIp(ip);
  856. OrderDon orderDon = orderDonService.submitRenewUpgrade(payRequest);
  857. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  858. }
  859. /**
  860. * cc抵扣升级 预支付
  861. */
  862. @PostMapping("/cc/deduct/submit")
  863. public Result<OrderDon> deductSubmitOrder(@RequestBody OrderPayRequest payRequest) {
  864. long userId = StpUserUtil.getLoginIdAsLong();
  865. payRequest.setUserId(userId);
  866. OrderDon orderDon = orderDonService.ccDeductSubmitOrder(payRequest);
  867. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  868. }
  869. /**
  870. * 获取续费套餐订单列表
  871. */
  872. @GetMapping("/renew/get")
  873. public Result<SearchResult<RenewUpgradeOrderDonView>> listRenewOrders(){
  874. long userId = StpUserUtil.getLoginIdAsLong();
  875. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  876. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  877. SearchResult<RenewUpgradeOrderDonView> search = beanSearcher.search(RenewUpgradeOrderDonView.class, builder
  878. .field(UpgradeOrderDonView::getUserId, userIds).op(Operator.InList)
  879. .orderBy(UpgradeOrderDonView::getId).desc()
  880. .build());
  881. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  882. }
  883. /**
  884. * luma查询订单用户账号剩余次数
  885. */
  886. @GetMapping("/get/luma/user")
  887. public Result<LumaUserView> getLumaUser(Long relationId) {
  888. long userId = StpUserUtil.getLoginIdAsLong();
  889. LumaUserView search = beanSearcher.searchFirst(LumaUserView.class, MapUtils.flatBuilder(request.getParameterMap())
  890. .field(LumaUserView::getUserId, userId).field(LumaUserView::getRelationId, relationId).build());
  891. if (search == null) {
  892. LumaUser lumaUser = lumaService.getLumaUser(userId, relationId);
  893. search = new LumaUserView();
  894. BeanUtils.copyProperties(lumaUser, search);
  895. }
  896. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  897. }
  898. /**
  899. * 用户续费订单列表
  900. */
  901. @GetMapping("/get/renew/order")
  902. public Result<List<OrderDonView>> getRenewOrder(Long relationId) {
  903. long userId = StpUserUtil.getLoginIdAsLong();
  904. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  905. if (relationId != null) {
  906. builder.field(OrderDonView::getRelationId, relationId);
  907. }
  908. GroupsRelation relation = relationMapper.selectById(relationId);
  909. if (relation == null) {
  910. return GatewayResponse.SUCCESS.newBuilder().toResult();
  911. }
  912. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  913. List<OrderDonView> list = beanSearcher.searchAll(OrderDonView.class, builder
  914. .field(OrderDonView::getUserId, userIds).op(Operator.InList)
  915. .field(OrderDonView::getOrderType, 2)
  916. .field(OrderDonView::getCreatedTime, relation.getStartTime()).op(Operator.GreaterThan)
  917. .orderBy(OrderDonView::getId).desc()
  918. .build());
  919. return GatewayResponse.SUCCESS.newBuilder().toResult(list);
  920. }
  921. /**
  922. * 用户权益预支付
  923. */
  924. @PostMapping("/user/benefits/submit")
  925. public Result<OrderDon> userBenefitsSubmit(@RequestBody OrderPayRequest orderPayRequest) throws Exception {
  926. long userId = StpUserUtil.getLoginIdAsLong();
  927. orderPayRequest.setUserId(userId);
  928. String ip = ServletUtil.getClientIP(request);
  929. orderPayRequest.setIp(ip);
  930. OrderDon orderDon = orderDonService.userBenefitsSubmit(orderPayRequest);
  931. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  932. }
  933. /**
  934. * 是否是实物可选多张车票权益记录
  935. */
  936. @GetMapping("/get/combo/optional/ticket/record/{orderId}")
  937. public Result<UserPayEquipmentAvailableBenefits> getComboOptionalTicketRecord(@PathVariable Long orderId) {
  938. long userId = StpUserUtil.getLoginIdAsLong();
  939. UserPayEquipmentAvailableBenefits userPayEquipmentAvailableBenefits = orderDonService.getComboOptionalTicketRecord(userId, orderId);
  940. return GatewayResponse.SUCCESS.newBuilder().toResult(userPayEquipmentAvailableBenefits);
  941. }
  942. /**
  943. * 是否购买过实物设备
  944. */
  945. @GetMapping("/has/paid/equipment")
  946. public Result<Boolean> hasPaidEquipment() {
  947. long userId = StpUserUtil.getLoginIdAsLong();
  948. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  949. //是否买过设备
  950. Integer selectCount = orderDonService.count(Wrappers.lambdaQuery(OrderDon.class)
  951. .eq(OrderDon::getGoodsId, 15)
  952. .in(OrderDon::getUserId, userIdList)
  953. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
  954. return GatewayResponse.SUCCESS.newBuilder().toResult(selectCount > 0);
  955. }
  956. /**
  957. * paypalV2支付
  958. */
  959. @PostMapping("/paypalV2/pay/{orderId}")
  960. public Result<String> paypalV2Pay(@PathVariable Long orderId,String successUrl) throws Exception {
  961. authorizePayment(orderId, false);
  962. final String methodName = "paypal支付";
  963. log.info("{}[start] orderId:{}",methodName,orderId);
  964. String payUrl = invokePayment(orderId, () -> paypalV2Service.createPayment(orderId, successUrl));
  965. log.info("paypal links:{}",payUrl);
  966. log.info("paypal支付成功[end]");
  967. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  968. }
  969. /**
  970. * paypal支付回调
  971. */
  972. @RequestMapping(value = "/paypalV2/notify")
  973. public void successV2Pay(@RequestParam(value = "token") String token, @RequestParam(value = "PayerID") String PayerID) throws Exception {
  974. PaypalPayConfig paypalPayConfig = paypalPayConfigService.getById(1);
  975. response.sendRedirect(paypalV2Service.successPayment(token,PayerID,paypalPayConfig));
  976. }
  977. /**
  978. * 领取GPT镜像天卡
  979. */
  980. @PostMapping("/receive/gptMirror/dayCard/{orderId}")
  981. public Result<String> receiveGptMirrorDayCard(@PathVariable Long orderId) throws Exception {
  982. orderDonService.receiveGptMirrorDayCard(orderId);
  983. return GatewayResponse.SUCCESS.newBuilder().toResult();
  984. }
  985. /**
  986. * 是否购买过AI订单
  987. */
  988. @GetMapping("/get/payAiOrders/condition")
  989. public Result<Boolean> getPayAiOrdersConditions() {
  990. long userId = StpUserUtil.getLoginIdAsLong();
  991. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  992. Integer selectCount = orderDonMapper.hasPaymentAiGoods(userIdList);
  993. return GatewayResponse.SUCCESS.newBuilder().toResult(selectCount > 0);
  994. }
  995. }