How To Integrate Razorpay In Spring Boot & Angular?

Nowadays, Every business makes their presence on the internet to grow their business. Online payment is now a common thing. It helps businesses to run their business more smoothly.

Depending on the business, they want to integrate a payment gateway for their platform or website. Selecting a payment gateway makes lives easier for the customer and the business owner. On the market, there are several payment gateways to choose from. But this is where we’ll look at the Razorpay payment gateway.

In this post, we’ll look at how to use Spring Boot (Java) and Angular(Client-Side) to integrate the Razorpay payment gateway and accept payments quickly and easily.

What is a Razorpay Payment Gateway?

The Razorpay payment gateway is a software solution that makes it possible for individuals and businesses to accept payments and route the same to owners’ accounts.

By using Razorpay you can collect payment from customers using all payment modes, including debit and credit cards, UPI, and other popular mobile wallets.

With the help of Razorpay, you can automate bank transfers, collect recurring payments, share invoices with customers, and manage your marketplace.

Integration Of Razorpay

Integration of the Razorpay payment gateway is different for different technologies. Here we are going to use Angular (Client-Side) and Spring Boot Java (Server-Side).

To integrate Razorpay, all you need to do is create a Razorpay account. Visit the link to create an account.

There are basically two environments provided by Razorpay payment.

  1. Test Mode (Testing purpose)
  2. Live Mode (To accept real-time payments)

Here we will use the test mode for integration.

Step 1: Get Id And Secret Key

Before accessing any API of Razorpay you will need Razorpay Id and Secret which you can get from the Razorpay dashboard.

– Go To Razorpay Dashboard
Go to Razorpay Dashboard.
– On The Left Side, The Sidebar Menu Clicks On Settings. After That Click On The API Keys Tab
Razor_pay_setting
– Click On Generate A Key To View On Downloading The Id And Secret Key

Make sure the secret key will not be shared with anyone. We need a Razorpay Id at the client side.

Sample keys will look like below :
Key Id : rzp_test_********
Key Secret : i*********

Step 2: Setup Razorpay In Your Project

For starting using Razorpay first you need to add the official Razorpay library into your project. This will allow you to access all Razorpay APIs.

– Server Side:

For the spring boot project, you will need to add dependency into the pom.xml file.

<dependency>

<groupId>com.Razorpay</groupId>

<artifactId>Razorpay-java</artifactId>

<version>x.y.z</version> //x.y.z = the version you want to install

</dependency>

– Client Side:

For the Angular side, you will need to run the following command to install the npm package of Razorpay.

npm i Razorpay

Step 3: Understanding Payment Flow Of Razorpay

The Razorpay payment flow is depicted in the diagram below.

Razorpay payment flow

From the above steps, we have completed the setup of Razorpay into our project and understood the flow of payment checkout.

Let’s consider one scenario, you are building a web application for an e-commerce store. You want to create a checkout flow for purchasing any item. Then we need to follow the below process to accept customers’ payments through Razorpay checkout.

1. Customer Place An Order On Your Website Or App

A customer visits your website or application, then selects the item they want to purchase. After clicking on the buy button the front end will call the Backend API with the price of the item to create an Order in Razorpay.

2. Create Order From Your Backend Server

Use the Razorpay orders API to generate an order from your server for each customer order.

To build order in your (backend) server, use the endpoint below.

POST: /orders

try {

  JSONObject orderRequest = new JSONObject();

  orderRequest.put("amount", 50000); // amount in the smallest currency unit

  orderRequest.put("currency", "INR");

  orderRequest.put("receipt", "order_rcptid_11");

  Order order = Razorpay.Orders.create(orderRequest);

} catch (RazorpayException e) {

  // Handle Exception

  System.out.println(e.getMessage());

}

You can store customer details and order details in your payments table for future reference. When actual payment is completed by the customer at Razorpay that time using the order id you can verify the same purchase.

3. Pass Order Id To Front-end And Collect Payment Details

Pass the order_id returned by order create API of Razorpay to your front end for checkout.

There are two sample codes provided for checkout:

With Handler Function - When you use this:With Callback URL - When you use this:
On successful payment, the customer will be shown your webpage.On successful payment, the customer will be redirected to the specified URL, for example, a payment success page.
On payment failure, the customer will be notified of the reason for failure and asked to retry the payment.On payment failure, the customer will be asked to retry payment on Checkout.

We will need to pass Razorpay Id, Amount, and Order Id which are generated from the server-side to Razorpay checkout for opening the payment window.

var options = {

    "key": "YOUR_KEY_ID", // Enter the Key ID generated from the Dashboard

    "amount": "50000", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise

    "currency": "INR",

    "name": "Acme Corp",

    "description": "Test Transaction",

    "image": "https://example.com/your_logo",

    "order_id": "order_9A33XWu170gUtm", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1

    "handler": function (response){

        alert(response.Razorpay_payment_id);

        alert(response.Razorpay_order_id);

        alert(response.Razorpay_signature)

    },

    "prefill": {

        "name": "Gaurav Kumar",

        "email": "gaurav.kumar@example.com",

        "contact": "9999999999"

    },

    "notes": {

        "address": "Razorpay Corporate Office"

    },

    "theme": {

        "color": "#3399cc"

    }

};

var rzp1 = new Razorpay(options);

document.getElementById('rzp-button1').onclick = function(e){

    rzp1.open();

    e.preventDefault();

4. Handle Payment Success And Failure

Depending on the Checkout sample code you chose in the previous step, the way you handle payment success and failure circumstances will be different.

The customer will be directed to your page, and Checkout will return the response object of the successful payment (Razorpay payment id, Razorpay order id, and Razorpay signature). These must be gathered and sent to your server.

– Payment Success

"handler": function (response){

    alert(response.Razorpay_payment_id);

    alert(response.Razorpay_order_id);

    alert(response.Razorpay_signature)

}

On payment failure, the customer will be notified of the reason for failure and asked to retry the payment.

– Payment Failure

rzp1.on('payment.failed', function (response){

    alert(response.error.code);

    alert(response.error.description);

    alert(response.error.source);

    alert(response.error.step);

    alert(response.error.reason);

    alert(response.error.metadata.order_id);

    alert(response.error.metadata.payment_id);

} 

5. Capture The Payment

After payment is authorized, you need to capture the payment made by the customer for the amount to get settled in your bank account as per the settlement schedule. Payments that are not captured by you manually or automatically then those payments will be auto-refunded after a fixed time period.

  • Auto-capture payments (Recommended)

Authorized payments can be automatically captured. You can auto captured payments using settings in the Razorpay dashboard.

  • Manually capture payments

Each authorized payment can also be captured individually. You can manually capture payments:

    1. Payment Capture API
    2. Razorpay Dashboard

Best Practises & Key Points

1. Keep Secret Key Secure

Try to call all Razorpay APIs from the server-side only. So store the secret key on the server-side only. Do not share a secret key to the client-side for security reasons.

2. Capture Payment

When a payment made by the customer is authorized, it needs to settle in your bank account. For that, you must capture the payment by using any of the payment capture options. Payments that are not captured are auto-refunded after a fixed period of time.

3. Integrate Orders API

Orders APIs help in binding multiple payment attempts against a single order. This helps to prevent multiple payments. Integrate with Orders API of the Razorpay on your server-side and pass the order_id to the client-side for the checkout process. When you create an order from the server-side you can store order details for the customer in your payments table and at the time of capturing payment, you can change the payment status against that order id.

4. Check Payment/Order Status Before Providing Service To The Customer

Check the payment/order status, that is if the payment’s status is captured and the order’s status is paid before providing the services to the customers. It is a must-do activity to verify the payment is actually done or not and giving appropriate service to the customer.

5. Implement Webhooks

Implement webhooks or the query API to avoid any cases of callback failure (drop-offs could be connectivity or network failure) and to verify the payment details via S2S(Server to Server) call.

coma

Conclusion

In this article, we discussed the integration of the Razorpay payment gateway for the server-side and client-side.

More features of payments, API, and documentation you can find in the official documentation.

Thank you for reading!

Rohit

Full Stack Developer (Java | Angular)

Rohit is having 2.8 years of experience as a Full Stack Developer. He has good knowledge of creating APIs, well-designed microservices, payment gateway integrations and web technology like Angular 4+. He is a passionate coder who writes clean, optimized code. In his free time, he does solve technical problems on hacker rank, StackOverflow, geeks for geeks etc.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks
coma

Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.

author
George Hodulik
CEO, Stealth Startup, Ex-Google