欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java对接PayPal进行付款

程序员文章站 2022-04-21 15:25:41
大家好,我是傻明蚕豆,今天为大家带来的是PayPal付款的一个栗子。首先打开地址:https://developer.paypal.com/,自己注册一个账号,登录后页面如下:按照上图所示,在沙箱里面创建两个帐号,一个商家,一个买家,参数自己设置,使用默认的帐号也可以。接着按照下图所示,创建一个沙箱app。点击该app,即可获取到Client ID和Secret,如下图所示:到这里准备工作就完成了,下面开始Java和PayPal对接,完成一个完整的付款流程。首先当然是创建一个sprin....

大家好,我是傻明蚕豆,今天为大家带来的是PayPal付款的一个栗子。

首先打开地址:https://developer.paypal.com/,自己注册一个账号,登录后页面如下:
Java对接PayPal进行付款
按照上图所示,在沙箱里面创建两个帐号,一个商家,一个买家,参数自己设置,使用默认的帐号也可以。

接着按照下图所示,创建一个沙箱app。
Java对接PayPal进行付款
点击该app,即可获取到Client ID和Secret,如下图所示:
Java对接PayPal进行付款
到这里准备工作就完成了,下面开始Java和PayPal对接,完成一个完整的付款流程。

首先当然是创建一个springboot项目,然后引入PayPal的依赖:

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

然后配置application.properties

paypal.mode=sandbox #沙箱环境
paypal.client.app=这里是Client ID
paypal.client.secret=这里是Secret

接着创建页面index.html

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<form method="post" action="/paypal/pay">
    <button type="submit">我要支付</button>
</form>
</body>
</html>

支付成功后跳转的页面success.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h1>支付成功了</h1>
</body>
</html>

支付取消跳转页面cancel.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h1>支付取消鸟!!!</h1>
</body>
</html>

开始写接口:

import com.paypal.api.payments.*;
import com.paypal.base.rest.PayPalRESTException;
import com.sillyming.test.service.PaypalService;
import com.sillyming.test.utils.URLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/paypal")
public class PayPalController {

    public static final String SUCCESS_URL = "pay/success";
    public static final String CANCEL_URL = "pay/cancel";

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

    @Autowired
    private PaypalService paypalService;

    @RequestMapping(method = RequestMethod.GET ,value = "/index")
    public String index(){
        return "paypal/index";
    }

    @RequestMapping(method = RequestMethod.POST, value = "pay")
    public String pay(HttpServletRequest request){
        //定义支付成功和取消支付跳转url
        String cancelUrl = URLUtils.getBaseURl(request) + "/paypal/" + CANCEL_URL;
        String successUrl = URLUtils.getBaseURl(request) + "/paypal/" + SUCCESS_URL;
        String invoiceNumber="123456abc";//自定义一个账单号
        try {
            Payment payment = paypalService.createPayment(
                    "100.01",//支付金额
                    "USD",//金额的币种
                    "订单描述",
                    cancelUrl,
                    successUrl,invoiceNumber);
            System.out.println("payment id:"+payment.getId());
            System.out.println("payment state:"+payment.getState());
            System.out.println("payment invoiceNumber:"+payment.getTransactions().get(0).getInvoiceNumber());
            //这里成功返回payment对象,表示PayPal那边已经成功创建订单。
            for(Links links : payment.getLinks()){
                if(links.getRel().equals("approval_url")){
                    System.out.println("create payment success");
                    return "redirect:" + links.getHref();//把买家重定向到支付页面
                }
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
        }
        return "redirect:/";
    }

    @RequestMapping(method = RequestMethod.GET, value = CANCEL_URL)
    public String cancelPayment(){
        return "paypal/cancel";
    }

    @RequestMapping(method = RequestMethod.GET, value = SUCCESS_URL)
    public String successPayment(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId){
        try {
            System.out.println("start execute payment.");
            Payment payment = paypalService.executePayment(paymentId, payerId);//买家授权支付
            System.out.println("payment id:"+payment.getId());
            System.out.println("payment state:"+payment.getState());
            // 订单总价
            String total = payment.getTransactions().get(0).getAmount().getTotal();
            System.out.println("payment total:"+total);
            String orderId = payment.getTransactions().get(0).getRelatedResources().get(0).getOrder().getId();
            System.out.println("payment invoiceNumber:"+payment.getTransactions().get(0).getInvoiceNumber());
            System.out.println("payment orderId:"+orderId);
            System.out.println("end execute payment.");
            System.out.println();

            System.out.println("start capture payment.");
            Capture capture=paypalService.capturePayment(total,payment.getTransactions().get(0).getAmount().getCurrency(),orderId);//捕获到买家授权的订单,整个过程到这里就完成了。
            System.out.println("Capture id = " + capture.getId() + " and status = " + capture.getState());
            if(payment.getState().equals("completed")){
                return "paypal/success";
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
        }
        return "redirect:/";
    }

}

URLUtils

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();
    }

}

PaypalService

import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import com.sillyming.test.common.Constant;

@Service
public class PaypalService {

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

    @Autowired
    private APIContext apiContext;

    public Payment createPayment(
            String total,
            String currency,
            String description,
            String cancelUrl,
            String successUrl,String invoiceNumber) throws PayPalRESTException {
        Amount amount = new Amount();
        amount.setCurrency(currency);
        amount.setTotal(total);
        Details details=new Details();
        details.setSubtotal(total);
        amount.setDetails(details);
        Transaction transaction = new Transaction();
        transaction.setDescription(description);
        transaction.setAmount(amount);
        transaction.setInvoiceNumber(invoiceNumber);

        List<Transaction> transactions = new ArrayList<>();
        transactions.add(transaction);

        Payer payer = new Payer();
        payer.setPaymentMethod(Constant.PAYMENT_METHOD_PAYPAL);

        Payment payment = new Payment();
        payment.setIntent(Constant.PAYMENT_INTENT_ORDER);
        payment.setPayer(payer);
        payment.setTransactions(transactions);
        RedirectUrls redirectUrls = new RedirectUrls();
        redirectUrls.setCancelUrl(cancelUrl);
        redirectUrls.setReturnUrl(successUrl);
        payment.setRedirectUrls(redirectUrls);

        return payment.create(apiContext);
    }

    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);
    }

    public Capture capturePayment(String total,String currency,String orderId){
        try{
            Amount amount = new Amount();
            amount.setCurrency(currency);
            amount.setTotal(total);

            // Authorize order
            Order order = new Order();
            order = Order.get(apiContext, orderId);
            order.setAmount(amount);
            Authorization authorization = order.authorize(apiContext);

            // Capture payment
            Capture capture = new Capture();
            capture.setAmount(amount);
            capture.setIsFinalCapture(true);

            Capture responseCapture = authorization.capture(apiContext, capture);
            return responseCapture;

        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
            return null;
        }
    }

}

PaypalService 这个类,具体可以参考官方文档:https://developer.paypal.com/docs/api/quickstart/create-process-order/
Java对接PayPal进行付款
Constant

public final class Constant {
	public static final int CODE_SUCCESS=1;
	public static final int CODE_ERROR=-1;
	public static final String CODE_SUCCESS_STRING="success";
	public static final String CODE_ERROR_STRING="error";

	public static final String PAYMENT_METHOD_PAYPAL="paypal";
	public static final String PAYMENT_METHOD_CREDIT_CARD="credit_card";

	public static final String PAYMENT_INTENT_ORDER="order";
	public static final String PAYMENT_INTENT_SALE="sale";
	public static final String PAYMENT_INTENT_AUTHORIZE="authorize";

}

代码就这样写完了,运行项目,访问index页面
Java对接PayPal进行付款
点击支付按钮,发送请求到paypal创建订单,然后把客户重定向到paypal支付页面:
Java对接PayPal进行付款
客户登录
Java对接PayPal进行付款
客户点击继续,相当于同意授权付款,客户授权后,我们后台就可以捕获授权后的订单,捕获成功后跳到成功页面
Java对接PayPal进行付款
也可以查看控制台打印的相关信息:
Java对接PayPal进行付款
整个支付流程就执行完毕了。

登录沙箱https://www.sandbox.paypal.com账号可以查看交易记录,下面是买家登录:
Java对接PayPal进行付款
商家:
Java对接PayPal进行付款
以上内容就是我自己的实践,如有错误希望指出。
谢谢观看!

本文地址:https://blog.csdn.net/weixin_44668634/article/details/109641799

相关标签: java paypal支付