Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.serving.services;

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

import org.apache.log4j.Logger;
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.ShoppingCartException;
import in.shop2020.payments.Attribute;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.thrift.clients.PaymentServiceClient;
import in.shop2020.thrift.clients.TransactionServiceClient;
import in.shop2020.thrift.clients.config.ConfigClient;



import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;

public class HdfcPaymentService implements IPaymentService {
        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 double amount;
        private int gatewayId=1;
        
        private long paymentId;
        
        private enum ActionType{
                PURCHASE("1"),
                AUTH ("4");
                private String value;
                ActionType(String value) {
                        this.value = value;
                }
                public String value(){
                        return this.value;
                }
        }
        
        public HdfcPaymentService() {
        
        }
        
        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 long createPayment(long currentCartId, long userId, long txnId, String paymentOption){
                log.info("Creating payment for the txn#: " + txnId + " for the user: " + userId + " for processing through HDFC");
                CommonPaymentService cps = new CommonPaymentService();
                if(!cps.createPayment(currentCartId, userId, txnId, gatewayId)){
                        log.error("Error while creating the basic payment");
                        return PAYMENT_NOT_CREATED;
                }
                
                paymentId = cps.getPaymentId();
                amount = cps.getAmount();
                
                try {
                        initializePayment(paymentId, amount);
                } catch (ShoppingCartException e1) {
                        log.error("Error while creating hdfc payment.");
                        e1.printStackTrace();
                        return PAYMENT_NOT_CREATED;
                } catch (TException e1) {
                        log.error("Error while creating hdfc payment.");
                        e1.printStackTrace();
                        return PAYMENT_NOT_CREATED;
                }
                
                List<Attribute> attributes = null;
                try {
                        attributes = getAttributesAndSetUdfs(txnId);
                        attributes.add(new Attribute(IPaymentService.PAYMENT_METHOD, paymentOption));
                } catch (TransactionServiceException e1) {
                        log.error("Error while setting udfs to payment.");
                        e1.printStackTrace();
                        return PAYMENT_NOT_CREATED;
                } catch (TException e1) {
                        log.error("Error while setting udfs to payment.");
                        e1.printStackTrace();
                        return PAYMENT_NOT_CREATED;
                }
                
                PaymentServiceClient paymentServiceClient = null;
                try {
                        paymentServiceClient = new PaymentServiceClient();
                } catch (Exception e) {
                        log.error("Error while getting payment client");
                        e.printStackTrace();
                        return PAYMENT_NOT_CREATED;
                }
                
                try {
                        //TODO: Put this in a timed block.
                        short status = pipe.performPaymentInitialization();
                        if(status != e24PaymentPipe.SUCCESS) {
                                log.error("Error sending Payment Initialization Request: ");
                                paymentServiceClient.getClient().updatePaymentDetails(paymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
                                redirectURL = errorURL + "?paymentId="+ paymentId + "&ErrorText="+pipe.getErrorMsg();
                                return PAYMENT_NOT_CREATED;
                        }
                        else {
                                log.info("Payment Initialization Request processed successfully for payment Id: " + paymentId);
                                String paymentID = pipe.getPaymentId();
                                paymentServiceClient.getClient().updatePaymentDetails(paymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
                                
                                String payURL = pipe.getPaymentPage();
                                redirectURL = payURL + "?PaymentID=" + paymentID;
                                return paymentId;
                        }
                } 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="+paymentId + "?ErrorText=Error while initializing payment.";
                return PAYMENT_NOT_CREATED;
        }
        
        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(long merchantPaymentId, double amounta) throws ShoppingCartException, TException{
                String amount;
                
                amount = (new Double(amounta)).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((new Long(merchantPaymentId)).toString());
        
        }
        
        String formatUdf(String udfString){
                udfString = udfString.replaceAll(regex, replacement);
                if(udfString.length() > MAX_UDF_LENGTH){
                        udfString = udfString.substring(0, MAX_UDF_LENGTH);
                }
                return udfString;
        }
        
        public String getRedirectUrl(){
                return this.redirectURL;
        }

}