Next, update the PaymentController:
- Create a new GET API ‘/payment/paymentStatus’.
- Define a method getPaymentStatus that accepts @RequestParam String paymentId and returns PaymentStatus.
- Call paymentService.getPaymentStatus, pass paymentId, and return the result.
@RestController
public class PaymentController {
/* Previous code */
@GetMapping(“/payment/getPaymentStatus”)
public PaymentStatus getPaymentStatus(@RequestParam(“paymentId”) String paymentId, @RequestParam(“orderId”) String orderId){
return paymentService.getPaymentStatus(paymentId, orderId);
}
Create PaymentStatus Enum: In the `models` package, create an enum `PaymentStatus` with the values `SUCCESS`, `FAILURE`, and `INITIATED`.
public enum PaymentStatus {
SUCCESS, FAILURE, INITIATED
}
Update PaymentService:
- Create a new method public PaymentStatus getPaymentStatus(String paymentId) that returns PaymentStatus.
- This method should call another method getStatus from paymentGateway, pass paymentId, and hold the result in a variable of type PaymentStatus to return it.
@Service
public class PaymentService {
/* Previous code */
public PaymentStatus getPaymentStatus(String paymentId, String orderId) {
// Retrieve payment details by order ID
Optional<PaymentDetails> paymentDetails = paymentRepository.findByOrderId(orderId);
if(paymentDetails.isEmpty()){
throw new RuntimeException(“Payment not found”);
}
// Get payment status from the payment gateway
PaymentStatus status = paymentGateway.getStatus(paymentId, orderId);
// Update and save payment details with the new status
PaymentDetails paymentResponse = paymentDetails.get();
paymentResponse.setStatus(status);
paymentResponse.setPaymentId(paymentId);
paymentRepository.save(paymentResponse);
return status;
}
}
Update PaymentGateway Interface:
Add the method signature `PaymentStatus getStatus(String paymentId)
@Component
public interface PaymentGateway {
String createPaymentLink( String orderId, String customerName, String phone, int amount);
PaymentStatus getStatus(String paymentId);
}
Implement getStatus in RazorPayGateway:
- Implement the getStatus method in the RazorPayGateway class.
- Refer to the Razorpay documentation for fetching payment details. Click on the payment link to get the fetch payment code.
- Use the payment.fetch method from razorpayClient with paymentId, which returns a Payment type.
- Return the corresponding PaymentStatus.
@Service
public class RazorPayGateway implements PaymentGateway{
/* Previous code */
@Override
public PaymentStatus getStatus(String paymentId, String orderId) {
try {
Payment payment = razorpayClient.payments.fetch(paymentId);
String statusType = payment.get(“status”);
return switch (statusType) {
case “captured” -> PaymentStatus.SUCCESS;
case “failed” -> PaymentStatus.FAILURE;
default -> PaymentStatus.INITIATED;
};
} catch (RazorpayException e) {
throw new RuntimeException(“Unable to fetch the payment details”, e);
}
}
}