Subversion Repositories SmartDukaan

Rev

Rev 33672 | Rev 33684 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
32916 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
33672 ranu 3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
33581 ranu 4
import com.spice.profitmandi.common.web.util.ResponseSender;
33672 ranu 5
import com.spice.profitmandi.dao.entity.fofo.UpsellRazorpayPaymentStatus;
33595 ranu 6
import com.spice.profitmandi.dao.repository.cs.AgentRecordingRepository;
33672 ranu 7
import com.spice.profitmandi.dao.repository.fofo.UpsellRazorpayPaymentStatusRepository;
33602 ranu 8
import com.spice.profitmandi.service.integrations.kommuno.KommunoService;
32929 amit.gupta 9
import com.spice.profitmandi.service.integrations.smartping.SmartPingService;
10
import com.spice.profitmandi.service.integrations.smartping.model.CallDetailModel;
32916 amit.gupta 11
import com.spice.profitmandi.web.util.MVCResponseSender;
12
import org.apache.logging.log4j.LogManager;
13
import org.apache.logging.log4j.Logger;
33672 ranu 14
import org.json.JSONObject;
32916 amit.gupta 15
import org.springframework.beans.factory.annotation.Autowired;
33672 ranu 16
import org.springframework.beans.factory.annotation.Value;
17
import org.springframework.http.HttpStatus;
33581 ranu 18
import org.springframework.http.MediaType;
19
import org.springframework.http.ResponseEntity;
32916 amit.gupta 20
import org.springframework.stereotype.Controller;
21
import org.springframework.ui.Model;
33591 ranu 22
import org.springframework.web.bind.annotation.ModelAttribute;
33672 ranu 23
import org.springframework.web.bind.annotation.RequestBody;
32916 amit.gupta 24
import org.springframework.web.bind.annotation.RequestMapping;
25
import org.springframework.web.bind.annotation.RequestMethod;
26
 
33672 ranu 27
import javax.crypto.Mac;
28
import javax.crypto.spec.SecretKeySpec;
32916 amit.gupta 29
import javax.servlet.http.HttpServletRequest;
30
import javax.transaction.Transactional;
33672 ranu 31
import java.time.LocalDateTime;
32
import java.util.Base64;
33
import java.util.Enumeration;
34
import java.util.HashMap;
35
import java.util.Map;
32916 amit.gupta 36
 
37
@Controller
38
@Transactional(rollbackOn = Throwable.class)
39
public class WebHookController {
40
 
41
    @Autowired
42
    MVCResponseSender mvcResponseSender;
43
 
33581 ranu 44
    @Autowired
45
    private ResponseSender<?> responseSender;
46
 
32916 amit.gupta 47
    private static final Logger LOGGER = LogManager.getLogger(WebHookController.class);
48
 
32919 amit.gupta 49
    @Autowired
32929 amit.gupta 50
    SmartPingService smartPingService;
32916 amit.gupta 51
 
33595 ranu 52
    @Autowired
33602 ranu 53
    KommunoService kommunoService;
54
 
55
    @Autowired
33595 ranu 56
    AgentRecordingRepository agentRecordingRepository;
57
 
33590 ranu 58
    @RequestMapping(value = "/click2call/report-handler", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
33591 ranu 59
    public ResponseEntity<?> click2callReportHandlerPost(HttpServletRequest request, Model model, @ModelAttribute CallDetailModel callDetail) throws Exception {
33581 ranu 60
        LOGGER.info("first event call detail {}", callDetail);
33602 ranu 61
        kommunoService.updateAgentRecording(callDetail);
33581 ranu 62
 
63
        return responseSender.ok(true);
32917 amit.gupta 64
    }
33581 ranu 65
 
66
 
33590 ranu 67
    @RequestMapping(value = "/click2call/report-handler/recording-url", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
33591 ranu 68
    public ResponseEntity<?> click2callReportHandlerUpdateRecordingUrlPost(HttpServletRequest request, Model model, @ModelAttribute CallDetailModel callDetail) throws Exception {
33581 ranu 69
        LOGGER.info("update call detail {}", callDetail);
33602 ranu 70
        kommunoService.updateAgentRecordingUrl(callDetail);
33581 ranu 71
        return responseSender.ok(true);
72
    }
33672 ranu 73
 
74
 
75
    @Value("${razorpay.account.keySecret}")
76
    private String razorpaySecret;
77
    @Autowired
78
    private UpsellRazorpayPaymentStatusRepository upsellRazorpayPaymentStatusRepository;
79
 
80
    @RequestMapping(value = "/upsellPayment/callback", method = RequestMethod.POST)
81
    public ResponseEntity<String> handleCallback(HttpServletRequest request, @RequestBody String payload) {
82
        try {
33682 ranu 83
            LOGGER.info("webhookcalled {}", 1);
33672 ranu 84
            // Verify the callback request
85
            Map<String, String> headers = getHeadersInfo(request);
86
            String razorpaySignature = headers.get("x-razorpay-signature");
87
            boolean isSignatureValid = verifySignature(payload, razorpaySignature);
88
 
89
            if (!isSignatureValid) {
90
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid signature");
91
            }
92
 
93
            // Parse the payload
94
            JSONObject jsonObject = new JSONObject(payload);
95
            String paymentId = jsonObject.getString("razorpay_payment_id");
96
            String status = jsonObject.getString("status");
97
 
98
            JSONObject notes = jsonObject.getJSONObject("notes");
99
            String orderId = notes.getString("orderId");
100
            String orderItemId = notes.getString("orderItemId");
101
            String planId = notes.getString("planId");
102
 
103
            JSONObject customer = jsonObject.getJSONObject("customer");
104
            String customerName = notes.getString("name");
105
            String customerMobile = notes.getString("contact");
106
            String customerEmail = notes.getString("email");
107
            String insuranceAmount = notes.getString("insuranceAmount");
108
 
109
            // Process the payment status
110
            if ("captured".equals(status)) {
111
                updatePaymentStatus(paymentId, "captured", orderId, insuranceAmount);
112
                throw new Exception("Payment successful for ID: " + paymentId);
113
 
114
            } else {
115
                updatePaymentStatus(paymentId, "failed", orderId, insuranceAmount);
116
                throw new Exception("Payment failed for ID: " + paymentId);
117
 
118
            }
119
 
120
        } catch (Exception e) {
121
            e.printStackTrace();
122
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing callback");
123
        }
124
    }
125
 
126
    private boolean verifySignature(String payload, String razorpaySignature) throws Exception {
127
        String actualSignature = HmacSHA256(payload, razorpaySecret);
128
        return actualSignature.equals(razorpaySignature);
129
    }
130
 
131
    private String HmacSHA256(String data, String key) throws Exception {
132
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
133
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
134
        sha256_HMAC.init(secret_key);
135
        return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(data.getBytes()));
136
    }
137
 
138
    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
139
        Map<String, String> map = new HashMap<>();
140
        Enumeration headerNames = request.getHeaderNames();
141
        while (headerNames.hasMoreElements()) {
142
            String key = (String) headerNames.nextElement();
143
            String value = request.getHeader(key);
144
            map.put(key, value);
145
        }
146
        return map;
147
    }
148
 
149
    private void updatePaymentStatus(String paymentId, String status, String orderId, String amount) throws ProfitMandiBusinessException {
150
        UpsellRazorpayPaymentStatus upsellRazorpayPaymentStatus = new UpsellRazorpayPaymentStatus();
151
        upsellRazorpayPaymentStatus.setCreatedTimestamp(LocalDateTime.now());
152
        upsellRazorpayPaymentStatus.setOrderId(Integer.parseInt(orderId));
153
        upsellRazorpayPaymentStatus.setPaymentId(paymentId);
154
        upsellRazorpayPaymentStatus.setPaymentStatus(status);
33682 ranu 155
        upsellRazorpayPaymentStatus.setPayment(Float.parseFloat(amount));
33672 ranu 156
        upsellRazorpayPaymentStatusRepository.persist(upsellRazorpayPaymentStatus);
157
    }
32916 amit.gupta 158
}