Subversion Repositories SmartDukaan

Rev

Rev 1034 | Blame | Last modification | View Log | RSS feed

package in.shop2020.serving.controllers;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.thrift.TException;

import in.shop2020.config.ConfigException;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.Transaction;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.model.v1.user.Cart;
import in.shop2020.model.v1.user.Line;
import in.shop2020.model.v1.user.ShoppingCartException;
import in.shop2020.payments.Attribute;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.serving.utils.Utils;
import in.shop2020.thrift.clients.PaymentServiceClient;
import in.shop2020.thrift.clients.TransactionServiceClient;
import in.shop2020.thrift.clients.UserContextServiceClient;
import in.shop2020.thrift.clients.config.ConfigClient;



import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;
@Results({
        @Result(name="redirect", type="redirectAction", 
                        params = {"actionName" , "${url}"}),
        @Result(name="shipping-redirect", type="redirectAction", 
                params = {"actionName" , "shipping"})
})

public class HdfcPayController extends BaseController {
        private static final long serialVersionUID = 1L;
        private static Logger log = Logger.getLogger(Class.class);
        
        private static String resourceFilePath;
        private static String aliasName;
        private static String responseURL;
        private static String errorURL;
        private static final String regex = "[^a-zA-Z0-9\\s\\-\\@\\/\\.]";
        private static final String replacement = " ";
        private static final int MAX_UDF_LENGTH = 30;
        private String redirectURL;
        private e24PaymentPipe pipe = null;
        
        private enum ActionType{
                PURCHASE("1"),
                AUTH ("4");
                private String value;
                ActionType(String value) {
                        this.value = value;
                }
                public String value(){
                        return this.value;
                }
        }
        
        public HdfcPayController(){
                
        }
        
        static{
                try {
                        resourceFilePath = ConfigClient.getClient().get("payment_resource_file_path");
                        aliasName  = ConfigClient.getClient().get("payment_alias_name");
                        responseURL = ConfigClient.getClient().get("payment_response_url");
                        errorURL = ConfigClient.getClient().get("payment_error_url");
                } catch (ConfigException e) {
                        log.error("Unable to get data from config server.");
                }
        }
        
        
        public String index(){
                
                String merchantPaymentId = request.getParameter("paymentid");
                long txnId = Long.parseLong(request.getParameter("txnid"));
                
                if(merchantPaymentId == null){
                        addActionError("We are experiencing some problems. Please try later.");
                        log.error("Merchant payment is null. It should not have reached here.");
                        return "shipping-redirect";
                }
                
                PaymentServiceClient paymentServiceClient = null;
                try {
                        paymentServiceClient = new PaymentServiceClient();
                } catch (Exception e) {
                        e.printStackTrace();
                }
                
                try {
                        initializePayment(merchantPaymentId);
                } catch (ShoppingCartException e1) {
                        addActionError("We are experiencing some problems. Please try later.");
                        log.error("Error while creating hdfc payment.");
                        e1.printStackTrace();
                        return "shipping-redirect";
                } catch (TException e1) {
                        addActionError("We are experiencing some problems. Please try later.");
                        log.error("Error while creating hdfc payment.");
                        e1.printStackTrace();
                        return "shipping-redirect";
                }
                
                List<Attribute> attributes = null;
                try {
                        attributes = getAttributesAndSetUdfs(txnId);
                } catch (TransactionServiceException e1) {
                        addActionError("We are experiencing some problems. Please try later.");
                        log.error("Error while setting udfs to payment.");
                        e1.printStackTrace();
                        return "shipping-redirect";
                } catch (TException e1) {
                        addActionError("We are experiencing some problems. Please try later.");
                        log.error("Error while setting udfs to payment.");
                        e1.printStackTrace();
                        return "shipping-redirect";
                }
                
                
                try {
                        if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) 
                                {
                                        System.out.println("Error sending Payment Initialization Request: ");
                                        paymentServiceClient.getClient().updatePaymentDetails(Long.parseLong(merchantPaymentId), null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
                                        response.sendRedirect(response.encodeRedirectURL( errorURL + "?ErrorText="+pipe.getErrorMsg()+"&paymentId="+merchantPaymentId));
                                        redirectURL = errorURL + "?paymentId="+merchantPaymentId + "&ErrorText="+pipe.getErrorMsg();
                                        response.setHeader("Location", redirectURL);
                                        response.setStatus(HttpServletResponse.SC_FOUND);
                                }
                        else
                                {
                                        String paymentID = pipe.getPaymentId();
                                        // Update of payment information
                                        paymentServiceClient.getClient().updatePaymentDetails(Long.parseLong(merchantPaymentId), paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
                                        
                                        String payURL = pipe.getPaymentPage();
                                        redirectURL = payURL + "?PaymentID=" + paymentID;
                                        response.sendRedirect(response.encodeRedirectURL( redirectURL ));
                                        
                                        response.setHeader("Location", redirectURL);
                                        response.setStatus(HttpServletResponse.SC_FOUND);
                                }
                        return "success";
                } catch (NotEnoughDataException e) {
                        log.error("Error while initializing payment." + e.getMessage());
                        e.printStackTrace();
                }catch (Exception e) {
                        log.error("Error while initializing payment." + e.getMessage());
                        e.printStackTrace();
                }
                
                redirectURL = errorURL + "?paymentId="+merchantPaymentId + "?ErrorText=Error while initializing payment.";
                return "success";
        }
        
        
        private double getPaymentAmount(long cartId) throws ShoppingCartException, TException{
                double totalAmount = 0;
                Cart cart;
                UserContextServiceClient userContextServiceClient = null;
                try {
                        userContextServiceClient = new UserContextServiceClient();
                } catch (Exception e) {
                        e.printStackTrace();
                }
                in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
                cart = userClient.getCart(cartId);
        
                List<Line> lineItems = cart.getLines(); 
        
                for (Line line : lineItems) {
                        long productId = line.getItemId();
                        totalAmount =  totalAmount + line.getQuantity() * Utils.getItemPrice(productId);
                }

                return totalAmount;
        }
        
        
        private List<Attribute> getAttributesAndSetUdfs(long txnId) throws TransactionServiceException, TException{
                StringBuilder orderDetails = new StringBuilder();
                StringBuilder billingAddress = new StringBuilder();
                String email = "";
                String contactNumber = "";
                
                //get udfs
                Transaction transaction;
                TransactionServiceClient transactionServiceClient = null;
                try {
                        transactionServiceClient = new TransactionServiceClient();
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                
                in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
                transaction = txnClient.getTransaction(txnId);
                orderDetails.append(transaction.getOrdersSize() + " ");
                for (Order order : transaction.getOrders()) {
                        contactNumber= order.getCustomer_mobilenumber();
                        email = order.getCustomer_email();
                        billingAddress.append(" ");
                        if(order.getCustomer_pincode()!=null){
                                billingAddress.append(order.getCustomer_pincode());
                        }
                        if(order.getCustomer_city()!=null){
                                billingAddress.append(" " + order.getCustomer_city());
                        }
                        if(order.getCustomer_address1()!=null){
                                billingAddress.append(" " + order.getCustomer_address1());
                        }
                        if(order.getCustomer_address2()!=null){
                                billingAddress.append(" " + order.getCustomer_address2());
                        }
                        if(order.getCustomer_state()!=null){
                                billingAddress.append(" " + order.getCustomer_state());
                        }
                        

                        for(LineItem line: order.getLineitems()){
                                if(line.getBrand() != null){
                                        orderDetails.append(line.getBrand());
                                }
                                if(line.getModel_name() != null){
                                        orderDetails.append(line.getModel_name()); 
                                }
                                if(line.getModel_number() != null){
                                        orderDetails.append(line.getModel_number());
                                }
                                if(line.getColor() != null){
                                        orderDetails.append(line.getColor());
                                }
                                orderDetails.append(" ");
                        }
                        
                }
                
                Random random = new Random();
                String merchantInfo = ""+random.nextLong(); 
                
            String udf1 = formatUdf(orderDetails.toString()); 
            String udf2 = formatUdf(email);
            String udf3 = formatUdf(contactNumber);
            String udf4 = formatUdf(billingAddress.toString());
            String udf5 = merchantInfo;

            log.info("udf1:"  + udf1);
            log.info("udf2:"  + udf2);
            log.info("udf3:"  + udf3);
            log.info("udf4:"  + udf4);
            log.info("udf5:"  + udf5);
            

            pipe.setUdf1(udf1);       //        UDF 1 - Order details
                pipe.setUdf2(udf2);                                             //      UDF 2 - Email ID
                pipe.setUdf3(udf3);                             //      UDF 3 - Contact Number. 
                pipe.setUdf4(udf4);     //      UDF 4 - Billing Address
                pipe.setUdf5(udf5);                                                             //      UDF 5 - Merchant specific
            
                List<Attribute> attributes = new ArrayList<Attribute>();
                Attribute attribute1 = new Attribute("udf1",udf1);
                Attribute attribute2 = new Attribute("udf2",udf2);
                Attribute attribute3 = new Attribute("udf3",udf3);
                Attribute attribute4 = new Attribute("udf4",udf4);
                Attribute attribute5 = new Attribute("udf5",udf5);
                
                attributes.add(attribute1);
                attributes.add(attribute2);
                attributes.add(attribute3);
                attributes.add(attribute4);
                attributes.add(attribute5);
                
                return attributes;
        }

        
        
        private void initializePayment(String merchantPaymentId) throws ShoppingCartException, TException{
                String amount;
                
                amount = (new Double(getPaymentAmount(userinfo.getCartId()))).toString();
                
                //Following is the code which initilize e24PaymentPipe with proper value                
                pipe=new e24PaymentPipe();
                pipe.setResourcePath(resourceFilePath); //mandatory 
                String as = pipe.getResourcePath();
                log.info("Resource= " +as);
                
                pipe.setAlias(aliasName);                       //mandatory 
                String ab=pipe.getAlias();
                log.info("Alias= " +ab);
        
                pipe.setAction(ActionType.PURCHASE.value());                    //mandatory 
                String ac=pipe.getAction();
                log.info("Action= " +ac);
        
                pipe.setResponseURL( responseURL );     //mandatory
                String at=pipe.getResponseURL();
                log.info("ResponseURL= "+at);
        
                //pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );             //mandatory
                pipe.setErrorURL( errorURL);
            String ak=pipe.getErrorURL();
            log.info("ErrorURL= " + ak);
        
        
                pipe.setAmt(amount);            
                String ap=pipe.getAmt();
                log.info("Amt= " + ap);
        
                pipe.setCurrency("356");
                String a=pipe.getCurrency();
                log.info("Currency= " + a);
        
                pipe.setLanguage("USA");
                String p=pipe.getLanguage();
                log.info("Language= "+ p);
            
                pipe.setTrackId(merchantPaymentId);
        
        }
        
        String formatUdf(String udfString){
                udfString = udfString.replaceAll(regex, replacement);
                if(udfString.length() > MAX_UDF_LENGTH){
                        udfString = udfString.substring(0, MAX_UDF_LENGTH);
                }
                return udfString;
        }

}