Integrating Razorpay Payment Gateway with Your Spring Boot Application

Introduction

In the modern digital landscape, integrating online payment gateways has become crucial for any e-commerce or service-oriented application. Razorpay is a top choice among developers due to its ease of use and robust features. In this guide, we’ll cover how to integrate Razorpay into a Spring Boot application, from order creation to payment verification.into a Spring Boot application, from order creation to payment verification.

Why Choose Razorpay?
Razorpay is a versatile payment platform in India that helps businesses handle payments through its product suite. It offers support for various payment methods, including credit/debit cards, net banking, UPI, and digital wallets. Here are some of its standout features:
  • User-Friendly Integration: Razorpay offers simple APIs and SDKs for various platforms.
  • Diverse Payment Methods: Supports credit/debit cards, net banking, UPI, digital wallets, and EMI options.
  • Enhanced Security: Compliant with PCI DSS Level 1, ensuring top-notch data security.

Prerequisites

Before starting, make sure you have:
  1. Spring Boot Application: A basic Spring Boot setup.
  2. Razorpay Account: Sign up on Razorpay and obtain your API keys.
  3. Dependencies: Add necessary dependencies for Razorpay and Spring Boot.

    Prerequisites
    Before starting, make sure you have:
    1. Spring Boot Application: A basic Spring Boot setup.
    2. Razorpay Account: Sign up on Razorpay and obtain your API keys.
    3. Dependencies: Add necessary dependencies for Razorpay and Spring Boot.

Step-by-Step Integration
Step 1: Add Dependencies
Add the required dependencies in your pom.xml file:

org.springframework.boot spring-boot-starter-web com.razorpay razorpay-java 1.3.6

Step 2: Configure Razorpay Client
Create a configuration class to set up the Razorpay client:

import com.razorpay.RazorpayClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RazorpayConfig {
  @Value("${razorpay.keyId}")
  private String keyId;
  @Value("${razorpay.keySecret}")
  private String keySecret;
  @Bean
  public RazorpayClient razorpayClient() throws Exception {
    return new RazorpayClient(keyId, keySecret);
  }
}
Add the API keys in your application.properties file:
razorpay.keyId=YOUR_KEY_ID
razorpay.keySecret=YOUR_KEY_SECRET
    

Step 3: Create Order
Create a service to handle order creation:

import com.razorpay.Order;
import com.razorpay.RazorpayClient;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PaymentService {
  @Autowired
  private RazorpayClient razorpayClient;
  public String createOrder(double amount, String currency) throws Exception {
    JSONObject orderRequest = new JSONObject();
    orderRequest.put("amount", amount * 100);
    orderRequest.put("currency", currency);
    orderRequest.put("payment_capture", 1);
    Order order = razorpayClient.Orders.create(orderRequest);
    return order.toString();
  }
}
    

Step 4: Create Controller
Create a controller to expose the API endpoints:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PaymentController {
  @Autowired
  private PaymentService paymentService;
  @GetMapping("/createOrder")
  public String createOrder(@RequestParam double amount, @RequestParam String currency) {
    try {
      return paymentService.createOrder(amount, currency);
    } catch (Exception e) {
      return e.getMessage();
    }
  }
}
    

Step 5: Verify Payment
Create a service method to verify payment:

public boolean verifyPayment(String orderId, String paymentId, String razorpaySignature) {
  String payload = orderId + '|' + paymentId;
  try {
    return Utils.verifySignature(payload, razorpaySignature, razorpayConfig.getSecret());
  } catch (Exception e) {
    e.printStackTrace();
    return false;
  }
}
    

This is the Util class handling the verify signature method:

import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
public class Utils {
  public static boolean verifySignature(String payload, String expectedSignature, String secret) throws Exception {
    String actualSignature = calculateRFC2104HMAC(payload, secret);
    return actualSignature.equals(expectedSignature);
  }
  private static String calculateRFC2104HMAC(String data, String secret) throws Exception {
    SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(signingKey);
    byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
    return new String(Hex.encodeHex(rawHmac));
  }
}
    

Update the controller to handle payment verification:

@PostMapping("/verify")
public ResponseEntity verifyPayment(@RequestParam String orderId,
                      @RequestParam String paymentId,
                      @RequestParam String razorpaySignature) {
  try {
    boolean isValid = paymentService.verifyPayment(orderId, paymentId, razorpaySignature);
    if (isValid) {
      return ResponseEntity.ok("Payment verified successfully");
    } else {
      return ResponseEntity.status(400).body("Payment verification failed");
    }
  } catch (Exception e) {
    return ResponseEntity.status(500).body("Error verifying payment");
  }
}
    

Conclusion

Integrating Razorpay with a Spring Boot application is a straightforward process. By following the steps outlined above, you can easily set up payment processing, create orders, and verify payments within your application. Razorpay’s comprehensive API and extensive documentation make it an excellent choice for handling online payments securely and efficiently.