How to integrate Paypal Website Payment in Java

Paypal is most popular payment gateway available.Paypal provides Rest API implementation to integrate gateway to your website.I am here using Rest API to integrate Paypal and payment will be made on our site.

In this example we’re taking cart total and shipping as input, you can calculate them as per your own.

You can download project source code also at the end of this post.

Dependency

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>paypalrestintegration</groupId>
  <artifactId>paypalrestintegration</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>paypalrestintegration Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
	<dependency>
  <groupId>com.paypal.sdk</groupId>
  <artifactId>rest-api-sdk</artifactId>
  <version>LATEST</version>
</dependency>
<!-- Servlet and JSP API Jars -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.1</version>
    <scope>provided</scope>
</dependency>
<!-- JSTL Jars -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

 </dependencies>
  <build>
    <finalName>paypalrestintegration</finalName>
  </build>
</project>

Paypal API Credentials

You need to create app under developer account in paypal site and client id and secret need to add in PaypalServlet.java.

  • Client ID
  • Client Secret

index.jsp

Here we’re taking inputs cart total and shipping. You can calculate them as your own way.

<html>
<body>
<h2>Paypal Payment Example by StartWithJava</h2>

<form action="http://localhost:8080/paypalrestintegration/PaypalDirectPayment" method="post">
<table>
<tr>
<td>Cart Sub Total</td>
<td><input type="text" name="cartTotal"></td>
</tr>
<tr>
<td>Shipping</td>
<td><input type="text" name="shipping"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>

</body>
</html>

PaymentService.java

This class defines the methods for paypal payment processing.

package com.startwithjava.paypalrestintegration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.Links;
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 PaymentService {
	private APIContext apiContext;
	public PaymentService(String clientId,String clientSecret,String mode) {
		apiContext = new APIContext(clientId, clientSecret, mode);	
	}
	public void proecssPayment(HttpServletRequest request,HttpServletResponse response) {
		// Set payer details
		Payer payer = new Payer();
		payer.setPaymentMethod("paypal");

		// Set redirect URLs
		RedirectUrls redirectUrls = new RedirectUrls();
		redirectUrls.setCancelUrl("http://localhost:8080/paypalrestintegration/cancel");
		redirectUrls.setReturnUrl("http://localhost:8080/paypalrestintegration/PaypalDirectPayment");

		// Set payment details
		double shipping = Double.parseDouble(request.getParameter("shipping"));
		double cartTotal = Double.parseDouble(request.getParameter("cartTotal"));
		double tax  = (cartTotal*14)/100;
		
		Details details = new Details();
		details.setShipping(shipping+"");
		details.setSubtotal(cartTotal+"");
		details.setTax(tax+"");
		
		
		double total = cartTotal+shipping+tax;
		
		// Payment amount
		Amount amount = new Amount();
		amount.setCurrency("USD");
		// Total must be equal to sum of shipping, tax and subtotal.
		amount.setTotal(""+total);
		amount.setDetails(details);

		// Transaction information
		Transaction transaction = new Transaction();
		transaction.setAmount(amount);
		transaction
		  .setDescription("This is the payment transaction description.");

		// Add transaction to a list
		List<Transaction> transactions = new ArrayList<Transaction>();
		transactions.add(transaction);

		//Add payment details
		Payment payment = new Payment();
		payment.setIntent("sale");
		payment.setPayer(payer);
		payment.setRedirectUrls(redirectUrls);
		payment.setTransactions(transactions);	
		
		// Create payment
		try {
		  Payment createdPayment = payment.create(apiContext);
		  
		 // System.out.println(createdPayment);

		  Iterator<Links> links = createdPayment.getLinks().iterator();
		  while (links.hasNext()) {
		    Links link = links.next();
		    if (link.getRel().equalsIgnoreCase("approval_url")) {
		      // REDIRECT USER TO link.getHref()	
		     response.sendRedirect(link.getHref());	
		    }
		  }
		} catch (PayPalRESTException e) {
		    System.err.println(e.getDetails());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	public void completePayment(HttpServletRequest req) {
		Payment payment = new Payment();
		payment.setId(req.getParameter("paymentId"));

		PaymentExecution paymentExecution = new PaymentExecution();
		paymentExecution.setPayerId(req.getParameter("PayerID"));
		try {
		  Payment createdPayment = payment.execute(apiContext, paymentExecution);
		  System.out.println(createdPayment);
		} catch (PayPalRESTException e) {
		  System.err.println(e.getDetails());
		}
	}
}

PaypalServlet.java

This servlet will process the form and make rest api call to the paypal for further processing. The Paypal API response will be printed in console. You can use them accordingly as per your need.

package com.startwithjava.paypalrestintegration;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PaypalServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PaymentService paymentService;
		if (request.getParameter("PayerID") != null) {
			paymentService = new PaymentService("YOUR_CLIENT_ID","YOUR_CLIENT_SECRET","sandbox");
			paymentService.completePayment(request);
			
		} else {
			paymentService = new PaymentService("YOUR_CLIENT_ID","YOUR_CLIENT_SECRET","sandbox");
			paymentService.proecssPayment(request,response);
		}
	}

}

Download Source Code

Download PayPal Payment Integration

Leave a Reply