From 86cecf3b6a205972d621e61eaaae2be1cfc81c8b Mon Sep 17 00:00:00 2001 From: wuchunlei Date: Wed, 4 Dec 2024 09:55:25 +0800 Subject: [PATCH] =?UTF-8?q?paypal=E8=AE=A2=E5=8D=95=E8=B0=83=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bookAbroad/controller/HomeController.java | 2 +- .../controller/OrderController.java | 34 +++- .../modules/common/dao/PayPaypalOrderDao.java | 10 + .../modules/common/entity/PayPaypalOrder.java | 52 +++++ .../modules/pay/paypal/PaypalController.java | 150 -------------- .../pay/paypal/{ => config}/PaypalConfig.java | 40 +++- .../paypal/controller/PaypalController.java | 191 ++++++++++++++++++ .../paypal/service/PayPaypalOrderService.java | 7 + .../service/PayPaypalOrderServiceImpl.java | 16 ++ 9 files changed, 338 insertions(+), 164 deletions(-) create mode 100644 src/main/java/com/peanut/modules/common/dao/PayPaypalOrderDao.java create mode 100644 src/main/java/com/peanut/modules/common/entity/PayPaypalOrder.java delete mode 100644 src/main/java/com/peanut/modules/pay/paypal/PaypalController.java rename src/main/java/com/peanut/modules/pay/paypal/{ => config}/PaypalConfig.java (79%) create mode 100644 src/main/java/com/peanut/modules/pay/paypal/controller/PaypalController.java create mode 100644 src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderService.java create mode 100644 src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderServiceImpl.java diff --git a/src/main/java/com/peanut/modules/bookAbroad/controller/HomeController.java b/src/main/java/com/peanut/modules/bookAbroad/controller/HomeController.java index af3b4c5f..5e02c919 100644 --- a/src/main/java/com/peanut/modules/bookAbroad/controller/HomeController.java +++ b/src/main/java/com/peanut/modules/bookAbroad/controller/HomeController.java @@ -79,7 +79,7 @@ public class HomeController { List noBooks = bookService.list(new LambdaQueryWrapper() .eq(BookEntity::getState,1) .eq(BookEntity::getBookType,0) - .notIn(BookEntity::getId,bookIds) + .notIn(BookEntity::getId,bookIds.size()==0?0:bookIds) .last("limit 2")); Set books = new HashSet<>(); //查询阅读进度 diff --git a/src/main/java/com/peanut/modules/bookAbroad/controller/OrderController.java b/src/main/java/com/peanut/modules/bookAbroad/controller/OrderController.java index 4f4ce813..827d1ff6 100644 --- a/src/main/java/com/peanut/modules/bookAbroad/controller/OrderController.java +++ b/src/main/java/com/peanut/modules/bookAbroad/controller/OrderController.java @@ -1,10 +1,15 @@ package com.peanut.modules.bookAbroad.controller; import com.baomidou.mybatisplus.core.toolkit.IdWorker; +import com.github.promeg.pinyinhelper.Pinyin; import com.peanut.common.utils.R; +import com.peanut.common.utils.ShiroUtils; +import com.peanut.config.Constants; import com.peanut.config.DelayQueueConfig; import com.peanut.modules.book.service.BuyOrderService; +import com.peanut.modules.common.entity.BookEntity; import com.peanut.modules.common.entity.BuyOrder; +import com.peanut.modules.common.service.BookService; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.MessagePostProcessor; import org.springframework.amqp.rabbit.core.RabbitTemplate; @@ -13,35 +18,50 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.math.BigDecimal; + @Slf4j @RestController("bookAbroadOrder") @RequestMapping("bookAbroad/order") public class OrderController { + @Autowired + private BookService bookService; @Autowired private BuyOrderService buyOrderService; @Autowired private RabbitTemplate rabbitTemplate; - /** - * 充值专用订单生成接口 - */ - @RequestMapping("/rechargeSave") - public R rechargeSave(@RequestBody BuyOrder buyOrder){ + @RequestMapping("/placeOrder") + public R createOrder(@RequestBody BuyOrder buyOrder){ + buyOrder.setUserId(ShiroUtils.getUId()); + buyOrder.setCome(3);//3 海外读书 + buyOrder.setPaymentMethod("5"); //5 paypal + BookEntity bookEntity = bookService.getById(buyOrder.getAbroadBookId()); + BigDecimal orderMoney = buyOrder.getOrderMoney(); + //校验价格 + if (orderMoney.compareTo(bookEntity.getAbroadPrice())!=0){ + return R.error("订单价格异常"); + } + buyOrder.setRealMoney(orderMoney); + buyOrder.setRemark("Purchase the e-book '"+ Pinyin.toPinyin(bookEntity.getName(), " ").toLowerCase()+"'"); buyOrder.setOrderStatus("0"); buyOrder.setOrderType("abroadBook"); String timeId = IdWorker.getTimeId().substring(0, 32); buyOrder.setOrderSn(timeId); buyOrderService.save(buyOrder); + // 1. 虚拟币支付 + if (Constants.PAYMENT_METHOD_VIRTUAL.equals(buyOrder.getPaymentMethod())) { + + } rabbitTemplate.convertAndSend( DelayQueueConfig.ORDER_TO_BE_PAY_EXCHANGE, DelayQueueConfig.ORDER_TO_BE_PAY_ROUTING_KEY, buyOrder.getOrderId(), messagePostProcessor() ); - return R.ok().put("orderSn", timeId); + return R.ok(); } - private MessagePostProcessor messagePostProcessor() { return message -> { //设置有效期30分钟 diff --git a/src/main/java/com/peanut/modules/common/dao/PayPaypalOrderDao.java b/src/main/java/com/peanut/modules/common/dao/PayPaypalOrderDao.java new file mode 100644 index 00000000..c6c4c17b --- /dev/null +++ b/src/main/java/com/peanut/modules/common/dao/PayPaypalOrderDao.java @@ -0,0 +1,10 @@ +package com.peanut.modules.common.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.peanut.modules.common.entity.PayPaypalOrder; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface PayPaypalOrderDao extends BaseMapper { + +} diff --git a/src/main/java/com/peanut/modules/common/entity/PayPaypalOrder.java b/src/main/java/com/peanut/modules/common/entity/PayPaypalOrder.java new file mode 100644 index 00000000..ca2c911b --- /dev/null +++ b/src/main/java/com/peanut/modules/common/entity/PayPaypalOrder.java @@ -0,0 +1,52 @@ +package com.peanut.modules.common.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +//paypal支付实体 +@Data +@TableName("pay_paypal_order") +public class PayPaypalOrder implements Serializable { + private static final long serialVersionUID = 1L; + + @TableId + private Long id; + //用户Id + private Integer userId; + //订单Id + private Integer orderId; + //订单编号 + private String orderSn; + //PayPal订单ID + private String paypalOrderId; + //PayPal订单ID + private String description; + //创建订单时间 + private Date createTime; + //执行扣款id + private String captureId; + //执行扣款时间 + private Date captureTime; + //支付回调状态 + private String paymentStatus; + //支付回调时间 + private String paymentDate; + //paypal支付人邮箱 + private String payerEmail; + //paypal支付人id + private String payerId; + //交易金额 + private String mcGross; + //支付回调数据 + private String callbackData; + + + + + + +} diff --git a/src/main/java/com/peanut/modules/pay/paypal/PaypalController.java b/src/main/java/com/peanut/modules/pay/paypal/PaypalController.java deleted file mode 100644 index 9402feac..00000000 --- a/src/main/java/com/peanut/modules/pay/paypal/PaypalController.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.peanut.modules.pay.paypal; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.peanut.common.utils.R; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -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.net.URLEncoder; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * paypal支付 - */ -@RestController -@RequestMapping("/pay/paypal") -@Slf4j -public class PaypalController { - //点击购买 ->去支付 ->跳转完成、取消页面 - // ->创建订单 ->(支付完成)确认付款,打款到商家账户 ->支付成功 - - @Autowired - private PaypalConfig paypalConfig; - - @RequestMapping("/getAccessToken") - public R getAccessToken(){ - JSONObject res = paypalConfig.getAccessToken(); - return R.ok().put("res",res); - } - - @RequestMapping("/createOrder") - public R createOrder(@RequestBody Map params){ - JSONArray purchase_units = new JSONArray(); - JSONObject purchaseUnit = new JSONObject(); - JSONObject amount = new JSONObject(); - amount.put("currency_code", "USD");//美元 - amount.put("value", params.get("amount"));// 金额 - purchaseUnit.put("custom_id",params.get("orderSn")); - purchaseUnit.put("invoice_id",params.get("orderSn")); - purchaseUnit.put("amount",amount); - purchaseUnit.put("description", params.get("description")); - 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", params.get("returnUrl"));//客户批准付款后重定向到客户的 URL - applicationContext.put("cancel_url", params.get("cancelUrl"));//客户取消付款后,客户被重定向的 URL - JSONObject jsonObject = new JSONObject(); - // 用户付款了,商户立即收款 - jsonObject.put("intent","CAPTURE"); - jsonObject.put("purchase_units",purchase_units); - jsonObject.put("application_context", applicationContext); - JSONObject res = paypalConfig.createOrder(jsonObject); - if (res.containsKey("links")&&res.containsKey("status")){ - if ("CREATED".equals(res.get("status").toString())){ - List links = (List)res.get("links"); - for (JSONObject o:links) { - if ("approve".equals(o.get("rel").toString())){ - return R.ok().put("res",o.get("href").toString()); - } - } - } - } - 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") - public R capture(@RequestBody Map params) throws Exception{ - JSONObject res = paypalConfig.capture(params.get("paypalId").toString()); - return R.ok().put("res",res); - } - - @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; - } - System.out.println(str); - //发送给papal,确认回调信息的安全性 - String res = paypalConfig.receiveVerify(str); - if ("VERIFIED".equals(res)){ - // 交易状态 Completed 代表交易成功 - String paymentStatus = request.getParameter("payment_status"); - // 交易时间 - String paymentDate = request.getParameter("payment_date"); - // 付款人email - String payerEmail = request.getParameter("payer_email"); - // 付款人id - String payerId = request.getParameter("payer_id"); - // 交易金额 - String mcGross = request.getParameter("mc_gross"); - // 手续费 - String paymentFee = request.getParameter("payment_fee"); - // 自定义字段,存放订单号 - String custom = request.getParameter("custom"); - - } - } - - @RequestMapping("/receiveVerify") - public R receiveVerify(@RequestBody Map params) throws Exception{ - String res = params.get("verifyData").toString(); - Map map = new HashMap<>(); - String[] items = res.split("&"); - for (String item : items) { - String[] keyValues = item.split("="); - if (keyValues.length>1){ - map.put(keyValues[0],keyValues[1]); - }else { - map.put(keyValues[0],""); - } - } - - return R.ok().put("res",map); - } - - -} diff --git a/src/main/java/com/peanut/modules/pay/paypal/PaypalConfig.java b/src/main/java/com/peanut/modules/pay/paypal/config/PaypalConfig.java similarity index 79% rename from src/main/java/com/peanut/modules/pay/paypal/PaypalConfig.java rename to src/main/java/com/peanut/modules/pay/paypal/config/PaypalConfig.java index fc157040..b1d86248 100644 --- a/src/main/java/com/peanut/modules/pay/paypal/PaypalConfig.java +++ b/src/main/java/com/peanut/modules/pay/paypal/config/PaypalConfig.java @@ -1,7 +1,8 @@ -package com.peanut.modules.pay.paypal; +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; @@ -19,6 +20,11 @@ public class PaypalConfig { 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"; @@ -53,7 +59,7 @@ public class PaypalConfig { : connection.getErrorStream(); Scanner s = new Scanner(responseStream).useDelimiter("\\A"); String response = s.hasNext() ? s.next() : ""; - System.out.println(response); + log.info(">>>>>>>>>>>palypal回调验证返回的信息是 result = {}", response); return response; } @@ -70,7 +76,7 @@ public class PaypalConfig { : httpConn.getErrorStream(); Scanner s = new Scanner(responseStream).useDelimiter("\\A"); String response = s.hasNext() ? s.next() : ""; - System.out.println(response); + log.info(">>>>>>>>>>>palypal退款查询返回的信息是 result = {}", response); return JSONObject.parseObject(response); } @@ -89,7 +95,7 @@ public class PaypalConfig { : httpConn.getErrorStream(); Scanner s = new Scanner(responseStream).useDelimiter("\\A"); String response = s.hasNext() ? s.next() : ""; - System.out.println(response); + log.info(">>>>>>>>>>>palypal退款返回的信息是 result = {}", response); return JSONObject.parseObject(response); } @@ -105,7 +111,7 @@ public class PaypalConfig { : httpConn.getErrorStream(); Scanner s = new Scanner(responseStream).useDelimiter("\\A"); String response = s.hasNext() ? s.next() : ""; - System.out.println(response); + log.info(">>>>>>>>>>>palypal订单查询返回的信息是 result = {}", response); return JSONObject.parseObject(response); } @@ -122,11 +128,12 @@ public class PaypalConfig { : 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 createOrder(JSONObject jsonObject){ + public JSONObject createOrder(BuyOrder buyOrder){ try{ URL u = new URL(modeUrl+createOrderURL); HttpURLConnection connection = (HttpURLConnection) u.openConnection(); @@ -135,6 +142,26 @@ public class PaypalConfig { 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", "");//客户批准付款后重定向到客户的 URL + applicationContext.put("cancel_url", "");//客户取消付款后,客户被重定向的 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(); @@ -144,6 +171,7 @@ public class PaypalConfig { : 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()); 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 new file mode 100644 index 00000000..0491dea8 --- /dev/null +++ b/src/main/java/com/peanut/modules/pay/paypal/controller/PaypalController.java @@ -0,0 +1,191 @@ +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.baomidou.mybatisplus.core.toolkit.IdWorker; +import com.github.promeg.pinyinhelper.Pinyin; +import com.peanut.common.utils.R; +import com.peanut.common.utils.ShiroUtils; +import com.peanut.config.DelayQueueConfig; +import com.peanut.modules.book.service.BuyOrderService; +import com.peanut.modules.book.service.UserEbookBuyService; +import com.peanut.modules.common.entity.BookEntity; +import com.peanut.modules.common.entity.BuyOrder; +import com.peanut.modules.common.entity.PayPaypalOrder; +import com.peanut.modules.common.service.BookService; +import com.peanut.modules.pay.paypal.config.PaypalConfig; +import com.peanut.modules.pay.paypal.service.PayPaypalOrderService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.core.MessagePostProcessor; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +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.math.BigDecimal; +import java.util.*; + +/** + * paypal支付 + */ +@RestController +@RequestMapping("/pay/paypal") +@Slf4j +public class PaypalController { + + @Autowired + private BookService bookService; + @Autowired + private PaypalConfig paypalConfig; + @Autowired + private BuyOrderService buyOrderService; + @Autowired + private PayPaypalOrderService payPaypalOrderService; + @Autowired + private RabbitTemplate rabbitTemplate; + @Autowired + private UserEbookBuyService userEbookBuyService; + + @RequestMapping("/createOrder") + @Transactional + public R createOrder(@RequestBody Map params){ + BuyOrder buyOrder = new BuyOrder(); + buyOrder.setUserId(ShiroUtils.getUId()); + buyOrder.setCome(3);//3 海外读书 + buyOrder.setPaymentMethod("5"); //5 paypal + int bookId = Integer.parseInt(params.get("abroadBookId").toString()); + BookEntity bookEntity = bookService.getById(bookId); + BigDecimal orderMoney = new BigDecimal(params.get("orderMoney").toString()); + //校验价格 + if (orderMoney.compareTo(bookEntity.getAbroadPrice())!=0){ + return R.error("订单价格异常"); + } + buyOrder.setOrderMoney(orderMoney); + buyOrder.setRealMoney(orderMoney); + buyOrder.setRemark("Purchase the e-book '"+ Pinyin.toPinyin(bookEntity.getName(), " ").toLowerCase()+"'"); + buyOrder.setOrderStatus("0"); + buyOrder.setOrderType("abroadBook"); + buyOrder.setAbroadBookId(bookId); + String timeId = IdWorker.getTimeId().substring(0, 32); + buyOrder.setOrderSn(timeId); + JSONObject res = paypalConfig.createOrder(buyOrder); + if (res.containsKey("links")&&res.containsKey("status")){ + if ("CREATED".equals(res.get("status").toString())){ + buyOrderService.save(buyOrder); + String url = ""; + List links = (List)res.get("links"); + for (JSONObject o:links) { + if ("approve".equals(o.get("rel").toString())){ + url = o.get("href").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); + rabbitTemplate.convertAndSend( + DelayQueueConfig.ORDER_TO_BE_PAY_EXCHANGE, + DelayQueueConfig.ORDER_TO_BE_PAY_ROUTING_KEY, + buyOrder.getOrderId(), + messagePostProcessor() + ); + return R.ok().put("url",url).put("id",res.get("id").toString()); + } + } + return R.error(res.get("error").toString()); + } + private MessagePostProcessor messagePostProcessor() { + return message -> { + //设置有效期30分钟 + message.getMessageProperties().setExpiration(String.valueOf(30 * 60 * 1000)); + return message; + }; + } + + @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") + public R capture(@RequestBody Map params) throws Exception{ + 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())){ + payPaypalOrder.setCaptureId(capture.get("id").toString()); + payPaypalOrder.setCaptureTime(new Date()); + payPaypalOrderService.updateById(payPaypalOrder); + BuyOrder buyOrder = buyOrderService.getById(payPaypalOrder.getOrderId()); + userEbookBuyService.addBookForUser(buyOrder.getUserId(),Arrays.asList(buyOrder.getAbroadBookId())); + 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 new file mode 100644 index 00000000..c7132d5b --- /dev/null +++ b/src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderService.java @@ -0,0 +1,7 @@ +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 new file mode 100644 index 00000000..bb9b2ec9 --- /dev/null +++ b/src/main/java/com/peanut/modules/pay/paypal/service/PayPaypalOrderServiceImpl.java @@ -0,0 +1,16 @@ +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 { + +} + +