OrderController.java 32 KB

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