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

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

 

4. Code Order Detail DTO Class

 

Order.java


package com.oodles.spring.paypal.api;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Order {

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

}

 

5. Code PayPal Configuration Class

 

PayPalConfig.java

@Configuration
public class PaypalConfig {

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

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

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

    @Bean
    public APIContext apiContext() throws PayPalRESTException {
        APIContext context = new APIContext(oAuthTokenCredential().getAccessToken());
        context.setConfigurationMap(paypalSdkConfig());
        return context;
    }

}

 

6. Code PayPal Controller Class

 

PayPalController.java

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;

@Controller
public class PaypalController {

    @Autowired
    PaypalService service;

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

    @GetMapping("/")
    public String home() {
        return "home";
    }

    @PostMapping("/pay")
    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) {

            e.printStackTrace();
        }
        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);
                System.out.println(payment.toJSON());
                if (payment.getState().equals("approved")) {
                    return "success";
                }
            } catch (PayPalRESTException e) {
             System.out.println(e.getMessage());
            }
            return "redirect:/";
        }

}

 

7. Code PayPal Services Class

 

PayPalServices.java

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;

@Service
public class PaypalService {

    @Autowired
    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();
        amount.setCurrency(currency);
        total = new BigDecimal(total).setScale(2, RoundingMode.HALF_UP).doubleValue();
        amount.setTotal(String.format("%.2f", total));

        Transaction transaction = new Transaction();
        transaction.setDescription(description);
        transaction.setAmount(amount);

        List<Transaction> transactions = new ArrayList<>();
        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);
        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);
    }

}

 

 

8. Code PayPal Example application Class

 

SpringPaypalExampleApplication.java

package com.oodles.spring.paypal.api;

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

@SpringBootApplication
public class SpringPaypalExampleApplication {

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

}

 

Thanks

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..