From ef6ae58ff754ad3e370a7e5f14dcb02660dd6264 Mon Sep 17 00:00:00 2001 From: wuchunlei Date: Wed, 28 May 2025 09:05:26 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=A0=E9=99=A4paypal=E6=94=AF=E4=BB=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/paypal/config/PaypalConfig.java | 216 ------------------ .../paypal/controller/PaypalController.java | 174 -------------- .../paypal/service/PayPaypalOrderService.java | 7 - .../service/PayPaypalOrderServiceImpl.java | 16 -- 4 files changed, 413 deletions(-) delete mode 100644 src/main/java/com/peanut/modules/pay/paypal/config/PaypalConfig.java delete mode 100644 src/main/java/com/peanut/modules/pay/paypal/controller/PaypalController.java delete mode 100644 src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderService.java delete mode 100644 src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderServiceImpl.java diff --git a/src/main/java/com/peanut/modules/pay/paypal/config/PaypalConfig.java b/src/main/java/com/peanut/modules/pay/paypal/config/PaypalConfig.java deleted file mode 100644 index 13ace79a..00000000 --- a/src/main/java/com/peanut/modules/pay/paypal/config/PaypalConfig.java +++ /dev/null @@ -1,216 +0,0 @@ -package com.peanut.modules.pay.paypal.config; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.peanut.modules.common.entity.BuyOrder; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; -import java.io.*; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.*; - -@Component -@Slf4j -public class PaypalConfig { - - //沙盒 - public static final String modeUrl = "https://api-m.sandbox.paypal.com"; - public static final String CLIENID ="Ab8SeEuhkLGp6Fts9V3Cti0UcXQhITRWZkiHDM3U1fDY9YrrRc5IOcYHPfV6qROhmh0hvgysqrfOCSUr"; - public static final String SECRET ="EF63FGWI9fd4q07Ndvc_h8P7jxiZcGOWn8Ul_y1_EKpluKJNFHOW8BP62Kf1wBDQ3XYIeqF8_kVrDF7C"; - public static final String WEBSCR ="https://www.sandbox.paypal.com/cgi-bin/webscr";//回调验证地址 - //sb-in47yk34022562@personal.example.com - //p#54df;P - - //sb-n2lz015338486@business.example.com - //4lnAJn.G - - //正式 -// public static final String modeUrl = "https://api-m.paypal.com"; -// public static final String CLIENID =""; -// public static final String SECRET =""; -// public static final String WEBSCR ="https://www.paypal.com/cgi-bin/webscr"; - - - public static final String accessTokenURL = "/v1/oauth2/token"; - public static final String createOrderURL = "/v2/checkout/orders"; - public static final String captureURL = "/v2/checkout/orders/%1s/capture"; - public static final String orderInfoURL = "/v2/checkout/orders/"; - public static final String refundURL = "/v2/payments/captures/%1s/refund"; - public static final String refundInfoURL = "/v2/payments/refunds/"; - - - - //回调验证 - public String receiveVerify(String verifyData) throws Exception{ - URL url = new URL(WEBSCR); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setDoOutput(true); - OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); - writer.write(verifyData); - writer.flush(); - writer.close(); - connection.getOutputStream().close(); - InputStream responseStream = connection.getResponseCode() / 100 == 2 - ? connection.getInputStream() - : connection.getErrorStream(); - Scanner s = new Scanner(responseStream).useDelimiter("\\A"); - String response = s.hasNext() ? s.next() : ""; - log.info(">>>>>>>>>>>palypal回调验证返回的信息是 result = {}", response); - return response; - } - - //退款查询 - public JSONObject refundInfo(String refundId) throws Exception{ - URL url = new URL(modeUrl+refundInfoURL+refundId); - HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); - httpConn.setRequestMethod("GET"); - httpConn.setRequestProperty("Content-Type", "application/json"); - httpConn.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token")); - - InputStream responseStream = httpConn.getResponseCode() / 100 == 2 - ? httpConn.getInputStream() - : httpConn.getErrorStream(); - Scanner s = new Scanner(responseStream).useDelimiter("\\A"); - String response = s.hasNext() ? s.next() : ""; - log.info(">>>>>>>>>>>palypal退款查询返回的信息是 result = {}", response); - return JSONObject.parseObject(response); - } - - //退款 - public JSONObject refund(String captureId) throws Exception{ - URL url = new URL(String.format(modeUrl+refundURL,captureId)); - HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); - httpConn.setRequestMethod("POST"); - httpConn.setRequestProperty("Content-Type", "application/json"); - httpConn.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token")); - httpConn.setRequestProperty("Prefer", "return=representation"); - httpConn.setDoOutput(true); - - InputStream responseStream = httpConn.getResponseCode() / 100 == 2 - ? httpConn.getInputStream() - : httpConn.getErrorStream(); - Scanner s = new Scanner(responseStream).useDelimiter("\\A"); - String response = s.hasNext() ? s.next() : ""; - log.info(">>>>>>>>>>>palypal退款返回的信息是 result = {}", response); - return JSONObject.parseObject(response); - } - - //订单查询 - public JSONObject orderInfo(String paypalOrderId) throws Exception{ - URL url = new URL(modeUrl+orderInfoURL+paypalOrderId); - HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); - httpConn.setRequestMethod("GET"); - httpConn.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token")); - - InputStream responseStream = httpConn.getResponseCode() / 100 == 2 - ? httpConn.getInputStream() - : httpConn.getErrorStream(); - Scanner s = new Scanner(responseStream).useDelimiter("\\A"); - String response = s.hasNext() ? s.next() : ""; - log.info(">>>>>>>>>>>palypal订单查询返回的信息是 result = {}", response); - return JSONObject.parseObject(response); - } - - //用户授权支付成功,进行扣款操作 - public JSONObject capture(String paypalOrderId){ - try { - URL url = new URL(String.format(modeUrl+captureURL,paypalOrderId)); - HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); - httpConn.setRequestMethod("POST"); - httpConn.setRequestProperty("Content-Type", "application/json"); - httpConn.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token")); - - InputStream responseStream = httpConn.getResponseCode() / 100 == 2 - ? httpConn.getInputStream() - : httpConn.getErrorStream(); - Scanner s = new Scanner(responseStream).useDelimiter("\\A"); - String response = s.hasNext() ? s.next() : ""; - log.info(">>>>>>>>>>>palypal扣款返回的信息是 result = {}", response); - return JSONObject.parseObject(response); - }catch (Exception e) { - log.error(">>>>>>>>>>:PayPal扣款失败 reason = {}", e.getMessage()); - e.printStackTrace(); - return JSONObject.parseObject("{'error':'PayPal扣款失败,请联系管理员'}"); - } - } - - //下单 - public JSONObject createOrder(BuyOrder buyOrder,String returnUrl,String cancelUrl){ - try{ - URL u = new URL(modeUrl+createOrderURL); - HttpURLConnection connection = (HttpURLConnection) u.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setRequestProperty("Authorization", "Bearer " + getAccessToken().get("access_token")); - connection.setDoOutput(true); - OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); - - JSONArray purchase_units = new JSONArray(); - JSONObject purchaseUnit = new JSONObject(); - JSONObject amount = new JSONObject(); - amount.put("currency_code", "USD");//美元 - amount.put("value", buyOrder.getOrderMoney().toString());// 金额 - purchaseUnit.put("custom_id",buyOrder.getOrderSn()); - purchaseUnit.put("invoice_id",buyOrder.getOrderSn()); - purchaseUnit.put("amount",amount); - purchaseUnit.put("description", buyOrder.getRemark()); - purchase_units.add(purchaseUnit); - JSONObject applicationContext = new JSONObject(); - applicationContext.put("user_action", "PAY_NOW");//付款按钮显示立即付款 - applicationContext.put("shipping_preference", "NO_SHIPPING");//从 PayPal 网站编辑送货地址。推荐用于数字商品。 - applicationContext.put("return_url", returnUrl);//客户批准付款后重定向到客户的 URL - applicationContext.put("cancel_url", cancelUrl);//客户取消付款后,客户被重定向的 URL - JSONObject jsonObject = new JSONObject(); - jsonObject.put("intent","CAPTURE");// 用户付款了,商户立即收款 - jsonObject.put("purchase_units",purchase_units); - jsonObject.put("application_context", applicationContext); - writer.write(jsonObject.toString()); - writer.flush(); - writer.close(); - connection.getOutputStream().close(); - InputStream responseStream = connection.getResponseCode() / 100 == 2 - ? connection.getInputStream() - : connection.getErrorStream(); - Scanner s = new Scanner(responseStream).useDelimiter("\\A"); - String response = s.hasNext() ? s.next() : ""; - log.info(">>>>>>>>>>>palypal下单返回的信息是 result = {}", response); - return JSONObject.parseObject(response); - }catch (Exception e) { - log.error(">>>>>>>>>>:PayPal创建订单网络连接失败 reason = {}", e.getMessage()); - e.printStackTrace(); - return JSONObject.parseObject("{'error':'PayPal创建订单网络连接失败,请联系管理员'}"); - } - } - - public JSONObject getAccessToken(){ - try { - String credentials = CLIENID + ":" + SECRET; - String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes()); - URL url = new URL(modeUrl+accessTokenURL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Authorization", "Basic " + encodedCredentials); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setDoOutput(true); - String postParameters = "grant_type=client_credentials"; - try (OutputStream os = connection.getOutputStream()) { - byte[] postParametersBytes = postParameters.getBytes(); - os.write(postParametersBytes); - os.flush(); - } - InputStream responseStream = connection.getResponseCode() / 100 == 2 - ? connection.getInputStream() - : connection.getErrorStream(); - Scanner s = new Scanner(responseStream).useDelimiter("\\A"); - String response = s.hasNext() ? s.next() : ""; - return JSONObject.parseObject(response); - }catch (Exception e) { - e.printStackTrace(); - } - return null; - } - -} diff --git a/src/main/java/com/peanut/modules/pay/paypal/controller/PaypalController.java b/src/main/java/com/peanut/modules/pay/paypal/controller/PaypalController.java deleted file mode 100644 index d7084b5d..00000000 --- a/src/main/java/com/peanut/modules/pay/paypal/controller/PaypalController.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.peanut.modules.pay.paypal.controller; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.peanut.common.utils.R; -import com.peanut.modules.book.service.*; -import com.peanut.modules.common.entity.*; -import com.peanut.modules.pay.paypal.config.PaypalConfig; -import com.peanut.modules.pay.paypal.service.PayPaypalOrderService; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.*; - -/** - * paypal支付 - */ -@RestController -@RequestMapping("/pay/paypal") -@Slf4j -public class PaypalController { - - @Autowired - private PaypalConfig paypalConfig; - @Autowired - private BuyOrderService buyOrderService; - @Autowired - private PayPaypalOrderService payPaypalOrderService; - @Autowired - private UserEbookBuyService userEbookBuyService; - @Autowired - private BookBuyConfigService bookBuyConfigService; - @Autowired - private MyUserService userService; - @Autowired - private TransactionDetailsService transactionDetailsService; - @Autowired - private PayPaymentOrderService payPaymentOrderService; - - @RequestMapping("/createOrder") - public R createOrder(@RequestBody Map params){ - BuyOrder buyOrder = buyOrderService.getOne(new LambdaQueryWrapper() - .eq(BuyOrder::getOrderSn,params.get("orderSn"))); - if ("3".equals(buyOrder.getOrderStatus())){ - return R.error("订单已完成"); - } - if ("point".equals(buyOrder.getOrderType())){ - buyOrder.setRemark("Recharge Virtual Coin"); - } - JSONObject res = paypalConfig.createOrder(buyOrder,params.get("returnUrl").toString(),params.get("cancelUrl").toString()); - if (res.containsKey("links")&&res.containsKey("status")){ - if ("CREATED".equals(res.get("status").toString())){ - PayPaypalOrder payPaypalOrder = new PayPaypalOrder(); - payPaypalOrder.setOrderId(buyOrder.getOrderId()); - payPaypalOrder.setOrderSn(buyOrder.getOrderSn()); - payPaypalOrder.setUserId(buyOrder.getUserId()); - payPaypalOrder.setPaypalOrderId(res.get("id").toString()); - payPaypalOrder.setDescription(buyOrder.getRemark()); - payPaypalOrderService.save(payPaypalOrder); - JSONArray array = (JSONArray)res.get("links"); - String url = ""; - for (int i = 0; i < array.size(); i++) { - JSONObject o = (JSONObject)array.get(i); - if ("approve".equals(o.get("rel"))){ - url = o.get("href").toString(); - } - } - - return R.ok().put("id",res.get("id").toString()).put("url",url); - } - } - return R.error(res.get("error").toString()); - } - - @RequestMapping("/orderInfo") - public R orderInfo(@RequestBody Map params) throws Exception{ - JSONObject res = paypalConfig.orderInfo(params.get("paypalId").toString()); - return R.ok().put("res",res); - } - - @RequestMapping("/capture") - @Transactional - public R capture(@RequestBody Map params){ - JSONObject res = paypalConfig.capture(params.get("paypalId").toString()); - if (res.containsKey("status")&&"COMPLETED".equals(res.get("status").toString())){ - PayPaypalOrder payPaypalOrder = payPaypalOrderService.getOne(new LambdaQueryWrapper() - .eq(PayPaypalOrder::getPaypalOrderId,params.get("paypalId").toString())); - JSONArray purchaseUnits = JSONArray.parseArray(res.get("purchase_units").toString()); - JSONObject purchaseUnit = (JSONObject)purchaseUnits.get(0); - JSONObject payments = JSONObject.parseObject(purchaseUnit.get("payments").toString()); - JSONArray captures = JSONArray.parseArray(payments.get("captures").toString()); - JSONObject capture = (JSONObject)captures.get(0); - if ("COMPLETED".equals(capture.get("status").toString())){ - //更新PayPal订单 - payPaypalOrder.setCaptureId(capture.get("id").toString()); - payPaypalOrder.setCaptureTime(new Date()); - payPaypalOrderService.updateById(payPaypalOrder); - BuyOrder buyOrder = buyOrderService.getById(payPaypalOrder.getOrderId()); - if ("abroadBook".equals(buyOrder.getOrderType())){ - userEbookBuyService.addBookForUser(buyOrder.getUserId(),Arrays.asList(buyOrder.getAbroadBookId())); - } - if ("point".equals(buyOrder.getOrderType())){ - BookBuyConfigEntity bookBuyConfigEntity = bookBuyConfigService.getById(buyOrder.getProductId()); - MyUserEntity userEntity = userService.getById(buyOrder.getUserId()); - String realMoney = bookBuyConfigEntity.getRealMoney(); - //更新账户余额 - userService.rechargeHSPoint(userEntity,Integer.valueOf(realMoney)); - //插入虚拟币消费记录 - transactionDetailsService.rechargeRecord(userEntity,realMoney,payPaypalOrder.getId(),"PayPal",buyOrder.getOrderSn()); - //插入花生币充值记录 - payPaymentOrderService.insertDetail(userEntity,bookBuyConfigEntity,payPaypalOrder.getId().toString()); - } - return R.ok(); - } - } - return R.error("执行扣款失败"); - } - - @RequestMapping("/refund") - public R refund(@RequestBody Map params) throws Exception{ - JSONObject res = paypalConfig.refund(params.get("captureId").toString()); - return R.ok().put("res",res); - } - - @RequestMapping("/refundInfo") - public R refundInfo(@RequestBody Map params) throws Exception{ - JSONObject res = paypalConfig.refundInfo(params.get("refundId").toString()); - return R.ok().put("res",res); - } - - @RequestMapping("/receivePaypalStatus") - public void receivePaypalStatus(HttpServletRequest request, HttpServletResponse response) throws Exception{ - //获取paypal请求参数,并拼接验证参数 - Enumeration en = request.getParameterNames(); - String str = "cmd=_notify-validate"; - while (en.hasMoreElements()) { - String paramName = en.nextElement(); - String paramValue = request.getParameter(paramName); - str = str + "&" + paramName + "=" + paramValue; - } - //发送给papal,确认回调信息的安全性 - String res = paypalConfig.receiveVerify(str); - if ("VERIFIED".equals(res)){ - log.info(">>>>>>>>>>>palypal回调校验通过,返回的信息是 result = {}", str); - String paymentStatus = request.getParameter("payment_status"); - //扣款id - String txnId = request.getParameter("txn_id"); - PayPaypalOrder payPaypalOrder = payPaypalOrderService.getOne(new LambdaQueryWrapper() - .eq(PayPaypalOrder::getCaptureId,txnId)); - payPaypalOrder.setPaymentStatus(request.getParameter("payment_status"));// 交易状态 Completed 代表交易成功 - payPaypalOrder.setPaymentDate(request.getParameter("payment_date"));// 交易时间 - payPaypalOrder.setPayerEmail(request.getParameter("payer_email"));// 付款人email - payPaypalOrder.setPayerId(request.getParameter("payer_id")); // 付款人id - payPaypalOrder.setMcGross(request.getParameter("mc_gross")); // 交易金额 - payPaypalOrder.setCallbackData(str); - payPaypalOrderService.updateById(payPaypalOrder); - BuyOrder buyOrder = buyOrderService.getById(payPaypalOrder.getOrderId()); - if (paymentStatus.equalsIgnoreCase("Completed")) {// 订单交易成功 - buyOrder.setOrderStatus("3"); - } else { - buyOrder.setOrderStatus("2"); - } - buyOrderService.updateById(buyOrder); - } - } - - -} diff --git a/src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderService.java b/src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderService.java deleted file mode 100644 index c7132d5b..00000000 --- a/src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderService.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.peanut.modules.pay.paypal.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.peanut.modules.common.entity.PayPaypalOrder; - -public interface PayPaypalOrderService extends IService { -} diff --git a/src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderServiceImpl.java b/src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderServiceImpl.java deleted file mode 100644 index bb9b2ec9..00000000 --- a/src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderServiceImpl.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.peanut.modules.pay.paypal.service; - -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.peanut.modules.common.dao.PayPaypalOrderDao; -import com.peanut.modules.common.entity.PayPaypalOrder; -import com.peanut.modules.pay.paypal.service.PayPaypalOrderService; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -@Slf4j -@Service("payPaypalOrderService") -public class PayPaypalOrderServiceImpl extends ServiceImpl implements PayPaypalOrderService { - -} - -