OrderController.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. package com.cyksj.web.controller.payment;
  2. import cn.hutool.core.util.StrUtil;
  3. import cn.hutool.extra.qrcode.QrCodeUtil;
  4. import cn.hutool.extra.qrcode.QrConfig;
  5. import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
  6. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  7. import com.cyksj.common.constant.Constant;
  8. import com.cyksj.common.exception.BusinessRuntimeException;
  9. import com.cyksj.common.util.IoKit;
  10. import com.cyksj.common.util.Jsons;
  11. import com.cyksj.common.util.Xmls;
  12. import com.cyksj.config.zfb.BaseZfbConfig;
  13. import com.cyksj.config.zfb.ZfbProductCode;
  14. import com.cyksj.dto.Result;
  15. import com.cyksj.enums.GatewayApiCode;
  16. import com.cyksj.enums.GatewayResponse;
  17. import com.cyksj.mapper.OrderDonMapper;
  18. import com.cyksj.mapper.OrderDonWaybillMapper;
  19. import com.cyksj.mapper.UserMapper;
  20. import com.cyksj.mapper.channel.UserPayEquipmentAvailableBenefitsMapper;
  21. import com.cyksj.mapper.market.task.UserBindDetailMapper;
  22. import com.cyksj.model.dto.AliPayParams;
  23. import com.cyksj.model.dto.H5JsPayParams;
  24. import com.cyksj.model.entity.*;
  25. import com.cyksj.model.manage.views.OrderDonSearchView;
  26. import com.cyksj.model.manage.views.OrderDonView;
  27. import com.cyksj.model.request.AlipayOrderDonReq;
  28. import com.cyksj.model.request.OrderPayRequest;
  29. import com.cyksj.model.response.AliPayTradeStatus;
  30. import com.cyksj.model.views.GoodsDonSkuView;
  31. import com.cyksj.model.views.OrderCommentView;
  32. import com.cyksj.service.order.OrderDonService;
  33. import com.cyksj.service.paypal.PayPalService;
  34. import com.cyksj.service.paypal.PaypalPayConfigService;
  35. import com.cyksj.service.stripe.StripePayConfigService;
  36. import com.cyksj.service.stripe.StripeService;
  37. import com.cyksj.service.user.UserService;
  38. import com.cyksj.web.util.StpUserUtil;
  39. import com.ejlchina.searcher.BeanSearcher;
  40. import com.ejlchina.searcher.SearchResult;
  41. import com.ejlchina.searcher.param.Operator;
  42. import com.ejlchina.searcher.util.MapUtils;
  43. import com.google.gson.JsonSyntaxException;
  44. import com.paypal.api.payments.Links;
  45. import com.paypal.api.payments.Payment;
  46. import com.stripe.exception.SignatureVerificationException;
  47. import com.stripe.model.*;
  48. import com.stripe.model.checkout.Session;
  49. import com.stripe.net.Webhook;
  50. import lombok.extern.slf4j.Slf4j;
  51. import org.apache.commons.lang3.StringUtils;
  52. import org.springframework.beans.factory.annotation.Autowired;
  53. import org.springframework.validation.annotation.Validated;
  54. import org.springframework.web.bind.annotation.*;
  55. import javax.annotation.Resource;
  56. import javax.servlet.http.HttpServletRequest;
  57. import javax.servlet.http.HttpServletResponse;
  58. import java.io.InputStream;
  59. import java.io.OutputStream;
  60. import java.nio.charset.StandardCharsets;
  61. import java.util.HashMap;
  62. import java.util.List;
  63. import java.util.Map;
  64. import java.util.Set;
  65. import java.util.stream.Collectors;
  66. /**
  67. * @author chan
  68. * @date 2021/10/11 下午3:50
  69. */
  70. @Slf4j
  71. @RequestMapping("/applets/order")
  72. @RestController
  73. public class OrderController {
  74. @Autowired
  75. private OrderDonService orderDonService;
  76. @Resource
  77. private BeanSearcher beanSearcher;
  78. @Resource
  79. private HttpServletRequest request;
  80. @Resource
  81. private HttpServletResponse response;
  82. @Autowired
  83. private OrderDonMapper orderDonMapper;
  84. @Autowired
  85. private UserBindDetailMapper userBindDetailMapper;
  86. @Autowired
  87. private UserMapper userMapper;
  88. @Autowired
  89. private UserPayEquipmentAvailableBenefitsMapper availableBenefitsMapper;
  90. @Autowired
  91. private OrderDonWaybillMapper waybillMapper;
  92. @Autowired
  93. private UserService userService;
  94. @Autowired
  95. private PaypalPayConfigService paypalPayConfigService;
  96. @Autowired
  97. private PayPalService payPalService;
  98. @Autowired
  99. private StripePayConfigService stripePayConfigService;
  100. @Autowired
  101. private StripeService stripeService;
  102. /**
  103. * 支付
  104. * @author chan
  105. * @date 2021-10-11 下午4:56
  106. */
  107. @PostMapping("/post/submit")
  108. public Result<OrderDon> submit(@Validated @RequestBody OrderPayRequest payRequest) throws Exception {
  109. final String methodName = "吊起微信支付";
  110. if (payRequest.getIsNoLogin() == null || !payRequest.getIsNoLogin()) {
  111. payRequest.setUserId(StpUserUtil.getLoginIdAsLong());
  112. }
  113. log.info("{}[start] params:{}",methodName,payRequest);
  114. OrderDon orderDon = orderDonService.submit(payRequest);
  115. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
  116. }
  117. /**
  118. * 0元订单确认
  119. */
  120. @PostMapping("/post/order/status/{orderId}")
  121. public Result<String> zeroOrderConfirm(@PathVariable Long orderId) {
  122. orderDonService.zeroOrderConfirm(orderId);
  123. return GatewayResponse.SUCCESS.newBuilder().toResult();
  124. }
  125. /**
  126. * 支付
  127. * @author chan
  128. * @date 2021-10-11 下午4:56
  129. */
  130. @PostMapping("/post/pay/{orderId}")
  131. public Result<H5JsPayParams> pay(@PathVariable Long orderId) throws Exception {
  132. final String methodName = "吊起微信支付";
  133. log.info("{}[start] orderId:{}",methodName,orderId);
  134. H5JsPayParams payParams = orderDonService.pay(orderId, "JSAPI");
  135. return GatewayResponse.SUCCESS.newBuilder().toResult(payParams);
  136. }
  137. /**
  138. * 调用生成订单之后
  139. * 微信网页预下单获取交易链接生成二维码
  140. */
  141. @PostMapping("/get/wx/orderQrCode/{orderId}")
  142. public Result<String> createUnifiedOrderQr(@PathVariable Long orderId) throws Exception {
  143. //预下单
  144. H5JsPayParams payParams = orderDonService.wxPcWebPay(orderId, "NATIVE");
  145. //获取二维码链接code_url
  146. String codeUrl = payParams.getCodeUrl();
  147. QrConfig qrConfig = new QrConfig(300, 300);
  148. return GatewayResponse.SUCCESS.newBuilder().toResult(QrCodeUtil.generateAsBase64(codeUrl, qrConfig, "png"));
  149. }
  150. /**
  151. * 微信支付回调
  152. * @author chan
  153. * @date 2021-10-11 下午5:42
  154. */
  155. @PostMapping("/prepay/notify")
  156. public void prepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  157. String xml = IoKit.toString(request.getInputStream());
  158. log.info("=== 微信支付成功的回调: \n {}", xml);
  159. // 解析xml
  160. Map<String, String> map = Xmls.toMap(xml);
  161. // 支付失败
  162. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  163. throw BusinessRuntimeException.getInstance("支付失败.");
  164. }
  165. orderDonService.prepayNotify(map);
  166. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  167. OutputStream out = null;
  168. try {
  169. out = response.getOutputStream();
  170. IoKit.write(toWeChatXmlResponse, out);
  171. } catch (Exception e) {
  172. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  173. } finally {
  174. IoKit.close(out);
  175. }
  176. }
  177. /**
  178. * pc端微信支付回调
  179. * @author chan
  180. * @date 2021-10-11 下午5:42
  181. */
  182. @PostMapping("/pc/prepay/notify")
  183. public void pcPrepayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  184. String xml = IoKit.toString(request.getInputStream());
  185. log.info("=== 微信pc端分发支付成功的回调: \n {}", xml);
  186. // 解析xml
  187. Map<String, String> map = Xmls.toMap(xml);
  188. // 支付失败
  189. if (!StringUtils.equals("SUCCESS", map.get("return_code")) || !StringUtils.equals("SUCCESS", map.get("result_code"))) {
  190. throw BusinessRuntimeException.getInstance("支付失败.");
  191. }
  192. orderDonService.prepayNotify(map);
  193. log.info("pc端微信支付回调修改订单状态成功");
  194. String toWeChatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  195. OutputStream out = null;
  196. try {
  197. out = response.getOutputStream();
  198. IoKit.write(toWeChatXmlResponse, out);
  199. } catch (Exception e) {
  200. throw BusinessRuntimeException.getInstance(e,e.getMessage());
  201. } finally {
  202. IoKit.close(out);
  203. }
  204. }
  205. /**
  206. * 支付宝表单支付
  207. * 支付宝调起支付宝表单
  208. * 手机支付
  209. */
  210. @PostMapping("/post/pay/zfb")
  211. @Deprecated
  212. public Result<String> aliPay(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  213. Long orderId = re.getOrderId();
  214. String returnUrl = re.getReturnUrl();
  215. AliPayParams aliPayParams = orderDonService.aliPay(orderId, returnUrl, ZfbProductCode.MOBILE_WEB.getProductCode(), null);
  216. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  217. //直接将完整的表单html输出到页面
  218. // response.getWriter().write(aliPayParams.getBody());
  219. // response.getWriter().flush();
  220. // response.getWriter().close();
  221. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  222. }
  223. /**
  224. * 支付宝web支付
  225. * pc网页内嵌二维码
  226. */
  227. @PostMapping("/get/zfb/orderQrCode")
  228. public Result<String> zfbWebQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  229. Long orderId = re.getOrderId();
  230. String returnUrl = re.getReturnUrl();
  231. AliPayParams aliPayParams = orderDonService.aliPay(orderId, returnUrl, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_orderCode);
  232. // response.setContentType("text/html;charset=" + BaseZfbConfig.charset);
  233. //直接将完整的表单html输出到页面
  234. // response.getWriter().write(aliPayParams.getBody());
  235. // response.getWriter().flush();
  236. // response.getWriter().close();
  237. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  238. }
  239. /**
  240. * 支付宝web支付
  241. * pc网页跳转二维码
  242. */
  243. @PostMapping("/get/zfb/orderRedirect")
  244. public Result<String> zfbWebRedirectQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
  245. Long orderId = re.getOrderId();
  246. String returnUrl = re.getReturnUrl();
  247. AliPayParams aliPayParams = orderDonService.aliPay(orderId, returnUrl, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_redirect);
  248. return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
  249. }
  250. /**
  251. * 支付宝回调
  252. */
  253. @PostMapping("/prepay/zfb/notify")
  254. public String aliPayNotify(HttpServletRequest request) throws Exception {
  255. ////将异步通知中收到的所有参数都存放到map中
  256. Map<String, String> params = convertRequestParamsToMap(request);
  257. String tradeStatus = params.get("trade_status");
  258. String orderNo = params.get("out_trade_no");
  259. if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
  260. log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
  261. orderDonService.aliPayNotify(params);
  262. } else {
  263. log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
  264. return "fail";
  265. }
  266. return "success";
  267. }
  268. /**
  269. * 支付宝转账
  270. */
  271. // @PostMapping("/zfb/transfer/accounts")
  272. // @NoSubmit
  273. // public Result<String> zfbTransferAccounts(@RequestBody @Validated TransferAccountsReq transferAccountsReq) throws Exception {
  274. // long userId = StpUserUtil.getLoginIdAsLong();
  275. // transferAccountsReq.setUserId(userId);
  276. // orderDonService.transferAccounts(transferAccountsReq);
  277. // return GatewayResponse.SUCCESS.newBuilder().toResult("转账成功");
  278. // }
  279. /**
  280. * 查询支付宝转账状态
  281. */
  282. @GetMapping("/zfb/transfer/status")
  283. public Result<String> getTransFerStatusByTid(String translationId) throws Exception {
  284. AlipayFundTransCommonQueryResponse response = orderDonService.getTransFerStatusByTid(translationId);
  285. if (response.isSuccess()) {
  286. if (!Constant.SUCCESS.equals(response.getStatus())) {
  287. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getFailReason());
  288. }
  289. return GatewayResponse.SUCCESS.newBuilder().toResult("该红包已转账成功");
  290. }
  291. return GatewayResponse.SUCCESS.newBuilder().toResult(response.getSubMsg());
  292. }
  293. /**
  294. * 获取订单列表
  295. */
  296. @GetMapping("/get")
  297. public Result<SearchResult<OrderDonView>> list(){
  298. long userId = StpUserUtil.getLoginIdAsLong();
  299. List<Long> userIds = userService.getRelationUserIdList(userId, null);
  300. SearchResult<OrderDonView> search = beanSearcher.search(OrderDonView.class, MapUtils.flatBuilder(request.getParameterMap())
  301. .field(OrderDonView::getUserId, userIds).op(Operator.InList)
  302. .orderBy(OrderDonView::getId).desc()
  303. .build());
  304. search.getDataList().forEach(data->{
  305. Integer count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  306. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, data.getId())
  307. .eq(UserPayEquipmentAvailableBenefits::getDeleted, true));
  308. data.setIsHasBenefits(count > 0 ? true : false);
  309. if (data.getIsBenefits() != null && data.getIsBenefits()) {
  310. String benefitsList = data.getBenefitsList();
  311. if (StrUtil.isNotBlank(benefitsList)) {
  312. try {
  313. List<Long> skuIds = Jsons.parseList(benefitsList, GoodsDonSku.class).stream().map(GoodsDonSku::getId).collect(Collectors.toList());
  314. data.setBenefitsViews(beanSearcher.searchAll(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuIds).op(Operator.InList).build()));
  315. } catch (Exception e) {
  316. }
  317. }
  318. }
  319. data.setWaybill(waybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, data.getId()).last("limit 1")));
  320. });
  321. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  322. }
  323. /**
  324. * 获取订单详情
  325. */
  326. @GetMapping("/get/{orderId}")
  327. public Result<OrderDetailView> detail(@PathVariable Long orderId, Boolean isNoLogin) {
  328. Long userId = null;
  329. if (isNoLogin == null || !isNoLogin) {
  330. userId = StpUserUtil.getLoginIdAsLong();
  331. }
  332. OrderDetailView detail = orderDonService.getDetail(orderId, userId);
  333. return GatewayResponse.SUCCESS.newBuilder().toResult(detail);
  334. }
  335. /**
  336. * 取消订单
  337. */
  338. @GetMapping("/get/close/{orderId}")
  339. public Result<String> closeOrder(@PathVariable Long orderId){
  340. orderDonService.closeOrder(orderId);
  341. return GatewayResponse.SUCCESS.newBuilder().toResult();
  342. }
  343. @GetMapping("/get/order/status/{orderId}")
  344. public Result<OrderDonSearchView> getOrderStatusById(@PathVariable Long orderId) {
  345. if (orderId < 1) {
  346. throw BusinessRuntimeException.getInstance("订单不存在");
  347. }
  348. OrderDonSearchView orderDonView = beanSearcher.searchFirst(OrderDonSearchView.class, MapUtils.builder()
  349. .put("orderId", String.format("where id = %s", orderId))
  350. .build());
  351. if (orderDonView == null) {
  352. throw BusinessRuntimeException.getInstance("订单不存在");
  353. }
  354. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
  355. }
  356. @PostMapping("/get/noLogin/order")
  357. public Result<List<OrderDonView>> getSearchResult(@RequestBody List<Long> orderIds) {
  358. List<OrderDonView> orderDonViews = beanSearcher.searchAll(OrderDonView.class, MapUtils.builder()
  359. .field(OrderDonView::getId, orderIds).op(Operator.InList)
  360. .orderBy(OrderDonView::getId).desc().build());
  361. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonViews);
  362. }
  363. /**
  364. * 平台评论列表
  365. */
  366. @GetMapping("/get/orderComment")
  367. public Result<SearchResult<OrderCommentView>> getOrderCommentView() {
  368. SearchResult<OrderCommentView> search = beanSearcher.search(OrderCommentView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  369. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  370. }
  371. /**
  372. * 电脑端手机号注册 购买车票是否绑定了微信用户
  373. */
  374. @GetMapping("/isBindWx")
  375. public Result<Boolean> isBindWx() {
  376. Long userId = StpUserUtil.getLoginIdAsLong();
  377. User user = userMapper.selectById(userId);
  378. if (user == null) {
  379. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  380. }
  381. if (StrUtil.isEmpty(user.getLoginPhone())) {
  382. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  383. }
  384. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  385. .eq(UserBindDetail::getPhone, user.getLoginPhone()));
  386. if (userBindDetail == null) {
  387. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  388. }
  389. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  390. }
  391. /**
  392. * 是否绑定了邮箱或手机号
  393. */
  394. @GetMapping("/isBind")
  395. public Result<Boolean> isBindPhoneOrEmail() {
  396. Long userId = StpUserUtil.getLoginIdAsLong();
  397. User user = userMapper.selectById(userId);
  398. if (user == null) {
  399. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  400. }
  401. if (StrUtil.isEmpty(user.getOpenId())) {
  402. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  403. }
  404. UserBindDetail userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
  405. .eq(UserBindDetail::getUserId, userId));
  406. if (userBindDetail == null) {
  407. return GatewayResponse.SUCCESS.newBuilder().toResult(false);
  408. }
  409. return GatewayResponse.SUCCESS.newBuilder().toResult(true);
  410. }
  411. /**
  412. * 获取支付宝回调参数
  413. */
  414. private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
  415. Map<String, String> retMap = new HashMap<>();
  416. Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
  417. for (Map.Entry<String, String[]> entry : entrySet) {
  418. String name = entry.getKey();
  419. String[] values = entry.getValue();
  420. int valLen = values.length;
  421. if (valLen == 1) {
  422. retMap.put(name, values[0]);
  423. } else if (valLen > 1) {
  424. StringBuilder sb = new StringBuilder();
  425. for (String val : values) {
  426. sb.append(",").append(val);
  427. }
  428. retMap.put(name, sb.substring(1));
  429. } else {
  430. retMap.put(name, "");
  431. }
  432. }
  433. return retMap;
  434. }
  435. /**
  436. * paypal支付
  437. */
  438. @PostMapping("/paypal/pay/{orderId}")
  439. public Result<String> paypalPay(@PathVariable Long orderId,String successUrl) throws Exception {
  440. final String methodName = "paypal支付";
  441. log.info("{}[start] orderId:{}",methodName,orderId);
  442. Payment payment = payPalService.createPayment(orderId,successUrl);
  443. String payUrl = "/";
  444. log.info("paypal links:{}",payment.getLinks());
  445. for(Links links : payment.getLinks()){
  446. if("approval_url".equals(links.getRel())){
  447. // 客户付款登陆地址
  448. String payPalUrl = links.getHref();
  449. log.info("PayPal调起支付成功[end]:{}", orderId);
  450. payUrl = payPalUrl;
  451. }
  452. }
  453. log.info("paypal支付成功[end]");
  454. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  455. }
  456. /**
  457. * stripe支付
  458. */
  459. @PostMapping("/stripe/pay/{orderId}")
  460. public Result<String> stripePay(@PathVariable Long orderId,String successUrl) throws Exception {
  461. final String methodName = "stripe支付";
  462. log.info("{}[start] orderId:{}",methodName,orderId);
  463. String payUrl = stripeService.checkOutStripe(orderId,successUrl);
  464. log.info("Stripe支付成功 result:{}[end]",payUrl);
  465. return GatewayResponse.SUCCESS.newBuilder().toResult(payUrl);
  466. }
  467. /**
  468. * paypal支付回调
  469. */
  470. @RequestMapping(value = "/paypal/notify")
  471. public void successPay(@RequestParam(value = "paymentId") String paymentId, @RequestParam(value = "PayerID") String PayerID) throws Exception {
  472. PaypalPayConfig paypalPayConfig = paypalPayConfigService.getById(1);
  473. response.sendRedirect(payPalService.successPayment(paymentId,PayerID,paypalPayConfig));
  474. }
  475. /**
  476. * stripe支付回调
  477. */
  478. @PostMapping("/stripe/notify")
  479. @ResponseBody
  480. public String webhooks() throws Exception {
  481. InputStream inputStream = request.getInputStream();
  482. byte[] bytes = IoKit.toBytes(inputStream);
  483. String payload = new String(bytes, StandardCharsets.UTF_8);
  484. String sigHeader = request.getHeader("Stripe-Signature");
  485. StripePayConfig stripePayConfig = stripePayConfigService.getById(1);
  486. Event event = null;
  487. try {
  488. event = Webhook.constructEvent(
  489. payload, sigHeader, stripePayConfig.getWebhookSecret()
  490. );
  491. } catch (JsonSyntaxException | SignatureVerificationException e) {
  492. response.setStatus(400);
  493. return "";
  494. }
  495. // Deserialize the nested object inside the event
  496. EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer();
  497. StripeObject stripeObject = null;
  498. if (dataObjectDeserializer.getObject().isPresent()) {
  499. stripeObject = dataObjectDeserializer.getObject().orElse(null);
  500. } else {
  501. // Deserialization failed, probably due to an API version mismatch.
  502. // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for
  503. // instructions on how to handle this case, or return an error here.
  504. }
  505. // Handle the event
  506. switch (event.getType()) {
  507. case "payment_intent.succeeded":
  508. PaymentIntent paymentIntent = (PaymentIntent) stripeObject;
  509. response.setStatus(200);
  510. break;
  511. case "charge.succeeded":
  512. //使用token支付成功回调
  513. Charge charge = (Charge) stripeObject;
  514. //TODO 此时根据charge ID 查询出关联的订单并处理支付成功业务代码
  515. response.setStatus(200);
  516. break;
  517. case "checkout.session.completed":
  518. //使用checkout支付成功回调
  519. Session session = (Session) stripeObject;
  520. stripeService.fulfillOrder(session);
  521. response.setStatus(200);
  522. break;
  523. default:
  524. response.setStatus(400);
  525. return "";
  526. }
  527. response.setStatus(200);
  528. return "";
  529. }
  530. }