基于springboot的paypal支付demo

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” 跳转到如下界面,点击右上角的注册
在这里插入图片描述
在这里插入图片描述
根据要求填写信息,注册完得去邮箱激活
2.在浏览器输入“https://developer.paypal.com”,点击右上角的“Log into Dashboard”,用上一步创建好的账号登录
登录完成后,系统会默认给你配置2个测试账号,我们不使用它:
在这里插入图片描述
3.我们开始创建沙箱测试账号:
在这里插入图片描述
如上图所示,我们开始创建:

在这里插入图片描述
账号创建一个个人, 一个商家,完成后列表中将会显示你新建的账号。右键能看到账号的一些信息;

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

5.我们创建一个自己的APP:
在这里插入图片描述
如上图所示,我们创建一个自己的APP,然后,选择刚刚创建的商户即可,
然后返回点击我们创建的APP,会看到需要在代码中配置的商家信息(clientId,clientSecret)

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

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 是一款基于 Spring 框架的开源应用程序框架,它旨在简化和加速Java应用程序的开发和部署。PayPal 则是一家全球领先的在线支付解决方案提供商。两者结合在一起,意味着我们可以使用 Spring Boot 来集成 PayPal支付功能。 通过 Spring Boot 和 PayPal 的集成,我们可以轻松地向我们的应用程序添加支付功能。我们可以使用 PayPal 的 API 来创建付款,接收付款以及管理退款。通过集成 PayPal,我们可以为用户提供一种方便,安全和可靠的在线支付方式。 在实现这个集成过程中,需要引入 PayPalJava SDK,它提供了与 PayPal 平台进行通信的各种方法和功能。可以使用 Maven 或 Gradle 管理工具来添加相应的依赖项。然后,我们可以在 Spring Boot 应用程序中使用这些 SDK 提供的 API 来实现支付功能。 在开发过程中,我们需要配置 PayPal 的 API 密钥和其他相关参数,以便与 PayPal 平台进行通信。这些配置可以在应用程序的配置文件中设置,以便在运行时动态加载。 一旦集成完成,我们就可以通过调用相应的 API 来处理付款请求和响应。例如,我们可以创建一个付款订单,设置收款人和订单金额,然后使用 PayPal 的 API 请求来提交付款。成功的付款将触发回调通知,我们可以使用这些通知来更新订单状态或进行其他后续操作。 总而言之,Spring Boot 和 PayPal 的集成为我们提供了一个简单和方便的方式来实现在线支付功能。它使我们能够更快速地构建和部署应用程序,并为用户提供安全可靠的支付体验。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值