OrderController.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. package com.cyksj.web.controller.payment;
  2. import cn.hutool.core.codec.Base64;
  3. import cn.hutool.core.util.StrUtil;
  4. import cn.hutool.extra.qrcode.QrCodeUtil;
  5. import cn.hutool.extra.qrcode.QrConfig;
  6. import cn.hutool.extra.servlet.ServletUtil;
  7. import cn.hutool.json.JSONObject;
  8. import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
  9. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  10. import com.cyksj.common.constant.Constant;
  11. import com.cyksj.common.exception.BusinessRuntimeException;
  12. import com.cyksj.common.util.IoKit;
  13. import com.cyksj.common.util.Jsons;
  14. import com.cyksj.common.util.StringUtil;
  15. import com.cyksj.common.util.Xmls;
  16. import com.cyksj.config.zfb.BaseZfbConfig;
  17. import com.cyksj.config.zfb.ZfbProductCode;
  18. import com.cyksj.dto.Result;
  19. import com.cyksj.enums.GatewayApiCode;
  20. import com.cyksj.enums.GatewayResponse;
  21. import com.cyksj.mapper.GoodsDonSkuMapper;
  22. import com.cyksj.mapper.OrderDonRenewRecordMapper;
  23. import com.cyksj.mapper.OrderDonWaybillMapper;
  24. import com.cyksj.mapper.UserMapper;
  25. import com.cyksj.mapper.channel.UserPayEquipmentAvailableBenefitsMapper;
  26. import com.cyksj.mapper.market.task.UserBindDetailMapper;
  27. import com.cyksj.model.dto.AliPayParams;
  28. import com.cyksj.model.dto.H5JsPayParams;
  29. import com.cyksj.model.entity.*;
  30. import com.cyksj.model.manage.views.*;
  31. import com.cyksj.model.request.AlipayOrderDonReq;
  32. import com.cyksj.model.request.OrderPayRequest;
  33. import com.cyksj.model.response.AliPayTradeStatus;
  34. import com.cyksj.model.views.GoodsDonSkuView;
  35. import com.cyksj.model.views.LumaUserView;
  36. import com.cyksj.model.views.MidjourneyUserView;
  37. import com.cyksj.model.views.OrderCommentView;
  38. import com.cyksj.service.luma.LumaService;
  39. import com.cyksj.service.midjourney.MidjourneyAccountService;
  40. import com.cyksj.service.order.OrderDonService;
  41. import com.cyksj.service.paypal.PayPalService;
  42. import com.cyksj.service.paypal.PaypalPayConfigService;
  43. import com.cyksj.service.stripe.StripePayConfigService;
  44. import com.cyksj.service.stripe.StripeService;
  45. import com.cyksj.service.user.UserBindRelationService;
  46. import com.cyksj.web.util.StpUserUtil;
  47. import com.ejlchina.searcher.BeanSearcher;
  48. import com.ejlchina.searcher.SearchResult;
  49. import com.ejlchina.searcher.param.Operator;
  50. import com.ejlchina.searcher.util.MapBuilder;
  51. import com.ejlchina.searcher.util.MapUtils;
  52. import com.google.gson.JsonSyntaxException;
  53. import com.paypal.api.payments.Links;
  54. import com.paypal.api.payments.Payment;
  55. import com.stripe.exception.SignatureVerificationException;
  56. import com.stripe.model.*;
  57. import com.stripe.model.checkout.Session;
  58. import com.stripe.net.Webhook;
  59. import lombok.extern.slf4j.Slf4j;
  60. import org.apache.commons.lang3.StringUtils;
  61. import org.springframework.beans.BeanUtils;
  62. import org.springframework.beans.factory.annotation.Autowired;
  63. import org.springframework.validation.annotation.Validated;
  64. import org.springframework.web.bind.annotation.*;
  65. import javax.annotation.Resource;
  66. import javax.servlet.http.Cookie;
  67. import javax.servlet.http.HttpServletRequest;
  68. import javax.servlet.http.HttpServletResponse;
  69. import java.io.InputStream;
  70. import java.io.OutputStream;
  71. import java.nio.charset.StandardCharsets;
  72. import java.util.*;
  73. import java.util.stream.Collectors;
  74. /**
  75. * @author chan
  76. * @date 2021/10/11 下午3:50
  77. */
  78. @Slf4j
  79. @RequestMapping("/applets/order")
  80. @RestController
  81. public class OrderController {
  82. @Autowired
  83. private OrderDonService orderDonService;
  84. @Resource
  85. private BeanSearcher beanSearcher;
  86. @Resource
  87. private HttpServletRequest request;
  88. @Resource
  89. private HttpServletResponse response;
  90. @Autowired
  91. private UserBindDetailMapper userBindDetailMapper;
  92. @Autowired
  93. private UserMapper userMapper;
  94. @Autowired
  95. private UserPayEquipmentAvailableBenefitsMapper availableBenefitsMapper;
  96. @Autowired
  97. private OrderDonWaybillMapper waybillMapper;
  98. @Autowired
  99. private UserBindRelationService UserBindRelationService;
  100. @Autowired
  101. private PaypalPayConfigService paypalPayConfigService;
  102. @Autowired
  103. private PayPalService payPalService;
  104. @Autowired
  105. private StripePayConfigService stripePayConfigService;
  106. @Autowired
  107. private StripeService stripeService;
  108. @Autowired
  109. private MidjourneyAccountService midjourneyAccountService;
  110. @Autowired
  111. private GoodsDonSkuMapper skuMapper;
  112. @Autowired
  113. private OrderDonRenewRecordMapper orderDonRenewRecordMapper;
  114. @Autowired
  115. private LumaService lumaService;
  116. /**
  117. * 支付
  118. * @author chan
  119. * @date 2021-10-11 下午4:56
  120. */
  121. @PostMapping("/post/submit")
  122. public Result<OrderDon> submit(@Validated @RequestBody OrderPayRequest payRequest, HttpServletResponse response) throws Exception {
  123. final String methodName = "吊起微信支付";
  124. Long userId = StpUserUtil.getUserIdAfterLogin();
  125. payRequest.setUserId(userId);
  126. log.info("{}[start] params:{}", methodName, payRequest);
  127. String ip = ServletUtil.getClientIP(request);
  128. String address = StringUtil.getNewInternalAddressByIp(ip);
  129. //address.contains("柬埔寨") ||
  130. if (address != null && address.contains("缅甸")) {
  131. throw BusinessRuntimeException.getInstance("用户系统异常");
  132. }
  133. payRequest.setIp(ip);
  134. OrderDon orderDon = orderDonService.submit(payRequest);
  135. //无登录订单 预留手机号免登录
  136. if (userId == null && payRequest.getPopularizeId() != null && StrUtil.isNotBlank(payRequest.getPhone())) {
  137. User user = userMapper.selectById(orderDon.getUserId());
  138. //写回登陆信息
  139. StpUserUtil.login(user.getId());
  140. response.addHeader("satoken-user", StpUserUtil.getTokenValue());
  141. Cookie cookie = new Cookie("satoken-user", StpUserUtil.getTokenValue());
  142. cookie.setMaxAge(31536000);
  143. cookie.setPath("/");
  144. response.addCookie(cookie);
  145. JSONObject jsonObject = new JSONObject();
  146. jsonObject.putOpt("showId", user.getShowId());
  147. jsonObject.putOpt("nickName", user.getNickname());
  148. Cookie userInfo = new Cookie("info", Base64.encode(jsonObject.toString()));
  149. cookie.setMaxAge(31536000);
  150. cookie.setPath("/");
  151. response.addCookie(userInfo);
  152. }
  153. if (orderDon.getGoodsId() != null && orderDon.getGoodsId() == 26l) {
  154. GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
  155. orderDon.setIsMirror(sku.getIsMirror());
  156. }
  157. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  158. }
  159. /**
  160. * 套餐提交支付
  161. */
  162. @PostMapping("/post/upgrade/submit")
  163. public Result<UpgradeOrderDon> submitUpgrade(@Validated @RequestBody OrderPayRequest payRequest) throws Exception {
  164. final String methodName = "套餐吊起支付";
  165. //无需免登录
  166. Long userId = StpUserUtil.getLoginIdAsLong();
  167. payRequest.setUserId(userId);
  168. log.info("{}[start] params:{}", methodName, payRequest);
  169. String ip = ServletUtil.getClientIP(request);
  170. payRequest.setIp(ip);
  171. UpgradeOrderDon orderDon = orderDonService.submitUpgrade(payRequest);
  172. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  173. }
  174. /**
  175. * 0元订单确认
  176. */
  177. @PostMapping("/post/order/status/{orderId}")
  178. public Result<String> zeroOrderConfirm(@PathVariable Long orderId) {
  179. orderDonService.zeroOrderConfirm(orderId);
  180. return GatewayResponse.SUCCESS.newBuilder().toResult();
  181. }
  182. /**
  183. * 套餐0元订单确认
  184. */
  185. @PostMapping("/post/upgrade/order/status/{orderId}")
  186. public Result<String> zeroUpgradeOrderConfirm(@PathVariable Long orderId) {
  187. orderDonService.zeroUpgradeOrderConfirm(orderId);
  188. return GatewayResponse.SUCCESS.newBuilder().toResult();
  189. }
  190. /**
  191. * 支付
  192. * @author chan
  193. * @date 2021-10-11 下午4:56
  194. */
  195. @PostMapping("/post/pay/{orderId}")
  196. public Result<H5JsPayParams> pay(@PathVariable Long orderId) throws Exception {
  197. final String methodName = "吊起微信支付";
  198. log.info("{}[start] orderId:{}",methodName,orderId);
  199. H5JsPayParams payParams = orderDonService.pay(orderId, "JSAPI");
  200. return GatewayResponse.SUCCESS.newBuilder().toResult(payParams);
  201. }
  202. /**
  203. * 调用生成订单之后
  204. * 微信网页预下单获取交易链接生成二维码
  205. */
  206. @PostMapping("/get/wx/orderQrCode/{orderId}")
  207. public Result<String> createUnifiedOrderQr(@PathVariable Long orderId) throws Exception {
  208. //预下单
  209. H5JsPayParams payParams = orderDonService.wxPcWebPay(orderId, "NATIVE");
  210. //获取二维码链接code_url
  211. String codeUrl = payParams.getCodeUrl();
  212. QrConfig qrConfig = new QrConfig(300, 300);
  213. return GatewayResponse.SUCCESS.newBuilder().toResult(QrCodeUtil.generateAsBase64(codeUrl, qrConfig, "png"));
  214. }
  215. /**
  216. * 微信支付回调
  217. * @author chan
  218. * @date 2021-10-11 下午5:42
  219. */
  220. @PostMapping("/prepay/notify")
  221. public void prepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  222. String xml = IoKit.toString(request.getInputStream());
  223. log.info("=== 微信支付成功的回调: \n {}", xml);
  224. // 解析xml
  225. Map<String, String> map = Xmls.toMap(xml);
  226. // 支付失败
  227. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  228. throw BusinessRuntimeException.getInstance("支付失败.");
  229. }
  230. orderDonService.prepayNotify(map);
  231. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  232. OutputStream out = null;
  233. try {
  234. out = response.getOutputStream();
  235. IoKit.write(toWeChatXmlResponse, out);
  236. } catch (Exception e) {
  237. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  238. } finally {
  239. IoKit.close(out);
  240. }
  241. }
  242. /**
  243. * pc端微信支付回调
  244. * @author chan
  245. * @date 2021-10-11 下午5:42
  246. */
  247. @PostMapping("/pc/prepay/notify")
  248. public void pcPrepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  249. String xml = IoKit.toString(request.getInputStream());
  250. log.info("=== 微信pc端分发支付成功的回调: \n {}", xml);
  251. // 解析xml
  252. Map<String, String> map = Xmls.toMap(xml);
  253. // 支付失败
  254. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  255. throw BusinessRuntimeException.getInstance("支付失败.");
  256. }
  257. orderDonService.prepayNotify(map);
  258. log.info("pc端微信支付回调修改订单状态成功");
  259. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  260. OutputStream out = null;
  261. try {
  262. out = response.getOutputStream();
  263. IoKit.write(toWeChatXmlResponse, out);
  264. } catch (Exception e) {
  265. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  266. } finally {
  267. IoKit.close(out);
  268. }
  269. }
  270. /**
  271. * 支付宝表单支付
  272. * 支付宝调起支付宝表单
  273. * 手机支付
  274. */
  275. @PostMapping("/post/pay/zfb")
  276. public Result<String> aliPay(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  277. AliPayParams aliPayParams = orderDonService.aliPay(re, ZfbProductCode.MOBILE_WEB.getProductCode(), null);
  278. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  279. //直接将完整的表单html输出到页面
  280. // response.getWriter().write(aliPayParams.getBody());
  281. // response.getWriter().flush();
  282. // response.getWriter().close();
  283. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  284. }
  285. /**
  286. * 套餐支付宝支付
  287. */
  288. @PostMapping("/post/pay/upgrade/zfb")
  289. public Result<String> aliPayUpgrade(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  290. AliPayParams aliPayParams = orderDonService.aliPayUpgrade(re, ZfbProductCode.MOBILE_WEB.getProductCode(),null);
  291. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  292. }
  293. /**
  294. * 支付宝web支付
  295. * pc网页内嵌二维码
  296. */
  297. @PostMapping("/get/zfb/orderQrCode")
  298. public Result<String> zfbWebQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  299. AliPayParams aliPayParams = orderDonService.aliPay(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_orderCode);
  300. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  301. //直接将完整的表单html输出到页面
  302. // response.getWriter().write(aliPayParams.getBody());
  303. // response.getWriter().flush();
  304. // response.getWriter().close();
  305. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  306. }
  307. /**
  308. * 支付宝web支付
  309. * pc网页内嵌二维码
  310. */
  311. @PostMapping("/get/zfb/upgrade/orderQrCode")
  312. public Result<String> zfbWebQrCodeUpgrade(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  313. AliPayParams aliPayParams = orderDonService.aliPayUpgrade(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_orderCode);
  314. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  315. //直接将完整的表单html输出到页面
  316. // response.getWriter().write(aliPayParams.getBody());
  317. // response.getWriter().flush();
  318. // response.getWriter().close();
  319. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  320. }
  321. /**
  322. * 支付宝web支付
  323. * pc网页跳转二维码
  324. */
  325. @PostMapping("/get/zfb/orderRedirect")
  326. public Result<String> zfbWebRedirectQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  327. AliPayParams aliPayParams = orderDonService.aliPay(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_redirect);
  328. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  329. }
  330. /**
  331. * 支付宝回调
  332. */
  333. @PostMapping("/prepay/zfb/notify")
  334. public String aliPayNotify(HttpServletRequest request) throws Exception {
  335. ////将异步通知中收到的所有参数都存放到map中
  336. Map<String, String> params = convertRequestParamsToMap(request);
  337. String tradeStatus = params.get("trade_status");
  338. String orderNo = params.get("out_trade_no");
  339. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  340. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  341. orderDonService.aliPayNotify(params);
  342. } else {
  343. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  344. return "fail";
  345. }
  346. return "success";
  347. }
  348. /**
  349. * 支付宝套餐包回调
  350. */
  351. @PostMapping("/prepay/zfb/upgrade/notify")
  352. public String aliPayUpgradeNotify(HttpServletRequest request) throws Exception {
  353. ////将异步通知中收到的所有参数都存放到map中
  354. Map<String, String> params = convertRequestParamsToMap(request);
  355. String tradeStatus = params.get("trade_status");
  356. String orderNo = params.get("out_trade_no");
  357. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  358. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  359. orderDonService.aliPayUpgradeNotify(params);
  360. } else {
  361. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  362. return "fail";
  363. }
  364. return "success";
  365. }
  366. /**
  367. * 支付宝转账
  368. */
  369. // @PostMapping("/zfb/transfer/accounts")
  370. // @NoSubmit
  371. // public Result<String> zfbTransferAccounts(@RequestBody @Validated TransferAccountsReq transferAccountsReq) throws Exception {
  372. // long userId = StpUserUtil.getLoginIdAsLong();
  373. // transferAccountsReq.setUserId(userId);
  374. // orderDonService.transferAccounts(transferAccountsReq);
  375. // return GatewayResponse.SUCCESS.newBuilder().toResult("转账成功");
  376. // }
  377. /**
  378. * 查询支付宝转账状态
  379. */
  380. @GetMapping("/zfb/transfer/status")
  381. public Result<String> getTransFerStatusByTid(String translationId) throws Exception {
  382. AlipayFundTransCommonQueryResponse response = orderDonService.getTransFerStatusByTid(translationId);
  383. if (response.isSuccess()) {
  384. if (!Constant.SUCCESS.equals(response.getStatus())) {
  385. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getFailReason());
  386. }
  387. return GatewayResponse.SUCCESS.newBuilder().toResult("该红包已转账成功");
  388. }
  389. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getSubMsg());
  390. }
  391. /**
  392. * 获取订单列表
  393. */
  394. @GetMapping("/get")
  395. public Result<SearchResult<OrderDonView>> list(String customId){
  396. long userId = StpUserUtil.getLoginIdAsLong();
  397. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  398. //Long yhsId = yhShopFrontService.getYhsIdByCustomId(customId);
  399. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  400. SearchResult<OrderDonView> search = beanSearcher.search(OrderDonView.class, builder
  401. //.field(OrderDonView::getYhsId, yhsId)
  402. .field(OrderDonView::getUserId, userIds).op(Operator.InList)
  403. .orderBy(OrderDonView::getId).desc()
  404. .build());
  405. search.getDataList().forEach(data->{
  406. Integer count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  407. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, data.getId())
  408. .eq(UserPayEquipmentAvailableBenefits::getDeleted, true));
  409. data.setIsHasBenefits(count > 0 ? true : false);
  410. if (data.getIsBenefits() != null && data.getIsBenefits()) {
  411. String benefitsList = data.getBenefitsList();
  412. if (StrUtil.isNotBlank(benefitsList)) {
  413. try {
  414. List<Long> skuIds = Jsons.parseList(benefitsList, GoodsDonSku.class).stream().map(GoodsDonSku::getId).collect(Collectors.toList());
  415. data.setBenefitsViews(beanSearcher.searchAll(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuIds).op(Operator.InList).build()));
  416. } catch (Exception e) {
  417. }
  418. }
  419. }
  420. if (data.getRelationId() == 0) {
  421. data.setWaybill(waybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, data.getId()).last("limit 1")));
  422. }
  423. if (data.getOrderType() == 2) {
  424. OrderDonRenewRecord orderDonRenewRecord = orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  425. .eq(OrderDonRenewRecord::getOrderId, data.getId())
  426. .last("limit 1"));
  427. data.setIsRenewPackage(orderDonRenewRecord != null ? true : false);
  428. }
  429. });
  430. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  431. }
  432. /**
  433. * 获取订单详情
  434. */
  435. @GetMapping("/get/{orderId}")
  436. public Result<OrderDetailView> detail(@PathVariable Long orderId, Boolean isNoLogin) {
  437. Long userId = StpUserUtil.getUserIdAfterLogin();
  438. OrderDetailView detail = orderDonService.getDetail(orderId, userId);
  439. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  440. }
  441. /**
  442. * 取消订单
  443. */
  444. @GetMapping("/get/close/{orderId}")
  445. public Result<String> closeOrder(@PathVariable Long orderId) {
  446. long userId = StpUserUtil.getLoginIdAsLong();
  447. orderDonService.closeOrder(orderId, userId);
  448. return GatewayResponse.SUCCESS.newBuilder().toResult();
  449. }
  450. @GetMapping("/get/order/status/{orderId}")
  451. public Result<OrderDonSearchView> getOrderStatusById(@PathVariable Long orderId) {
  452. if (orderId < 1) {
  453. throw BusinessRuntimeException.getInstance("订单不存在");
  454. }
  455. OrderDonSearchView orderDonView = beanSearcher.searchFirst(OrderDonSearchView.class, MapUtils.builder()
  456. .put("orderId", String.format("where id = %s", orderId))
  457. .build());
  458. if (orderDonView == null) {
  459. throw BusinessRuntimeException.getInstance("订单不存在");
  460. }
  461. if (orderDonView.getIsMirror() && orderDonView.getOrderType() == 2) {
  462. Optional.ofNullable(orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  463. .eq(OrderDonRenewRecord::getOrderId, orderId)
  464. .last("limit 1")))
  465. .ifPresent(renew -> {
  466. GoodsDonSku sku = skuMapper.selectById(renew.getOriSkuId());
  467. orderDonView.setOriSpecVal(sku.getSpecVal());
  468. });
  469. }
  470. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  471. }
  472. /**
  473. * 查询套餐订单支付状态
  474. */
  475. @GetMapping("/get/upgrade/order/status/{orderId}")
  476. public Result<UpgradeOrderDonSearchView> getUpgradeOrderStatusById(@PathVariable Long orderId) {
  477. if (orderId < 1) {
  478. throw BusinessRuntimeException.getInstance("订单不存在");
  479. }
  480. UpgradeOrderDonSearchView orderDonView = beanSearcher.searchFirst(UpgradeOrderDonSearchView.class, MapUtils.builder()
  481. .put("orderId", String.format("where id = %s", orderId))
  482. .build());
  483. if (orderDonView == null) {
  484. throw BusinessRuntimeException.getInstance("订单不存在");
  485. }
  486. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  487. }
  488. @PostMapping("/get/noLogin/order")
  489. public Result<List<OrderDonView>> getSearchResult(@RequestBody List<Long> orderIds) {
  490. List<OrderDonView> orderDonViews = beanSearcher.searchAll(OrderDonView.class, MapUtils.builder()
  491. .field(OrderDonView::getId, orderIds).op(Operator.InList)
  492. .orderBy(OrderDonView::getId).desc().build());
  493. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonViews);
  494. }
  495. /**
  496. * 平台评论列表
  497. */
  498. @GetMapping("/get/orderComment")
  499. public Result<SearchResult<OrderCommentView>> getOrderCommentView() {
  500. SearchResult<OrderCommentView> search = beanSearcher.search(OrderCommentView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  501. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  502. }
  503. /**
  504. * 电脑端手机号注册 购买车票是否绑定了微信用户
  505. */
  506. @GetMapping("/isBindWx")
  507. public Result<Boolean> isBindWx() {
  508. Long userId = StpUserUtil.getLoginIdAsLong();
  509. User user = userMapper.selectById(userId);
  510. if (user == null) {
  511. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  512. }
  513. if (StrUtil.isEmpty(user.getLoginPhone())) {
  514. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  515. }
  516. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  517. .eq(UserBindDetail::getPhone, user.getLoginPhone()));
  518. if (userBindDetail == null || userBindDetail.getUserId() == null) {
  519. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  520. }
  521. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  522. }
  523. /**
  524. * 是否绑定了邮箱或手机号
  525. */
  526. @GetMapping("/isBind")
  527. public Result<Boolean> isBindPhoneOrEmail(@RequestParam(defaultValue = "1") Boolean fip) {
  528. Long userId = StpUserUtil.getLoginIdAsLong();
  529. User user = userMapper.selectById(userId);
  530. if (user == null) {
  531. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  532. }
  533. //手机号注册 无需绑定
  534. if (StrUtil.isNotEmpty(user.getLoginPhone())) {
  535. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  536. }
  537. //是否绑定了手机号
  538. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  539. .eq(StrUtil.isNotEmpty(user.getOpenId()), UserBindDetail::getUserId, userId)
  540. .eq(StrUtil.isNotEmpty(user.getEmail()), UserBindDetail::getEmailUserId, userId).last("limit 1"));
  541. if (fip) {
  542. //台湾ip
  543. String address = StringUtil.getNewInternalAddressByIp(ServletUtil.getClientIP(request));
  544. if (address.contains("台湾") || !address.contains("中国")) {
  545. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  546. }
  547. }
  548. if (userBindDetail == null || StrUtil.isEmpty(userBindDetail.getPhone())) {
  549. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  550. }
  551. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  552. }
  553. /**
  554. * 获取支付宝回调参数
  555. */
  556. private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
  557. Map<String, String> retMap = new HashMap<>();
  558. Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
  559. for (Map.Entry<String, String[]> entry : entrySet) {
  560. String name = entry.getKey();
  561. String[] values = entry.getValue();
  562. int valLen = values.length;
  563. if (valLen == 1) {
  564. retMap.put(name, values[0]);
  565. } else if (valLen > 1) {
  566. StringBuilder sb = new StringBuilder();
  567. for (String val : values) {
  568. sb.append(",").append(val);
  569. }
  570. retMap.put(name, sb.substring(1));
  571. } else {
  572. retMap.put(name, "");
  573. }
  574. }
  575. return retMap;
  576. }
  577. /**
  578. * paypal支付
  579. */
  580. @PostMapping("/paypal/pay/{orderId}")
  581. public Result<String> paypalPay(@PathVariable Long orderId,String successUrl) throws Exception {
  582. final String methodName = "paypal支付";
  583. log.info("{}[start] orderId:{}",methodName,orderId);
  584. Payment payment = payPalService.createPayment(orderId,successUrl);
  585. String payUrl = "/";
  586. log.info("paypal links:{}",payment.getLinks());
  587. for(Links links : payment.getLinks()){
  588. if("approval_url".equals(links.getRel())){
  589. // 客户付款登陆地址
  590. String payPalUrl = links.getHref();
  591. log.info("PayPal调起支付成功[end]:{}", orderId);
  592. payUrl = payPalUrl;
  593. }
  594. }
  595. log.info("paypal支付成功[end]");
  596. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  597. }
  598. /**
  599. * stripe支付
  600. */
  601. @PostMapping("/stripe/pay/{orderId}")
  602. public Result<String> stripePay(@PathVariable Long orderId,String successUrl) throws Exception {
  603. final String methodName = "stripe支付";
  604. log.info("{}[start] orderId:{}",methodName,orderId);
  605. String payUrl = stripeService.checkOutStripe(orderId,successUrl);
  606. log.info("Stripe支付成功 result:{}[end]",payUrl);
  607. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  608. }
  609. /**
  610. * paypal支付回调
  611. */
  612. @RequestMapping(value = "/paypal/notify")
  613. public void successPay(@RequestParam(value = "paymentId") String paymentId, @RequestParam(value = "PayerID") String PayerID) throws Exception {
  614. PaypalPayConfig paypalPayConfig = paypalPayConfigService.getById(1);
  615. response.sendRedirect(payPalService.successPayment(paymentId,PayerID,paypalPayConfig));
  616. }
  617. /**
  618. * stripe支付回调
  619. */
  620. @PostMapping("/stripe/notify")
  621. @ResponseBody
  622. public String webhooks() throws Exception {
  623. InputStream inputStream = request.getInputStream();
  624. byte[] bytes = IoKit.toBytes(inputStream);
  625. String payload = new String(bytes, StandardCharsets.UTF_8);
  626. String sigHeader = request.getHeader("Stripe-Signature");
  627. StripePayConfig stripePayConfig = stripePayConfigService.getById(1);
  628. Event event = null;
  629. try {
  630. event = Webhook.constructEvent(
  631. payload, sigHeader, stripePayConfig.getWebhookSecret()
  632. );
  633. } catch (JsonSyntaxException | SignatureVerificationException e) {
  634. response.setStatus(400);
  635. return "";
  636. }
  637. // Deserialize the nested object inside the event
  638. EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer();
  639. StripeObject stripeObject = null;
  640. if (dataObjectDeserializer.getObject().isPresent()) {
  641. stripeObject = dataObjectDeserializer.getObject().orElse(null);
  642. } else {
  643. // Deserialization failed, probably due to an API version mismatch.
  644. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for
  645. // instructions on how to handle this case, or return an error here.
  646. }
  647. // Handle the event
  648. switch (event.getType()) {
  649. case "payment_intent.succeeded":
  650. PaymentIntent paymentIntent = (PaymentIntent) stripeObject;
  651. response.setStatus(200);
  652. break;
  653. case "charge.succeeded":
  654. //使用token支付成功回调
  655. Charge charge = (Charge) stripeObject;
  656. //TODO 此时根据charge ID 查询出关联的订单并处理支付成功业务代码
  657. response.setStatus(200);
  658. break;
  659. case "checkout.session.completed":
  660. //使用checkout支付成功回调
  661. Session session = (Session) stripeObject;
  662. stripeService.fulfillOrder(session);
  663. response.setStatus(200);
  664. break;
  665. default:
  666. response.setStatus(400);
  667. return "";
  668. }
  669. response.setStatus(200);
  670. return "";
  671. }
  672. /**
  673. * 余额明细
  674. */
  675. @GetMapping("/get/balance/detail")
  676. public Result<SearchResult<UserBalanceSourceRecord>> getUserBalanceSourceRecord() {
  677. long userId = StpUserUtil.getLoginIdAsLong();
  678. SearchResult<UserBalanceSourceRecord> search = beanSearcher.search(UserBalanceSourceRecord.class, MapUtils.flatBuilder(request.getParameterMap())
  679. .field(UserBalanceSourceRecord::getUserId, userId)
  680. .field(UserBalanceSourceRecord::getDetail).op(Operator.NotNull)
  681. .orderBy(UserBalanceSourceRecord::getId).desc()
  682. .onlySelect(UserBalanceSourceRecord::getBalance, UserBalanceSourceRecord::getDetail, UserBalanceSourceRecord::getCreatedTime)
  683. .build());
  684. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  685. }
  686. /**
  687. * 获取套餐订单列表
  688. */
  689. @GetMapping("/upgrade/get")
  690. public Result<SearchResult<UpgradeOrderDonView>> listUpgradeOrder(){
  691. long userId = StpUserUtil.getLoginIdAsLong();
  692. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  693. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  694. SearchResult<UpgradeOrderDonView> search = beanSearcher.search(UpgradeOrderDonView.class, builder
  695. .field(UpgradeOrderDonView::getUserId, userIds).op(Operator.InList)
  696. .orderBy(UpgradeOrderDonView::getId).desc()
  697. .build());
  698. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  699. }
  700. /**
  701. * 获取套餐订单详情
  702. */
  703. @GetMapping("/get/upgrade/{orderId}")
  704. public Result<UpgradeOrderDetailView> upgradeOrderDetail(@PathVariable Long orderId) {
  705. Long userId = StpUserUtil.getUserIdAfterLogin();
  706. UpgradeOrderDetailView detail = orderDonService.getUpgradeOrderDetail(orderId, userId);
  707. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  708. }
  709. /**
  710. * 取消套餐订单
  711. */
  712. @GetMapping("/get/close/upgrade/{orderId}")
  713. public Result<String> closeUpgradeOrder(@PathVariable Long orderId) {
  714. long userId = StpUserUtil.getLoginIdAsLong();
  715. orderDonService.closeUpgradeOrder(orderId, userId);
  716. return GatewayResponse.SUCCESS.newBuilder().toResult();
  717. }
  718. /**
  719. * midjourney查询订单用户账号剩余次数
  720. */
  721. @GetMapping("/get/midjourney/user")
  722. public Result<MidjourneyUserView> getMidjourneyUser(Long relationId) {
  723. long userId = StpUserUtil.getLoginIdAsLong();
  724. MidjourneyUserView search = beanSearcher.searchFirst(MidjourneyUserView.class, MapUtils.flatBuilder(request.getParameterMap())
  725. .field(MidjourneyUserView::getUserId, userId).field(MidjourneyUserView::getRelationId, relationId).build());
  726. if (search == null) {
  727. MidjourneyUser midjourneyUser = midjourneyAccountService.getMidjourneyUserToken(userId, relationId);
  728. search = new MidjourneyUserView();
  729. BeanUtils.copyProperties(midjourneyUser, search);
  730. }
  731. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  732. }
  733. /**
  734. * 续费升级提交支付
  735. */
  736. @PostMapping("/post/renew/upgrade/submit")
  737. public Result<OrderDon> submitRenewUpgrade(@Validated @RequestBody OrderPayRequest payRequest) throws Exception {
  738. final String methodName = "续费升级吊起支付";
  739. //无需免登录
  740. Long userId = StpUserUtil.getLoginIdAsLong();
  741. payRequest.setUserId(userId);
  742. log.info("{}[start] params:{}", methodName, payRequest);
  743. String ip = ServletUtil.getClientIP(request);
  744. payRequest.setIp(ip);
  745. OrderDon orderDon = orderDonService.submitRenewUpgrade(payRequest);
  746. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  747. }
  748. /**
  749. * 获取续费套餐订单列表
  750. */
  751. @GetMapping("/renew/get")
  752. public Result<SearchResult<RenewUpgradeOrderDonView>> listRenewOrders(){
  753. long userId = StpUserUtil.getLoginIdAsLong();
  754. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  755. List<Long> userIds = UserBindRelationService.getRelationUserIdList(userId, null);
  756. SearchResult<RenewUpgradeOrderDonView> search = beanSearcher.search(RenewUpgradeOrderDonView.class, builder
  757. .field(UpgradeOrderDonView::getUserId, userIds).op(Operator.InList)
  758. .orderBy(UpgradeOrderDonView::getId).desc()
  759. .build());
  760. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  761. }
  762. /**
  763. * luma查询订单用户账号剩余次数
  764. */
  765. @GetMapping("/get/luma/user")
  766. public Result<LumaUserView> getLumaUser(Long relationId) {
  767. long userId = StpUserUtil.getLoginIdAsLong();
  768. LumaUserView search = beanSearcher.searchFirst(LumaUserView.class, MapUtils.flatBuilder(request.getParameterMap())
  769. .field(LumaUserView::getUserId, userId).field(LumaUserView::getRelationId, relationId).build());
  770. if (search == null) {
  771. LumaUser lumaUser = lumaService.getLumaUser(userId, relationId);
  772. search = new LumaUserView();
  773. BeanUtils.copyProperties(lumaUser, search);
  774. }
  775. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  776. }
  777. /**
  778. * 用户权益预支付
  779. */
  780. @PostMapping("/user/benefits/submit")
  781. public Result<OrderDon> userBenefitsSubmit(@RequestBody OrderPayRequest orderPayRequest) throws Exception {
  782. long userId = StpUserUtil.getLoginIdAsLong();
  783. orderPayRequest.setUserId(userId);
  784. String ip = ServletUtil.getClientIP(request);
  785. orderPayRequest.setIp(ip);
  786. OrderDon orderDon = orderDonService.userBenefitsSubmit(orderPayRequest);
  787. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  788. }
  789. }