Subversion Repositories SmartDukaan

Rev

Rev 13393 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.serving.controllers;

import in.shop2020.config.ConfigException;
import in.shop2020.model.v1.order.RechargeOrder;
import in.shop2020.model.v1.order.RechargeOrderStatus;
import in.shop2020.payments.Attribute;
import in.shop2020.payments.Payment;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.serving.services.CommonPaymentService;
import in.shop2020.thrift.clients.PaymentClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.thrift.clients.config.ConfigClient;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;

@SuppressWarnings("serial")
public class PayuPayResponseController extends BaseController{

        private static Logger log = Logger.getLogger(Class.class);

        private static final String UNMAPPED_STATUS = "UnMappedStatus";
        
        private static String successUrl;
        private static String errorUrl;
        private static String rechargeResultUri;

        /**
         * The secret key used to decode RC4 encoded data.
         */
        private static String accountKey;

        private static String salt;
        
        private String redirectUrl;
        
        private String eurl;
        private String surl;

        static{
                try {
                        ConfigClient cc = ConfigClient.getClient();
                        successUrl = cc.get("payu_success_url");
                        errorUrl = cc.get("payu_error_url");
                        accountKey = cc.get("payu_account_id");
                        salt = cc.get("payu_secret_key");
                        rechargeResultUri = ConfigClient.getClient().get("recharge_result_uri");
                } catch (ConfigException e) {
                        log.error("Unable to get success and error usr info from config server.");
                }
        }

        private Map<String, String> paymentParams = new TreeMap<String, String>();

        public String create() {
                eurl = errorUrl;
                surl = successUrl;
                updatePaymentParams(request.getParameterMap());

                PaymentClient paymentServiceClient = null;
                TransactionClient transactionServiceClient = null;
                UserClient userServiceClient = null;
                try {
                        userServiceClient = new UserClient();
                        paymentServiceClient = new PaymentClient();
                        transactionServiceClient = new TransactionClient();
                } catch (Exception e) {
                        log.error("Unable to initialize one of the clients", e);
                }


                long merchantPaymentId = Long.parseLong(paymentParams.get("txnid"));
                String gatewayPaymentId = paymentParams.get("mihpayid");
                double amount = Double.parseDouble(paymentParams.get("amount"));
                String gatewayTxnStatus = paymentParams.get("status");
                String hash = paymentParams.get("hash");
                String bankRefId = paymentParams.get("bank_ref_num");
                String unmappedStatus  = paymentParams.get("unmappedstatus");
                

                List<Attribute> attributes = new ArrayList<Attribute>();
                attributes.add(new Attribute(UNMAPPED_STATUS, unmappedStatus));

                Payment payment = null;
                Long txnId = null;
                try {
                        payment = paymentServiceClient.getClient().getPayment(merchantPaymentId);
                        txnId = payment.getMerchantTxnId();
                } catch (PaymentException e1) {
                        log.error("Payment exception. It is serious, check merchant payment id + " + merchantPaymentId, e1);
                } catch (TException e1) {
                        log.error("Thrift exception. Check payment id "+ merchantPaymentId, e1);
                }
                
                if(payment.getStatus() != PaymentStatus.INIT){
                        // We have already processed a response for this payment. Processing
                        // it again may fail his orders. So, let's ask him to check his
                        // account.
                        return "ebs-pay-response-maybe";
                }

                if(payment.isIsDigital()){
                        eurl = rechargeResultUri;
                        surl = rechargeResultUri;
                }
                
                if(!validatePaymentParams(amount, payment, hash)){
                        this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
                        return "index";
                }

                if(gatewayTxnStatus.equalsIgnoreCase("SUCCESS")){
                        try {
                                paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
                                                "", gatewayTxnStatus, unmappedStatus.equals("captured") ? "Transaction captured at PG":"Transaction Authorized at PG", 
                                                "", "", bankRefId, "", unmappedStatus.equals("captured") ? PaymentStatus.SUCCESS : PaymentStatus.AUTHORIZED, new SimpleDateFormat().format(new Date()), attributes);
                        } catch (PaymentException e) {
                                this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
                                return "index";
                        } catch (TException e) {
                                this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
                                return "index";
                        }
            if(payment.isIsDigital()){
                RechargeOrder rechargeOrder = null;
                try {
                    rechargeOrder = transactionServiceClient.getClient().getRechargeOrdersForTransaction(txnId);
                } catch (Exception e1) {
                    log.error("Problem with txn client while getting recharge object", e1);
                                this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
                                return "index";
                }
                
                        try {
                            PaymentClient pcl = new PaymentClient();
                            boolean isCaptured = pcl.getClient().capturePayment(txnId, true);
                            
                            //Retry in case we are not able to capture first time
                            if(!isCaptured){
                                Thread.sleep(2000);
                                isCaptured = pcl.getClient().capturePayment(txnId, true);
                            }
                            if(!isCaptured){
                                Thread.sleep(2000);
                                isCaptured = pcl.getClient().capturePayment(txnId, true);
                            }
                            
                            if(isCaptured) {
                                transactionServiceClient.getClient().updateRechargeOrderStatus(rechargeOrder.getId(), RechargeOrderStatus.PAYMENT_SUCCESSFUL);
                            } else {
                        transactionServiceClient.getClient().updateRechargeOrderStatus(rechargeOrder.getId(), RechargeOrderStatus.PAYMENT_FAILED);
                            }
                        } catch (Exception e) {
                            log.error("Problem with txn client while trying to recharge", e);
                        }
            } else {
                        CommonPaymentService.processSuccessfulTxn(txnId, userServiceClient, transactionServiceClient, false);
            }
            this.redirectUrl = surl + "?paymentId=" + merchantPaymentId;
                        
                } else{
                        try {
                                paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
                                                "", gatewayTxnStatus, "Payment Failed at PG", "", "", "", "", PaymentStatus.FAILED, new SimpleDateFormat().format(new Date()), attributes);
                        } catch (PaymentException e) {
                            log.error("Unable to mark the payment as failed", e);
                        } catch (TException e) {
                            log.error("Unable to mark the payment as failed", e);
                        }

                        if(!payment.isIsDigital()) {
                                CommonPaymentService.processFailedTxn(txnId, transactionServiceClient);
                        }

                        this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
                        
                }

                log.info("User will be redirected to: " + surl + "?paymentId=" + merchantPaymentId);
                return "index";
        }

        private boolean validatePaymentParams(double returnedAmount, Payment payment, String hash){
                if(!(payment != null && Math.abs(payment.getAmount() - returnedAmount) <= 0.50 && hash.equals(getSecureHash()))){
                        // We did not request this payment or the authorised amount is different.
                        log.error("Checks and balance failed on returned data");
                        return false;
                }
                return true;
        }


        public String getSecureHash(){
                try{
                        String pass = salt + "|" + paymentParams.get("status") + "|||||||||||" + paymentParams.get("email") + "|" +  paymentParams.get("firstname") + "|" + paymentParams.get("productinfo") + "|" + paymentParams.get("amount") + "|" + paymentParams.get("txnid") + "|" + accountKey;
                        System.out.println(pass);
                        MessageDigest md = MessageDigest.getInstance("SHA-512");
                        md.update(pass.getBytes(), 0, pass.getBytes().length);
                        byte[] mdbytes = md.digest();
                        //      convert the byte to hex format method
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < mdbytes.length; i++) {
                                sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
                        }
                        return sb.toString();
                }catch(NoSuchAlgorithmException nsae){
                        log.error("No such algorithm exception");
                        return null;
                }
        }

        private void updatePaymentParams(Map map){
                for(Object key : map.keySet()){
                    String keyStr = (String)key;
                    String[] vals = (String[])map.get(keyStr);
                    String value = vals[0];
                    System.out.println("Key " + (String)key + "     :    " + value);
                    paymentParams.put(keyStr, value);
                }
        }

        public String getRedirectUrl(){
                return this.redirectUrl;
        }

        @Override
        public void setServletRequest(HttpServletRequest request) {
                this.request = request;
        }

        public Map<String, String> getPaymentParams() {
                return paymentParams;
        }
}