Subversion Repositories SmartDukaan

Rev

Rev 33686 | Rev 33689 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.fofo.UpsellRazorpayPaymentStatus;
import com.spice.profitmandi.dao.repository.cs.AgentRecordingRepository;
import com.spice.profitmandi.dao.repository.fofo.UpsellRazorpayPaymentStatusRepository;
import com.spice.profitmandi.service.integrations.kommuno.KommunoService;
import com.spice.profitmandi.service.integrations.smartping.SmartPingService;
import com.spice.profitmandi.service.integrations.smartping.model.CallDetailModel;
import com.spice.profitmandi.web.util.MVCResponseSender;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Controller
@Transactional(rollbackOn = Throwable.class)
public class WebHookController {

    @Autowired
    MVCResponseSender mvcResponseSender;

    @Autowired
    private ResponseSender<?> responseSender;

    private static final Logger LOGGER = LogManager.getLogger(WebHookController.class);

    @Autowired
    SmartPingService smartPingService;

    @Autowired
    KommunoService kommunoService;

    @Autowired
    AgentRecordingRepository agentRecordingRepository;

    @RequestMapping(value = "/click2call/report-handler", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<?> click2callReportHandlerPost(HttpServletRequest request, Model model, @ModelAttribute CallDetailModel callDetail) throws Exception {
        LOGGER.info("first event call detail {}", callDetail);
        kommunoService.updateAgentRecording(callDetail);

        return responseSender.ok(true);
    }


    @RequestMapping(value = "/click2call/report-handler/recording-url", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<?> click2callReportHandlerUpdateRecordingUrlPost(HttpServletRequest request, Model model, @ModelAttribute CallDetailModel callDetail) throws Exception {
        LOGGER.info("update call detail {}", callDetail);
        kommunoService.updateAgentRecordingUrl(callDetail);
        return responseSender.ok(true);
    }


    @Value("${razorpay.account.keySecret}")
    private String razorpaySecret;
    @Autowired
    private UpsellRazorpayPaymentStatusRepository upsellRazorpayPaymentStatusRepository;

    @RequestMapping(value = "/upsellPayment/callback", method = RequestMethod.GET)
    public ResponseEntity<String> handleCallback(HttpServletRequest request) {
        try {
            LOGGER.info("Webhook called with query parameters");

            // Retrieve the Razorpay parameters from the query string
            String paymentId = request.getParameter("razorpay_payment_id");
            String razorpaySignature = request.getParameter("razorpay_signature");
            String orderId = request.getParameter("orderId");
            String insuranceAmount = request.getParameter("insuranceAmount");

            // Check for required parameters
            if (paymentId == null || razorpaySignature == null || orderId == null || insuranceAmount == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Missing required parameters");
            }

            // Construct payload for signature verification
            String payload = "razorpay_payment_id=" + paymentId + "&orderId=" + orderId + "&insuranceAmount=" + insuranceAmount;

            // Verify the signature
            boolean isSignatureValid = verifySignature(payload, razorpaySignature);
            if (!isSignatureValid) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid signature");
            }

            // Handle the payment status (you may need to add more logic depending on the status)
            updatePaymentStatus(paymentId, "captured", orderId, insuranceAmount);

            return ResponseEntity.ok("Payment successful for ID: " + paymentId);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing callback");
        }
    }


    private boolean verifySignature(String payload, String razorpaySignature) throws Exception {
        String actualSignature = HmacSHA256(payload, razorpaySecret);
        return actualSignature.equals(razorpaySignature);
    }

    private String HmacSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(data.getBytes()));
    }

    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    private void updatePaymentStatus(String paymentId, String status, String orderId, String amount) throws ProfitMandiBusinessException {
        UpsellRazorpayPaymentStatus upsellRazorpayPaymentStatus = new UpsellRazorpayPaymentStatus();
        upsellRazorpayPaymentStatus.setCreatedTimestamp(LocalDateTime.now());
        upsellRazorpayPaymentStatus.setOrderId(Integer.parseInt(orderId));
        upsellRazorpayPaymentStatus.setPaymentId(paymentId);
        upsellRazorpayPaymentStatus.setPaymentStatus(status);
        upsellRazorpayPaymentStatus.setPayment(Float.parseFloat(amount));
        upsellRazorpayPaymentStatusRepository.persist(upsellRazorpayPaymentStatus);
    }
}