当前位置: 首页>后端>正文

springboot 接入银行卡支付 spring boot pay

paypal是什么,可以百度下,就像国内支付宝一样,这玩意是全球最大的线上支付,做全球性支付一般都会用到。废话不多说,开始demo:

1.首先引入依赖(目前最新版本):

<dependency>
    <groupId>com.paypal.sdk</groupId>
    <artifactId>rest-api-sdk</artifactId>
    <version>1.14.0</version>
</dependency>

2.PayPal配置类:

import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * PayPal配置类,注入需要的认证信息
 *
 * @author Tom
 * @date 2021-06-28
 */
@Configuration
public class PaypalConfig {

    @Value("${paypal.client.app}")
    private String clientId;

    @Value("${paypal.client.secret}")
    private String clientSecret;

    @Value("${paypal.mode}")
    private String mode;

    /**
     * 注入APIContext,APP的认证信息clientId,Secret,开发者账号创建APP时提供
     * 每次调用时都需要创建一次
     * @return
     * @throws PayPalRESTException
     */
    @Bean
    public APIContext apiContext() throws PayPalRESTException {
        APIContext apiContext = new APIContext(clientId,clientSecret,mode);
        return apiContext;
    }

}

3.交易时参数枚举:

/**
 * 交易时参数枚举-意图
 *
 * @author Tom
 * @date 2021-06-28
 */
public enum PaypalPaymentIntent {
    sale,authorize,order
}
/**
 * 交易时参数枚举-作用
 *
 * @author Tom
 * @date 2021-06-28
 */
public enum PaypalPaymentMethod {
    credit_card, paypal
}

4.PayPal支付-controller:

import com.example.paypallesson01.config.PaypalPaymentIntent;
import com.example.paypallesson01.config.PaypalPaymentMethod;
import com.example.paypallesson01.service.PaypalService;
import com.example.paypallesson01.utils.URLUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;


/**
 * PayPal支付-controller
 *
 * @author Tom
 * @date 2021-06-28
 */
@Controller
@RequestMapping("/")
public class PaymentController {

    private Logger log = LoggerFactory.getLogger(getClass());

    public static final String PAYPAL_SUCCESS_URL = "pay/success";
    public static final String PAYPAL_CANCEL_URL = "pay/cancel";

    @Autowired
    private PaypalService paypalService;

    /**
     * 进入项目跳转
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String index(){
        return "index";
    }

    /**
     * 开始交易
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "pay")
    public String pay(HttpServletRequest request){
        String cancelUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_CANCEL_URL;
        String successUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_SUCCESS_URL;
        try {
            //调用交易方法
            Payment payment = paypalService.createPayment(
                    500.00,
                    "USD",
                    PaypalPaymentMethod.paypal,
                    PaypalPaymentIntent.sale,
                    "payment description",
                    cancelUrl,
                    successUrl);
            //交易成功后,跳转反馈地址
            for(Links links : payment.getLinks()){
                if(links.getRel().equals("approval_url")){
                    return "redirect:" + links.getHref();
                }
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
        }
        return "redirect:/";
    }

    /**
     * 交易取消
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = PAYPAL_CANCEL_URL)
    public String cancelPay(){
        return "cancel";
    }

    /**
     * 交易成功,并执行交易(相当于提交事务)
     * @param paymentId
     * @param payerId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = PAYPAL_SUCCESS_URL)
    public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId){
        try {
            Payment payment = paypalService.executePayment(paymentId, payerId);
            if(payment.getState().equals("approved")){
                return "success";
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
        }
        return "redirect:/";
    }

}

5.PayPal支付service类:

import com.example.paypallesson01.config.PaypalPaymentIntent;
import com.example.paypallesson01.config.PaypalPaymentMethod;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * PayPal支付service类
 *
 * @author Tom
 * @date 2021-06-28
 */
@Service
public class PaypalService {

    //注入认证信息bean
    @Autowired
    private APIContext apiContext;

    /**
     * 支付方法
     * @param total 交易金额
     * @param currency 货币类型
     * @param method 枚举-作用
     * @param intent 枚举-意图
     * @param description 交易描述
     * @param cancelUrl 交易取消后跳转url
     * @param successUrl 交易成功后跳转url
     * @return
     * @throws PayPalRESTException
     */
    public Payment createPayment(
            Double total,
            String currency,
            PaypalPaymentMethod method,
            PaypalPaymentIntent intent,
            String description,
            String cancelUrl,
            String successUrl) throws PayPalRESTException {
        //设置金额和单位对象
        Amount amount = new Amount();
        amount.setCurrency(currency);
        amount.setTotal(String.format("%.2f", total));
        //设置具体的交易对象
        Transaction transaction = new Transaction();
        transaction.setDescription(description);
        transaction.setAmount(amount);
        //交易集合-可以添加多个交易对象
        List<Transaction> transactions = new ArrayList<Transaction>();
        transactions.add(transaction);

        Payer payer = new Payer();
        payer.setPaymentMethod(method.toString());

        Payment payment = new Payment();
        payment.setIntent(intent.toString());
        payment.setPayer(payer);
        payment.setTransactions(transactions);
        //设置反馈url
        RedirectUrls redirectUrls = new RedirectUrls();
        redirectUrls.setCancelUrl(cancelUrl);
        redirectUrls.setReturnUrl(successUrl);
        //加入反馈对象
        payment.setRedirectUrls(redirectUrls);
        //加入认证并创建交易
        return payment.create(apiContext);

    }

    /**
     * 执行支付的方法(相当于提交事务)
     * @param paymentId 支付ID
     * @param payerId 支付人ID
     */
    public Payment executePayment(String paymentId, String payerId) throws PayPalRESTException{
        Payment payment = new Payment();
        payment.setId(paymentId);
        PaymentExecution paymentExecute = new PaymentExecution();
        paymentExecute.setPayerId(payerId);
        return payment.execute(apiContext, paymentExecute);
    }

}

6.获取请求url的util:

import javax.servlet.http.HttpServletRequest;

/**
 * 获取请求url的util
 *
 * @author Tom
 * @date 2021-06-28
 */
public class URLUtils {
    public static String getBaseURl(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();
        StringBuffer url =  new StringBuffer();
        url.append(scheme).append("://").append(serverName);
        if ((serverPort != 80) && (serverPort != 443)) {
            url.append(":").append(serverPort);
        }
        url.append(contextPath);
        if(url.toString().endsWith("/")){
            url.append("/");
        }
        return url.toString();
    }
}

7.springboot启动类:略

8.application.properties

server.port=8088
spring.thymeleaf.cache=false

paypal.mode=sandbox
paypal.client.app=AZUMue4yTWdVC6eEtGkFeW1ieiSdtMtvwIdfpt4_eSUAhSgZjHhqUGrCylhvdeRxa2XjSF48QwAHZ2mm
paypal.client.secret=EN97KXuVEQgixqw3zATODs37-xjVtdfSLV91Ar-84hm4IiHtTYfkcyIrpBw40FJOi9qiZZZeOY_bJTij

9.给出前端三个页面:

启动项目后:http://localhost:8088/的跳转页

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" th:action="@{/pay}">
    <button type="submit"><img src="http://***********.com/feed_back/1624860034048_e5af86fa.jpg" width="100px;" height="30px;"/></button>
</form>

</body>
</html>

支付成功后的回调页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Payment Success</h1>
</body>
</html>

取消支付后的跳转页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Canceled by user</h1>
</body>
</html>

以上为代码demo;

以下关于paypal的账号:

1.注册paypal账号

在浏览器输入“https://www.paypal.com” 跳转到如下界面,点击右上角的注册

springboot 接入银行卡支付 spring boot pay,springboot 接入银行卡支付 spring boot pay_html,第1张

springboot 接入银行卡支付 spring boot pay,springboot 接入银行卡支付 spring boot pay_java_02,第2张

根据要求填写信息,注册完得去邮箱激活

2.在浏览器输入“https://developer.paypal.com”,点击右上角的“Log into Dashboard”,用上一步创建好的账号登录

登录完成后,系统会默认给你配置2个测试账号,我们不使用它:

springboot 接入银行卡支付 spring boot pay,springboot 接入银行卡支付 spring boot pay_html_03,第3张

3.我们开始创建沙箱测试账号:

springboot 接入银行卡支付 spring boot pay,springboot 接入银行卡支付 spring boot pay_spring_04,第4张

如上图所示,我们开始创建:

springboot 接入银行卡支付 spring boot pay,springboot 接入银行卡支付 spring boot pay_html_05,第5张

账号创建一个个人, 一个商家,完成后列表中将会显示你新建的账号。右键能看到账号的一些信息;

4.用测试账号登录测试网站查看,注意!这跟paypal官网不同!不是同一个地址,在浏览器输入:https://www.sandbox.paypal.com 在这里登陆测试账户

5.我们创建一个自己的APP:

springboot 接入银行卡支付 spring boot pay,springboot 接入银行卡支付 spring boot pay_spring_06,第6张

如上图所示,我们创建一个自己的APP,然后,选择刚刚创建的商户即可,

然后返回点击我们创建的APP,会看到需要在代码中配置的商家信息(clientId,clientSecret)

总结:paypal的代码其实没有多少难度,主要是paypal有三个地址:
1.线上账号注册登录地址:https://www.paypal.com
2.开发者账号登录地址:https://developer.paypal.com
3.沙箱测试账号登录地址:https://www.sandbox.paypal.com



https://www.xamrdz.com/backend/3kn1923991.html

相关文章: