PaypalV2Service.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package com.cyksj.service.paypal;
  2. import com.cyksj.common.exception.BusinessRuntimeException;
  3. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  4. import com.cyksj.common.util.Jsons;
  5. import com.cyksj.enums.GatewayApiCode;
  6. import com.cyksj.mapper.GoodsDonSkuMapper;
  7. import com.cyksj.model.entity.GoodsDonSku;
  8. import com.cyksj.model.entity.OrderDon;
  9. import com.cyksj.model.entity.PaypalPayConfig;
  10. import com.cyksj.model.entity.VipOrderDon;
  11. import com.cyksj.redis.RedisService;
  12. import com.cyksj.service.order.OrderDonService;
  13. import com.cyksj.service.order.MultiQuantityOrderService;
  14. import com.cyksj.service.order.VipOrderDonService;
  15. import com.paypal.base.rest.APIContext;
  16. import com.paypal.base.rest.OAuthTokenCredential;
  17. import com.paypal.base.rest.PayPalRESTException;
  18. import com.paypal.core.PayPalHttpClient;
  19. import com.paypal.http.HttpResponse;
  20. import com.paypal.orders.*;
  21. import lombok.RequiredArgsConstructor;
  22. import lombok.extern.slf4j.Slf4j;
  23. import org.springframework.stereotype.Service;
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.io.OutputStreamWriter;
  27. import java.math.BigDecimal;
  28. import java.math.RoundingMode;
  29. import java.net.HttpURLConnection;
  30. import java.net.URL;
  31. import java.util.*;
  32. /**
  33. * @author zwhui
  34. * @date 2025/2/14 11:07
  35. */
  36. @Service
  37. @Slf4j
  38. @RequiredArgsConstructor
  39. public class PaypalV2Service {
  40. private static final GlobalThreadPoolTaskExecutor THREAD_POOL = GlobalThreadPoolTaskExecutor.getInstance();
  41. private final PaypalPayConfigService paypalPayConfigService;
  42. private final OrderDonService orderDonService;
  43. private final RedisService redisService;
  44. private final GoodsDonSkuMapper skuMapper;
  45. private final VipOrderDonService vipOrderDonService;
  46. private final MultiQuantityOrderService multiQuantityOrderService;
  47. private static final String SANDBOX_URL = "https://api-m.sandbox.paypal.com";
  48. private static final String LIVE_URL = "https://api-m.paypal.com";
  49. /**
  50. * LOGIN。当客户单击PayPal Checkout时,客户将被重定向到页面以登录PayPal并批准付款。
  51. * BILLING。当客户单击PayPal Checkout时,客户将被重定向到一个页面,以输入信用卡或借记卡以及完成购买所需的其他相关账单信息
  52. * NO_PREFERENCE。当客户单击“ PayPal Checkout”时,将根据其先前的交互方式将其重定向到页面以登录PayPal并批准付款,或重定向至页面以输入信用卡或借记卡以及完成购买所需的其他相关账单信息使用PayPal。
  53. * 默认值:NO_PREFERENCE
  54. */
  55. public static final String LANDINGPAGE = "BILLING";
  56. /**
  57. * CONTINUE。将客户重定向到PayPal付款页面后,将出现“ 继续”按钮。当结帐流程启动时最终金额未知时,请使用此选项,并且您想将客户重定向到商家页面而不处理付款。
  58. * PAY_NOW。将客户重定向到PayPal付款页面后,出现“ 立即付款”按钮。当启动结帐时知道最终金额并且您要在客户单击“ 立即付款”时立即处理付款时,请使用此选项。
  59. */
  60. public static final String USERACTION = "PAY_NOW";
  61. public String createPayment(Long orderId, String successUrl) {
  62. OrderDon orderDon = orderDonService.getById(orderId);
  63. if (multiQuantityOrderService.isMultiQuantityOrder(orderId)) {
  64. throw BusinessRuntimeException.getInstance("Multi-quantity orders do not support PayPal");
  65. }
  66. if (orderDon.getGoodsId() == 26) {
  67. GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
  68. if (!sku.getIsMirror()) {
  69. throw BusinessRuntimeException.getInstance("订单异常..");
  70. }
  71. }
  72. //paypal 不能购买奈飞月付账号 24-1-23
  73. if (orderDon.getSkuId() != null && orderDon.getSkuId() == 4) {
  74. throw BusinessRuntimeException.getInstance("暂不支持paypal购买该规格车票..");
  75. }
  76. redisService.set(RedisService.key.ABROAD_SUCCESS_URL.getName() + orderId,successUrl,RedisService.key.ABROAD_SUCCESS_URL.getTimeout());
  77. BigDecimal money = orderDon.getMoney().divide(new BigDecimal(7),2,RoundingMode.HALF_DOWN);
  78. orderDon.setAbroadMoney(money);
  79. orderDon.setType(OrderDon.Type.PAYPAL);
  80. orderDonService.updateById(orderDon);
  81. if (OrderDon.Status.hasPayment.equals(orderDon.getStatus())) {
  82. throw new BusinessRuntimeException(GatewayApiCode.METADATA_SYSTEM_ERROR.getCode(),"该订单已支付");
  83. }
  84. PaypalPayConfig paypalPayConfig = paypalPayConfigService.getById(1);
  85. PayPalClient payPalClient = new PayPalClient();
  86. // 设置环境沙盒或生产
  87. PayPalHttpClient client = payPalClient.client(paypalPayConfig.getMode(), paypalPayConfig.getClientId(), paypalPayConfig.getClientSecret());
  88. //回调参数(支付成功success路径所携带的参数)
  89. Map<String, String> sParaTemp = new HashMap<String, String>();
  90. sParaTemp.put("orderId", orderId.toString());
  91. String returnUrl = "https://" + paypalPayConfig.getHost() + "/8081/api/applets/order/paypalV2/notify";
  92. // 配置请求参数
  93. OrderRequest orderRequest = new OrderRequest();
  94. orderRequest.checkoutPaymentIntent("CAPTURE");
  95. List<PurchaseUnitRequest> purchaseUnits = new ArrayList<>();
  96. BigDecimal totalMoney = money.divide(new BigDecimal(100), 2, RoundingMode.HALF_DOWN);
  97. purchaseUnits.add(new PurchaseUnitRequest().referenceId(orderId.toString()).amountWithBreakdown(new AmountWithBreakdown().currencyCode("USD").value(totalMoney.toString())));
  98. orderRequest.purchaseUnits(purchaseUnits);
  99. orderRequest.applicationContext(new ApplicationContext()
  100. .landingPage(LANDINGPAGE)
  101. .userAction(USERACTION)
  102. .returnUrl(returnUrl)
  103. .cancelUrl(paypalPayConfig.getCancelUrl()));
  104. OrdersCreateRequest request = new OrdersCreateRequest().requestBody(orderRequest);
  105. HttpResponse<Order> response;
  106. try {
  107. response = client.execute(request);
  108. Order order = response.result();
  109. String payHref = null;
  110. String status = order.status();
  111. if (status.equals("CREATED")) {
  112. List<LinkDescription> links = order.links();
  113. for (LinkDescription linkDescription : links) {
  114. if (linkDescription.rel().equals("approve")) {
  115. payHref = linkDescription.href();
  116. }
  117. }
  118. }
  119. return payHref;
  120. } catch (IOException e) {
  121. e.printStackTrace();
  122. }
  123. return null;
  124. }
  125. private static String paramsConvertUrl(Map<String, String> params) {
  126. StringBuilder urlParams = new StringBuilder("?");
  127. Set<Map.Entry<String, String>> entries = params.entrySet();
  128. for (Map.Entry<String, String> entry : params.entrySet()) {
  129. urlParams.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
  130. }
  131. String urlParamsStr = urlParams.toString();
  132. return urlParamsStr.substring(0, urlParamsStr.length()-1);
  133. }
  134. public static void main(String[] args) {
  135. String payUrl = "";
  136. PayPalClient payPalClient = new PayPalClient();
  137. // 设置环境沙盒或生产
  138. PayPalHttpClient client = payPalClient.client("sandbox", "Ad4Jbuus51awFCDQKRDkLHpLBfmCqFvCPYLTZEmQ8nEVQWV1jBuxNE7KfWqc8HOKgMCatrTLJFrTOqkb", "EKxtALS9isrGu7PcTLWjI3lGcPDMMkN8qwXIpW99oylFDfAf38nUB6hd0mbeVHv291BDfYtsB36IQRNN");
  139. //回调参数(支付成功success路径所携带的参数)
  140. Map<String, String> sParaTemp = new HashMap<String, String>();
  141. sParaTemp.put("orderId", "111");
  142. String returnUrl = "https://inside.yicanggongyi.com/8081/api/applets/order/paypal/notify";
  143. String url = returnUrl + paramsConvertUrl(sParaTemp);
  144. System.out.println("回调链接:"+url);
  145. // 配置请求参数
  146. OrderRequest orderRequest = new OrderRequest();
  147. orderRequest.checkoutPaymentIntent("CAPTURE");
  148. List<PurchaseUnitRequest> purchaseUnits = new ArrayList<>();
  149. purchaseUnits.add(new PurchaseUnitRequest().amountWithBreakdown(new AmountWithBreakdown().currencyCode("USD").value("100")));
  150. orderRequest.purchaseUnits(purchaseUnits);
  151. orderRequest.applicationContext(new ApplicationContext().landingPage(LANDINGPAGE)
  152. .userAction(USERACTION).returnUrl(url).cancelUrl("https://inside.yicanggongyi.com/yinhe/web/mine?modules=ticket"));
  153. OrdersCreateRequest request = new OrdersCreateRequest().requestBody(orderRequest);
  154. HttpResponse<Order> response;
  155. try {
  156. response = client.execute(request);
  157. Order order = response.result();
  158. String payHref = null;
  159. String status = order.status();
  160. if (status.equals("CREATED")) {
  161. List<LinkDescription> links = order.links();
  162. for (LinkDescription linkDescription : links) {
  163. if (linkDescription.rel().equals("approve")) {
  164. payHref = linkDescription.href();
  165. }
  166. }
  167. }
  168. payUrl = payHref;
  169. } catch (IOException e) {
  170. e.printStackTrace();
  171. }
  172. System.out.println(payUrl);
  173. }
  174. public String successPayment(String token, String payerId,PaypalPayConfig paypalPayConfig) throws Exception {
  175. log.info("paypalV2回调 token:{},payerId:{}", token, payerId);
  176. //捕获订单 进行支付
  177. HttpResponse<Order> response = null;
  178. OrdersCaptureRequest ordersCaptureRequest = new OrdersCaptureRequest(token);
  179. ordersCaptureRequest.requestBody(new OrderRequest());
  180. PayPalClient payPalClient = new PayPalClient();
  181. try {
  182. response = payPalClient.client(paypalPayConfig.getMode(), paypalPayConfig.getClientId(), paypalPayConfig.getClientSecret()).execute(ordersCaptureRequest);
  183. Order result = response.result();
  184. log.info("captureOrder response: {}", result);
  185. for (PurchaseUnit purchaseUnit : result.purchaseUnits()) {
  186. for (Capture capture : purchaseUnit.payments().captures()) {
  187. if ("COMPLETED".equals(capture.status())) {
  188. //支付成功
  189. // 订单号
  190. String saleId = capture.id();
  191. String fee = capture.sellerReceivableBreakdown().paypalFee().value();
  192. String orderId = purchaseUnit.referenceId();
  193. String json = Jsons.toJson(result);
  194. log.info("captureOrder response body: {}", json);
  195. //更新订单支付状态
  196. OrderDon orderDon = orderDonService.getById(orderId);
  197. orderDon.setTransactionId(saleId);
  198. orderDon.setPayTime(new Date());
  199. orderDon.setAbroadTransactionFee(new BigDecimal(fee).multiply(BigDecimal.valueOf(100)));
  200. orderDonService.orderNotify(orderDon);
  201. log.info("支付成功订单:"+orderId+",支付交易号:"+saleId);
  202. THREAD_POOL.execute(()->{
  203. try {
  204. APIContext apiContext = this.getAPIContext(paypalPayConfig.getClientId(), paypalPayConfig.getClientSecret(), paypalPayConfig.getMode());
  205. String baseUrl = "live".equals(paypalPayConfig.getMode()) ? LIVE_URL : SANDBOX_URL;
  206. URL url = new URL(baseUrl + "/v1/shipping/trackers-batch");
  207. HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
  208. httpConn.setRequestMethod("POST");
  209. httpConn.setRequestProperty("Content-Type", "application/json");
  210. httpConn.setRequestProperty("Authorization", apiContext.getAccessToken());
  211. httpConn.setDoOutput(true);
  212. OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
  213. writer.write("{\"trackers\": [{ \"transaction_id\": \"" + saleId + "\", \"status\": \"SHIPPED\"}]}");
  214. writer.flush();
  215. writer.close();
  216. httpConn.getOutputStream().close();
  217. InputStream responseStream = httpConn.getResponseCode() / 100 == 2 ? httpConn.getInputStream() : httpConn.getErrorStream();
  218. Scanner s = new Scanner(responseStream).useDelimiter("\\A");
  219. String res = s.hasNext() ? s.next() : "";
  220. log.info("添加物流信息 response:{}",res);
  221. } catch (Exception e) {
  222. e.printStackTrace();
  223. }
  224. });
  225. return redisService.getStr(RedisService.key.ABROAD_SUCCESS_URL.getName() + orderId);
  226. }
  227. }
  228. }
  229. } catch (IOException e) {
  230. throw new RuntimeException(e);
  231. }
  232. log.info("支付失败返回参数:"+ Jsons.toJson(response.result()));
  233. return paypalPayConfig.getCancelUrl();
  234. }
  235. private APIContext getAPIContext(String clientId,String clientSecret,String mode) throws PayPalRESTException {
  236. Map<String, String> sdkConfig = new HashMap<>();
  237. sdkConfig.put("mode", mode);
  238. OAuthTokenCredential authTokenCredential = new OAuthTokenCredential(clientId,clientSecret,sdkConfig);
  239. APIContext apiContext = new APIContext(authTokenCredential.getAccessToken());
  240. apiContext.setConfigurationMap(sdkConfig);
  241. return apiContext;
  242. }
  243. public String createVipPayment(Long orderId, String successUrl) {
  244. VipOrderDon orderDon = vipOrderDonService.getById(orderId);
  245. redisService.set(RedisService.key.ABROAD_SUCCESS_URL.getName() + orderId,successUrl,RedisService.key.ABROAD_SUCCESS_URL.getTimeout());
  246. BigDecimal money = orderDon.getMoney().divide(new BigDecimal(7),2,RoundingMode.HALF_DOWN);
  247. orderDon.setAbroadMoney(money);
  248. orderDon.setType(VipOrderDon.Type.PAYPAL);
  249. vipOrderDonService.updateById(orderDon);
  250. if (VipOrderDon.Status.hasPayment.equals(orderDon.getStatus())) {
  251. throw new BusinessRuntimeException(GatewayApiCode.METADATA_SYSTEM_ERROR.getCode(),"该订单已支付");
  252. }
  253. PaypalPayConfig paypalPayConfig = paypalPayConfigService.getById(1);
  254. PayPalClient payPalClient = new PayPalClient();
  255. // 设置环境沙盒或生产
  256. PayPalHttpClient client = payPalClient.client(paypalPayConfig.getMode(), paypalPayConfig.getClientId(), paypalPayConfig.getClientSecret());
  257. //回调参数(支付成功success路径所携带的参数)
  258. Map<String, String> sParaTemp = new HashMap<String, String>();
  259. sParaTemp.put("orderId", orderId.toString());
  260. String returnUrl = "https://" + paypalPayConfig.getHost() + "/8081/api/applet/vip/orders/paypalV2/notify";
  261. // 配置请求参数
  262. OrderRequest orderRequest = new OrderRequest();
  263. orderRequest.checkoutPaymentIntent("CAPTURE");
  264. List<PurchaseUnitRequest> purchaseUnits = new ArrayList<>();
  265. BigDecimal totalMoney = money.divide(new BigDecimal(100), 2, RoundingMode.HALF_DOWN);
  266. purchaseUnits.add(new PurchaseUnitRequest().referenceId(orderId.toString()).amountWithBreakdown(new AmountWithBreakdown().currencyCode("USD").value(totalMoney.toString())));
  267. orderRequest.purchaseUnits(purchaseUnits);
  268. orderRequest.applicationContext(new ApplicationContext()
  269. .landingPage(LANDINGPAGE)
  270. .userAction(USERACTION)
  271. .returnUrl(returnUrl)
  272. .cancelUrl(paypalPayConfig.getCancelUrl()));
  273. OrdersCreateRequest request = new OrdersCreateRequest().requestBody(orderRequest);
  274. HttpResponse<Order> response;
  275. try {
  276. response = client.execute(request);
  277. Order order = response.result();
  278. String payHref = null;
  279. String status = order.status();
  280. if (status.equals("CREATED")) {
  281. List<LinkDescription> links = order.links();
  282. for (LinkDescription linkDescription : links) {
  283. if (linkDescription.rel().equals("approve")) {
  284. payHref = linkDescription.href();
  285. }
  286. }
  287. }
  288. return payHref;
  289. } catch (IOException e) {
  290. e.printStackTrace();
  291. }
  292. return null;
  293. }
  294. public String successVipPayment(String token, String payerId, PaypalPayConfig paypalPayConfig) throws Exception {
  295. log.info("paypalV2回调 token:{},payerId:{}", token, payerId);
  296. //捕获订单 进行支付
  297. HttpResponse<Order> response = null;
  298. OrdersCaptureRequest ordersCaptureRequest = new OrdersCaptureRequest(token);
  299. ordersCaptureRequest.requestBody(new OrderRequest());
  300. PayPalClient payPalClient = new PayPalClient();
  301. try {
  302. response = payPalClient.client(paypalPayConfig.getMode(), paypalPayConfig.getClientId(), paypalPayConfig.getClientSecret()).execute(ordersCaptureRequest);
  303. Order result = response.result();
  304. log.info("captureOrder response: {}", result);
  305. for (PurchaseUnit purchaseUnit : result.purchaseUnits()) {
  306. for (Capture capture : purchaseUnit.payments().captures()) {
  307. if ("COMPLETED".equals(capture.status())) {
  308. //支付成功
  309. // 订单号
  310. String saleId = capture.id();
  311. String fee = capture.sellerReceivableBreakdown().paypalFee().value();
  312. String orderId = purchaseUnit.referenceId();
  313. String json = Jsons.toJson(result);
  314. log.info("captureOrder response body: {}", json);
  315. //更新订单支付状态
  316. VipOrderDon orderDon = vipOrderDonService.getById(orderId);
  317. orderDon.setTransactionId(saleId);
  318. orderDon.setPayTime(new Date());
  319. orderDon.setAbroadTransactionFee(new BigDecimal(fee).multiply(BigDecimal.valueOf(100)));
  320. vipOrderDonService.orderNotify(orderDon);
  321. log.info("支付成功订单:"+orderId+",支付交易号:"+saleId);
  322. THREAD_POOL.execute(()->{
  323. try {
  324. APIContext apiContext = this.getAPIContext(paypalPayConfig.getClientId(), paypalPayConfig.getClientSecret(), paypalPayConfig.getMode());
  325. String baseUrl = "live".equals(paypalPayConfig.getMode()) ? LIVE_URL : SANDBOX_URL;
  326. URL url = new URL(baseUrl + "/v1/shipping/trackers-batch");
  327. HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
  328. httpConn.setRequestMethod("POST");
  329. httpConn.setRequestProperty("Content-Type", "application/json");
  330. httpConn.setRequestProperty("Authorization", apiContext.getAccessToken());
  331. httpConn.setDoOutput(true);
  332. OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
  333. writer.write("{\"trackers\": [{ \"transaction_id\": \"" + saleId + "\", \"status\": \"SHIPPED\"}]}");
  334. writer.flush();
  335. writer.close();
  336. httpConn.getOutputStream().close();
  337. InputStream responseStream = httpConn.getResponseCode() / 100 == 2 ? httpConn.getInputStream() : httpConn.getErrorStream();
  338. Scanner s = new Scanner(responseStream).useDelimiter("\\A");
  339. String res = s.hasNext() ? s.next() : "";
  340. log.info("添加物流信息 response:{}",res);
  341. } catch (Exception e) {
  342. e.printStackTrace();
  343. }
  344. });
  345. return redisService.getStr(RedisService.key.ABROAD_SUCCESS_URL.getName() + orderId);
  346. }
  347. }
  348. }
  349. } catch (IOException e) {
  350. throw new RuntimeException(e);
  351. } catch (Exception e) {
  352. throw new RuntimeException(e);
  353. }
  354. log.info("支付失败返回参数:"+ Jsons.toJson(response.result()));
  355. return paypalPayConfig.getCancelUrl();
  356. }
  357. }