Requirement:

  1. Razorpay account.
  2. Update kyc with bank details.
  3. public URL for webhook.

How to set sandbox account

  1. Register using mobile number and email address.
  2. Fill basic details with Business information(like what type of business)
  3. Generate api key for test mode :-
    • 3.1. Log in to dashboard.
    • 3.2. select mode (test).
    • 3.3. go to Settings → API Keys → Generate Key then download the key.

Implementation

1. Add Razorpay dependency

<dependency> 

<groupId>com.razorpay</groupId> 

<artifactId>razorpay-java</artifactId>

 <version>1.3.9</version> 

 </dependency>

2. Add secret-id and secret-key in appliction.properties.

3. Integration step:

  1. create a order in server and save in DB.
  2. Pass order id and to client side.
  3. handle payment success or failed status and store response in DB .
  4. Get payment details by passing payment id and save it in DB.

4. Create required class:

  1. Customers
  2. Orders
  3. Payments
  4. Refunds
  5. Cards

4.1. Customers :

A. properties:

@Id
private Long id;
private String name;
private String email;
private String contact;
private String gstin;
@OneToMany(mappedBy = "customers")
private List<Orders> orders;
@OneToMany(mappedBy = "customers")
private List<PaymentMethod> paymentMethods;
@OneToMany(mappedBy = "customers")
private List<Cards> cards;
/** * It represents record created date. */
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false)
private Date createdDate;
/** * It represents record updated date. */
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date updatedDate;

B. Dtos:

C. Services:

List<CustomerResponseDto> getAll();

CustomerResponseDto getById(Long id);

Customers getByContact(String contact);

CustomerRequestDto add(CustomerRequestDto customerRequestDto);

CustomerRequestDto update(Long id, CustomerRequestDto customerRequestDto);

normal crud services logic.

D. Implementation:

Get customer details from clientside using CustomerRequestDto and save it to DB.

4.2. Orders :

A. properties:

@Idprivate String id;
private int amount;
private int amount_paid;
private int amount_due;
private String currency;
private String receipt;
private String status;
private String refund_status;
private int attempts;
private String razorpay_payment_id;
private String razorpay_signature;
@ManyToOne
@JoinColumn(name = "customers_id")
private Customers customers;
@OneToOne(mappedBy = "orders")
private Payments payments;
/** * It represents record created date. */
@Column(updatable = false)
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
/** * It represents record updated date. */
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date updatedDate;

B. Dtos:

OrderRequestDto: to get order request from client side
OrderResponseDto: send order response to client side
OrderCheckDto: after payment success response

C. Service:

List<OrderResponseDto> getAll(Long customerId); //get from db

OrderResponseDto getById(Long customerId, String id); //get from db

Orders getOrder(String id); //get from db

OrderResponseDto add(OrderRequestDto orderRequestDto); 

Orders update(OrderCheckDto orderCheckDto) throws RazorpayException;

OrderResponseDto pending(String id);

4.3. Payments:

A. properties:

private String id;
private int amount;
private String currency;
private String status;
private String invoice_id;
@Builder.Default
private Boolean international = false;
private String method;
private int amount_refunded;
private String refund_status;
@Builder.Default
private Boolean captured = false;
private String description;
private String card_id;
private String bank;
private String wallet;
private String vpa;
private String email;
private String contact;
private int fee;
private int tax;
private String error_code;
private String error_description;
private String error_source;
private String error_step;
private String error_reason;
@JsonIgnore@OneToOne()
@JoinColumn(name = "order_id")
private Orders orders;
@OneToMany(mappedBy = "payments")
private List<Refunds> refunds;
/** 
 * It represents record created date.
 */
@Column(updatable = false)
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date createdDate;

B. Dtos:

PaymentDto: to create payment

C. Service:

List<PaymentDto> getAll(Long customerId);

PaymentDto getById(String id) throws RazorpayException;

Payments add(OrderCheckDto orderCheckDto) throws RazorpayException;

PaymentDto update(String paymentId) throws RazorpayException;

4.4. Refunds:

A. Properties:

private String id;
private int amount;
private String currency;
private String receipt;
private String batch_id;
private String status;
private String speed_processed;
private String speed_requested;
@ManyToOne
@JoinColumn(name = "payment_id")
private Payments payments;
private String created_at;

B. Dtos:

RefundDto: send refund response to client side

C. Service:

RefundDto add(RefundRequestDto refundRequestDto) throws RazorpayException;

4.5. Cards : This class is used to save card information.

A. Properties:

String id;
String entity;
String name;
int last4;
String network;
String type;
String issuer;
String emi;
String international;
String sub_type;
String token_iin;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "customers_id")
private Customers customers;

B. Service:

Cards getCard(String id) throws RazorpayException;

void addCard(String cardId, Customers customers) throws RazorpayException;

IMPLIMENTATION

To create order create pass all detail in OrderRequestDto and call add method;

Create Order:

  1. create razorpay client object and pass secret-id and secret-key.
  2. create JsonObject and provide details about amount, currency etc.
  3. pass json object in razorpay_client order create function.
  4. save response in DB.
  5. set customer in order
create order using razorpay client
save order in db

6. Return order response to client service .

Payment process:

1. In client site place all the field value from orderResponse.

by call this ajax function Order created and return order response
order response value place in razorpay parameter

razorpay chekout url script

<script src="https://checkout.razorpay.com/v1/checkout.js"></script>

Razorpay provide a payment gateway call url which takes some parameters and return payment response in handler section.

var options = {
    "key": "",   
     "amount": "",    
     "currency": "",    
     "name": "",    
     "description": "",    
     "order_id": "",    
     "image": "https://theovaku.com/wp-content/themes/ovaku-stronger-together/img/banner.jpg",    
     "handler": function (response) {
        // alert(response.razorpay_payment_id);        
        console.log(response)
        $('#pay-success').show();        
        dopay("/pay", response, false);        
        docheck("/checkPayment", response, false);        
        console.log(options.order_id);        
        alert(" Successfully payed");        
        // console.log(resp);    },    
        "prefill": {
                "name": "",
                "email": "",        
                "contact": ""
                 },    
        "notes": {
                    "address": "Razorpay Corporate Office"
                },
        "theme": {
            "color": "#3399cc"
               }

2. After razorpay .open() function call, payment go on progress and return response in handler.

3. Successfull payment return razorpay_order_id, razorpay_payment_id, razorpay_signature;

as response.

4. In handler call ajax function to call payment (add service method) and pass orderCheckDto.

4.i)Add and save payment:

  1. create razorpay client object and pass secret-id and secret-key.
  2. call razorpay client Payment class method fetch and pass razorpay_order_id to get payment details;
  3. save payment in db;
  4. set order with payment;

5. after save payment back to handler.

6. call ajax function order (update) method to update payment status in order.

fetch order using razorpay client and update order in db