Spring Boot Payment Gateway with PayPal Example

Posted By : Avnish Yadav | 21-Apr-2020

An E-Commerce web site Payment is a crucial half, and therefore the world’s most favorite and trustworthy online payment gateway is PayPal. It permits customers to shop for product or services either by exploitation their credit/debit cards, or their PayPal balance. PayPal additionally provides a mature SDK that helps programmers integrating PayPal payment solution into a web site.


In this Java tutorial, i will facilitate your write code to integrate PayPal payment into a Java internet application, step by step.


1. Objective of this tutorial


      1.1 Using PayPal API’s you'll place hold on your customer’s account.

      1.2  Same method you'll capture cash directly for your purchase.

      1.3 You could refund your client using API.

      1.4 Also, void any hold you've got placed on your account before.

      1.5 There are easy steps by that you may perform all on top of operations and that’s what we'll do in this tutorial. mainly we'll put HOLD on customer’s account.


2. What do I need?

You need PayPal Account. Follow below steps:

      2.1 Create official PayPal account

      2.2 Login to PayPal’s developer portal by using this link: https://developer.paypal.com/developer/applications

      2.3 Create new App by using this link: https://developer.paypal.com/developer/applications/create

      2.4 Get ClientID and ClientSecret that we'd like in our program to get paypalContext.


3. Add PayPal REST SDK dependency



4. Code Order Detail DTO Class



package com.oodles.spring.paypal.api;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

public class Order {

    private double price;
    private String currency;
    private String method;
    private String intent;
    private String description;



5. Code PayPal Configuration Class



public class PaypalConfig {

    private String clientId;
    private String clientSecret;
    private String mode;

    public Map<String, String> paypalSdkConfig() {
        Map<String, String> configMap = new HashMap<>();
        configMap.put("mode", mode);
        return configMap;

    public OAuthTokenCredential oAuthTokenCredential() {
        return new OAuthTokenCredential(clientId, clientSecret, paypalSdkConfig());

    public APIContext apiContext() throws PayPalRESTException {
        APIContext context = new APIContext(oAuthTokenCredential().getAccessToken());
        return context;



6. Code PayPal Controller Class



package com.oodles.spring.paypal.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
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;

public class PaypalController {

    PaypalService service;

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

    public String home() {
        return "home";

    public String payment(@ModelAttribute("order") Order order) {
        try {
            Payment payment = service.createPayment(order.getPrice(), order.getCurrency(), order.getMethod(),
                    order.getIntent(), order.getDescription(), "http://localhost:9090/" + CANCEL_URL,
                    "http://localhost:9090/" + SUCCESS_URL);
            for(Links link:payment.getLinks()) {
                if(link.getRel().equals("approval_url")) {
                    return "redirect:"+link.getHref();

        } catch (PayPalRESTException e) {

        return "redirect:/";

     @GetMapping(value = CANCEL_URL)
        public String cancelPay() {
            return "cancel";

        @GetMapping(value = SUCCESS_URL)
        public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId) {
            try {
                Payment payment = service.executePayment(paymentId, payerId);
                if (payment.getState().equals("approved")) {
                    return "success";
            } catch (PayPalRESTException e) {
            return "redirect:/";



7. Code PayPal Services Class



package com.oodles.spring.paypal.api;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.PaymentExecution;
import com.paypal.api.payments.RedirectUrls;
import com.paypal.api.payments.Transaction;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;

public class PaypalService {

    private APIContext apiContext;

    public Payment createPayment(
            Double total, 
            String currency, 
            String method,
            String intent,
            String description, 
            String cancelUrl, 
            String successUrl) throws PayPalRESTException{
        Amount amount = new Amount();
        total = new BigDecimal(total).setScale(2, RoundingMode.HALF_UP).doubleValue();
        amount.setTotal(String.format("%.2f", total));

        Transaction transaction = new Transaction();

        List<Transaction> transactions = new ArrayList<>();

        Payer payer = new Payer();

        Payment payment = new Payment();
        RedirectUrls redirectUrls = new RedirectUrls();

        return payment.create(apiContext);

    public Payment executePayment(String paymentId, String payerId) throws PayPalRESTException{
        Payment payment = new Payment();
        PaymentExecution paymentExecute = new PaymentExecution();
        return payment.execute(apiContext, paymentExecute);




8. Code PayPal Example application Class



package com.oodles.spring.paypal.api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class SpringPaypalExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringPaypalExampleApplication.class, args);




About Author

Author Image
Avnish Yadav

Avnish is a Software Developer having knowledge of java , j2ee ,sql , javascript and Data Structure.

Request for Proposal

Name is required

Comment is required

Sending message..