提交 32dcd1eb authored 作者: 吴德鹏's avatar 吴德鹏

paypal payment

上级 4a2f2a0c
......@@ -249,6 +249,26 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!--发邮件 END-->
</dependencies>
......
//package com.example.afrishop_v3.controllers;
//
//import com.diaoyun.zion.chinafrica.constant.KeyConstant;
//import com.diaoyun.zion.chinafrica.entity.TbCfOrderEntity;
//import com.diaoyun.zion.chinafrica.enums.OrderStatusEnum;
//import com.diaoyun.zion.chinafrica.service.PayPalService;
//import com.diaoyun.zion.chinafrica.service.TbCfOrderService;
//import com.diaoyun.zion.chinafrica.vo.TbCfOrderVo;
//import com.diaoyun.zion.master.base.Result;
//import com.diaoyun.zion.master.common.RedisCache;
//import com.diaoyun.zion.master.config.PaypalPaymentIntent;
//import com.diaoyun.zion.master.config.PaypalPaymentMethod;
//import com.diaoyun.zion.master.enums.ResultCodeEnum;
//import com.example.afrishop_v3.base.Result;
//import com.example.afrishop_v3.bo.KeyConstant;
//import com.example.afrishop_v3.config.PaypalPaymentIntent;
//import com.example.afrishop_v3.config.PaypalPaymentMethod;
//import com.example.afrishop_v3.enums.OrderStatusEnum;
//import com.example.afrishop_v3.enums.ResultCodeEnum;
//import com.example.afrishop_v3.models.TbCfOrder;
//import com.example.afrishop_v3.repository.TbCfOrderRepository;
//import com.paypal.api.payments.Links;
//import com.paypal.api.payments.Payment;
//import com.paypal.base.rest.APIContext;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.web.bind.annotation.*;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.math.BigDecimal;
//import java.util.Date;
//import java.util.Optional;
//
///**
// * @Auther: wudepeng
// * @Date: 2020/11/10
// * @Description:paypal支付
// */
//@RestController
//@RequestMapping(value = "/paypal")
//public class PaypalContoller {
//
// private static Logger logger = LoggerFactory.getLogger(PaypalContoller.class);
//
// @Value("${paypal.success_url}")
// private String PAYPAL_SUCCESS_URL;
//
// @Value("${paypal.cancel_url}")
// private String PAYPAL_CANCEL_URL;
//
// @Value("${paypal.success_page}")
// private String PAYPAL_SUCCESS_PAGE;
//
// @Value("${paypal.failed_page}")
// private String PAYPAL_FAILED_PAGE;
//
// @Autowired
// private APIContext apiContext;
//
// @Autowired
// private TbCfOrderRepository orderRepository;
//
// /**
// * 发起paypal支付
// *
// * @param orderId 订单号
// * @return Result
// */
// @PostMapping("/payment/{orderId}")
// public Result payment(@PathVariable("orderId") String orderId) {
// Result result = new Result();
// //==========================支付信息校验==========================
//
// //订单号
// if (StringUtils.isBlank(orderId)) {
// logger.error("paypal支付,订单Id不能为空");
// return payErrorInfo(result);
// }
//
//// //从缓存中获取订单信息
//// TbCfOrderVo orderCache = (TbCfOrderVo) orderRedisCache.get(KeyConstant.ORDER_DET + orderId);
////
//// if (orderCache == null) {
//// //订单已过期或者不存在
//// logger.error("paypal支付,订单不存在");
//// return payErrorInfo(result);
//// }
//
// //订单信息
// Optional<TbCfOrder> byId = orderRepository.findById(orderId);
// if (byId.isPresent()) {
// TbCfOrder order = byId.get();
// //价格不存在或错误
// if (order.getRealityPay() == null || order.getRealityPay().compareTo(BigDecimal.ZERO) <= 0) {
// logger.error("paypal支付,订单[" + order.getOrderNo() + "]价格错误");
// return payErrorInfo(result);
// }
//
//
// //订单已支付
// if (OrderStatusEnum.PAID.getValue().equals(order.getPayStatus().toString())) {
// logger.error("paypal支付,订单[" + order.getOrderNo() + "]已支付");
// return payErrorInfo(result);
// }
//
//
// //价格转double类型
// BigDecimal realityPay = order.getRealityPay();
// String price = realityPay.toString();
// double orderPrice = Double.parseDouble(price);
//
// //==========================paypal支付业务开始==========================
//
// logger.info("paypal支付开始,时间:" + new Date());
// String orderInfo = order.getDeliveryName() + "'s payment information";
// logger.info(orderInfo);
// String currency = "USD";
// try {
// Payment payment = payPalService.payment(
// orderId,
// orderPrice,
// currency,
// PaypalPaymentMethod.paypal,
// PaypalPaymentIntent.sale,
// orderInfo,
// PAYPAL_CANCEL_URL,
// PAYPAL_SUCCESS_URL);
//
// String paymentId = payment.getId();
// orderRedisCache.set(KeyConstant.ORDER_DET + "_" + paymentId, orderId);
// logger.info("paypal支付完成,时间:" + new Date());
// for (Links links : payment.getLinks()) {
// if (links.getRel().equals("approval_url")) {
// return result.setData(links.getHref());
// }
// }
// } catch (Exception e) {
// logger.info("paypal支付发生异常,时间:" + new Date() + e.getMessage());
// return payErrorInfo(result);
// }
// }
//
// return payErrorInfo(result);
// }
//
// /**
// * 支付失败提示
// *
// * @param result
// */
// public Result payErrorInfo(Result result) {
// result.setCode(ResultCodeEnum.ORDER_PAY_ERROR.getCode());
// result.setMessage(ResultCodeEnum.ORDER_PAY_ERROR.getDesc());
// return result;
// }
//}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.config.PaypalPaymentIntent;
import com.example.afrishop_v3.config.PaypalPaymentMethod;
import com.example.afrishop_v3.enums.DeliveryStatusEnum;
import com.example.afrishop_v3.enums.OrderStatusEnum;
import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.TbCfFinance;
import com.example.afrishop_v3.models.TbCfOrder;
import com.example.afrishop_v3.repository.TbCfFinanceRepository;
import com.example.afrishop_v3.repository.TbCfOrderRepository;
import com.example.afrishop_v3.util.IdUtil;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
/**
* @Auther: wudepeng
* @Date: 2020/11/27
* @Description:paypal支付
*/
@RestController
@RequestMapping(value = "/paypal")
public class PaypalContoller {
private static Logger logger = LoggerFactory.getLogger(PaypalContoller.class);
@Value("${paypal.success_url}")
private String PAYPAL_SUCCESS_URL;
@Value("${paypal.cancel_url}")
private String PAYPAL_CANCEL_URL;
@Value("${paypal.success_page}")
private String PAYPAL_SUCCESS_PAGE;
@Value("${paypal.failed_page}")
private String PAYPAL_FAILED_PAGE;
private final APIContext apiContext;
private final TbCfOrderRepository orderRepository;
private final TbCfFinanceRepository financeRepository;
public PaypalContoller(APIContext apiContext, TbCfOrderRepository orderRepository, TbCfFinanceRepository financeRepository) {
this.apiContext = apiContext;
this.orderRepository = orderRepository;
this.financeRepository = financeRepository;
}
/**
* 发起paypal支付
*
* @param orderId 订单号
* @return Result
*/
@PostMapping("/payment/{orderId}")
public Result payment(@PathVariable("orderId") String orderId) {
Result result = new Result();
//==========================支付信息校验==========================
//订单号
if (StringUtils.isBlank(orderId)) {
logger.error("paypal支付,订单Id不能为空");
return payErrorInfo(result);
}
//订单信息
Optional<TbCfOrder> byId = orderRepository.findById(orderId);
if (byId.isPresent()) {
TbCfOrder order = byId.get();
//订单不存在
if (order == null) {
logger.error("订单不存在");
return payErrorInfo(result);
}
//价格不存在或错误
if (order.getRealityPay() == null || order.getRealityPay().compareTo(BigDecimal.ZERO) <= 0) {
logger.error("paypal支付,订单[" + order.getOrderNo() + "]价格错误");
return payErrorInfo(result);
}
//订单已支付
if (OrderStatusEnum.PAID.getValue().equals(order.getPayStatus().toString())) {
logger.error("paypal支付,订单[" + order.getOrderNo() + "]已支付");
return payErrorInfo(result);
}
//==========================paypal支付业务开始==========================
logger.info("paypal支付开始,时间:" + getTime());
String orderInfo = order.getDeliveryName() + "'s payment information";
logger.info(orderInfo);
try {
Amount amount = new Amount();
amount.setCurrency("USD");
amount.setTotal(String.format("%.2f", order.getRealityPay()));
Transaction transaction = new Transaction();
transaction.setDescription(orderInfo);
transaction.setAmount(amount);
List<Transaction> transactions = new ArrayList<>();
transactions.add(transaction);
Payer payer = new Payer();
payer.setPaymentMethod(PaypalPaymentMethod.paypal.toString());
Payment payment = new Payment();
payment.setIntent(PaypalPaymentIntent.sale.toString());
payment.setPayer(payer);
payment.setTransactions(transactions);
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl(PAYPAL_CANCEL_URL);
redirectUrls.setReturnUrl(PAYPAL_SUCCESS_URL + "/" + orderId);
payment.setRedirectUrls(redirectUrls);
Payment pay = payment.create(apiContext);
logger.info("paypal支付完成,时间:" + getTime());
for (Links links : pay.getLinks()) {
if (links.getRel().equals("approval_url")) {
return result.setData(links.getHref());
}
}
} catch (Exception e) {
logger.info("paypal支付发生异常,时间:" + getTime() + e.getMessage());
return payErrorInfo(result);
}
}
return payErrorInfo(result);
}
/**
* 用户取消支付
*/
@GetMapping("/cancel")
public void paymentCancle(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect(PAYPAL_FAILED_PAGE);
}
/**
* 支付成功的回调方法
* <p>
* https://app.afrieshop.com/afrishop/paypal/success?
* paymentId=PAYID-L6XFFIA6TM43947C4571820W&
* token=EC-82206922L7926962C&
* PayerID=WBS8FAZYEQQXS
*/
@GetMapping("/success/{orderId}")
public void paymentSuccess(@PathVariable("orderId") String orderId, HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("paypal支付校验开始,时间:" + getTime());
String payerId = request.getParameter("PayerID");
//订单id
String paymentId = request.getParameter("paymentId");
String token = request.getParameter("token");
System.out.println("payerId" + payerId);
System.out.println("paymentId" + paymentId);
System.out.println("token" + token);
Payment payment = new Payment();
payment.setId(paymentId);
PaymentExecution paymentExecute = new PaymentExecution();
paymentExecute.setPayerId(payerId);
Payment paypal = payment.execute(apiContext, paymentExecute);
logger.info("支付信息:" + paypal);
logger.info("orderId:" + orderId);
Optional<TbCfOrder> byId = orderRepository.findById(orderId);
String payUrl = PAYPAL_SUCCESS_URL + "?paymentId=" + payerId + "&token=" + token + "&PayerID=" + payerId;
if (byId.isPresent()) {
TbCfOrder order = byId.get();
//paypal支付成功
if (paypal.getState().equals("approved")) {
logger.info("paypal支付,订单[" + order.getOrderNo() + "]支付成功");
//1)、修改订单状态
TbCfOrder tbCfOrder = changeOrderState(payerId, order);
//2)、生成支付流水
createFinance(paymentId, payUrl, order);
//数据库校验支付状态##PayStatus 20
if (OrderStatusEnum.PAID.getValue().equals(tbCfOrder.getPayStatus())) {
response.sendRedirect(PAYPAL_SUCCESS_PAGE);
}
}
}
}
/**
* 支付失败提示
*
* @param result
*/
public Result payErrorInfo(Result result) {
result.setCode(ResultCodeEnum.ORDER_PAY_ERROR.getCode());
result.setMessage(ResultCodeEnum.ORDER_PAY_ERROR.getDesc());
return result;
}
/**
* 修改订单状态
*/
private TbCfOrder changeOrderState(String transToken, TbCfOrder order) {
//更改订单状态
order.setUpdateTime(new Date());
order.setDealTime(new Date());
order.setPayId(transToken);
order.setOrderStatus(OrderStatusEnum.PAID.getValue());
order.setPayStatus(OrderStatusEnum.PAID.getValue());
order.setDeliveryFlag(DeliveryStatusEnum.PROCESSING.getValue());
return orderRepository.save(order);
}
private TbCfFinance createFinance(String paymentId, String url, TbCfOrder tbCfOrderVo) {
TbCfFinance tbCfFinance = new TbCfFinance();
tbCfFinance.setOrderId(tbCfOrderVo.getOrderId());
tbCfFinance.setFinaceId(IdUtil.createIdbyUUID());
tbCfFinance.setPayAccount(tbCfOrderVo.getRealityPay());
tbCfFinance.setPayId(paymentId);
tbCfFinance.setPayTime(new Date());
tbCfFinance.setReceiptUrl(url);
tbCfFinance.setPayWayCode("paypal");
tbCfFinance.setUserId(tbCfOrderVo.getUserId());
financeRepository.save(tbCfFinance);
return tbCfFinance;
}
public String getTime() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String now = format.format(new Date());
return now;
}
}
......@@ -66,7 +66,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**", "/search/image/**", "/itemStation/**", "/startPage/**",
"/goodsType/**", "/home/**", "/spider/**", "/store/**", "/shopify/**", "/community/**", "/version/**",
"/flutterwave/notify/**", "/dpo/notify/**", "/advertisement/**", "/website/**").permitAll()
"/flutterwave/notify/**", "/dpo/notify/**", "/advertisement/**", "/website/**","/paypal/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated();
......
//package com.example.afrishop_v3;
//
//import org.junit.jupiter.api.Test;
//import org.junit.runner.RunWith;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringRunner;
//
//import java.text.SimpleDateFormat;
//import java.time.LocalDateTime;
//import java.util.Date;
//
//@RunWith(SpringRunner.class)
//@SpringBootTest
//class AfrishopV3ApplicationTests {
//public class AfrishopV3ApplicationTests {
//
// @Test
// void contextLoads() {
//
//
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// String now = format.format(new Date());
// System.out.println(now);
// }
//
//}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论