Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
3583 chandransh 1
package in.shop2020.payment.service.handler;
2
 
3
import in.shop2020.config.ConfigException;
4
import in.shop2020.model.v1.order.LineItem;
5
import in.shop2020.model.v1.order.Order;
6
import in.shop2020.model.v1.order.Transaction;
7
import in.shop2020.model.v1.order.TransactionServiceException;
8
import in.shop2020.model.v1.user.ShoppingCartException;
9
import in.shop2020.payment.domain.Payment;
10
import in.shop2020.payments.Attribute;
11
import in.shop2020.payments.PaymentException;
12
import in.shop2020.payments.PaymentStatus;
13
import in.shop2020.thrift.clients.TransactionClient;
14
import in.shop2020.thrift.clients.config.ConfigClient;
15
 
16
import java.util.ArrayList;
17
import java.util.HashMap;
18
import java.util.List;
19
import java.util.Map;
20
import java.util.Random;
21
 
22
import org.apache.log4j.Logger;
23
import org.apache.thrift.TException;
24
 
25
import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
26
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;
27
import com.aciworldwide.commerce.gateway.plugins.e24TranPipe;
28
 
29
public class HdfcEmiPaymentHandler implements IPaymentHandler {
4421 mandeep.dh 30
    private static final int CAPTURE_STATUS_FOR_CONNECTION_ISSUE = -1;
31
 
3583 chandransh 32
    private static Logger log = Logger.getLogger(HdfcEmiPaymentHandler.class);
4421 mandeep.dh 33
 
3583 chandransh 34
    private static String resourceFilePath;
35
    private static String aliasName;
36
    private static String responseURL;
37
    private static String errorURL;
38
    private static final String regex = "[^a-zA-Z0-9\\s\\-\\@\\/\\.]";
39
    private static final String replacement = " ";
40
    private static final int MAX_UDF_LENGTH = 30;
41
    private static final String currencyCode = "356";
42
 
43
    private enum ActionType{
44
        PURCHASE("1"),
45
        AUTH ("4"),
46
        CAPTURE("5");
47
        private String value;
48
        ActionType(String value) {
49
            this.value = value;
50
        }
51
        public String value(){
52
            return this.value;
53
        }
54
    }
55
 
56
    public HdfcEmiPaymentHandler() {
57
        // TODO Auto-generated constructor stub
58
    }
59
 
60
    static{
61
        try {
62
            resourceFilePath = ConfigClient.getClient().get("emi_payment_resource_file_path");
63
            aliasName  = ConfigClient.getClient().get("emi_payment_alias_name");
64
            responseURL = ConfigClient.getClient().get("emi_payment_response_url");
65
            errorURL = ConfigClient.getClient().get("emi_payment_error_url");
66
        } catch (ConfigException e) {
67
            log.error("Unable to get data from config server.");
68
        }
69
    }
70
 
71
    public static Map<String, String> capturePayment(Payment payment){
72
        String amount = "" + payment.getAmount();
73
        String gatewayPaymentId = payment.getGatewayPaymentId();
74
        log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
75
 
76
        //Prepare resultMap to elicit failure behaviour in case anything goes wrong.
77
        Map<String, String> resultMap = new HashMap<String, String>();
4421 mandeep.dh 78
        resultMap.put(STATUS, Errors.CAPTURE_FAILURE.code);
79
        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
80
        resultMap.put(ERROR, Errors.CAPTURE_FAILURE.message);
3583 chandransh 81
 
82
        e24TranPipe pipe = new e24TranPipe();
83
        pipe.setResourcePath(resourceFilePath);
84
        pipe.setAlias(aliasName);
85
        pipe.setAction(ActionType.CAPTURE.value());
86
        pipe.setAmt(amount);
87
        pipe.setTrackId("" + payment.getId());
88
        pipe.setMember("SAHOLIC");
89
        pipe.setCurrencyCode(currencyCode);
90
        pipe.setTransId(payment.getGatewayTxnId());
91
 
92
        //Check if the values have been set properly
93
        log.info("Pipe Amount: " + pipe.getAmt());
94
        log.info("Pipe Action Code: " + pipe.getAction());
95
        log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
96
        log.info("Pipe Track Id: " + pipe.getTrackId());
97
        log.info("Pipe Trans Id:" + pipe.getTransId());
98
 
99
        int captureStatus = e24TranPipe.FAILURE;
100
        try {
101
            captureStatus = pipe.performTransaction();
102
 
103
            log.info("Capture Status: " + captureStatus);
104
            log.info("Gateway Txn Status: " + pipe.getResult());
105
            log.info("Debug Msg: " + pipe.getDebugMsg());
106
            log.info("Auth: " + pipe.getAuth());
107
            log.info("Ref: " + pipe.getRef());
108
            log.info("TransId:" + pipe.getTransId());
109
            log.info("Amount: " + pipe.getAmt());
110
 
111
            resultMap.put(STATUS, "" + captureStatus);
112
            String result = pipe.getResult();
113
            resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());       //This will return the result of the transaction. (Successful or Failed)
114
            if(captureStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){
115
                resultMap.put(ERROR, pipe.getErrorMsg());               // In case of any error, we only need to get the error message
4421 mandeep.dh 116
 
117
                if (captureStatus == CAPTURE_STATUS_FOR_CONNECTION_ISSUE) {
118
                    resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
119
                }
120
            }
121
            else {
3583 chandransh 122
                resultMap.put(CAPTURE_AUTH_ID, pipe.getAuth());         // Unique ID generated by Authorizer of the transaction
123
                resultMap.put(CAPTURE_REF_ID, pipe.getRef());           // Unique reference number generated during the transaction
124
                resultMap.put(CAPTURE_TXN_ID, pipe.getTransId());       // Unique Transaction ID generated after every successful transaction
125
                resultMap.put(CAPTURE_AMNT, pipe.getAmt());         // Original Amount of the transaction
126
            }
127
        } catch (NotEnoughDataException e) {
4421 mandeep.dh 128
            log.error(Errors.CAPTURE_FAILURE.message, e);
129
            resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
130
            resultMap.put(ERROR, e.getMessage());
3583 chandransh 131
        }
132
 
133
        return resultMap;
134
    }
135
 
136
    public static String initializeHdfcPayment(Payment payment, PaymentServiceHandler handler) throws Exception{
137
        long merchantPaymentId = payment.getId();
138
        double amount = payment.getAmount();
139
        e24PaymentPipe pipe = new e24PaymentPipe();
140
 
141
        try {
142
            initializePayment(pipe, merchantPaymentId, amount);
143
        } catch (ShoppingCartException e1) {
144
            log.error("Error while creating hdfc payment.", e1);
145
            throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
146
        } catch (TException e1) {
147
            log.error("Error while creating hdfc payment.", e1);
148
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
149
        }
150
 
151
        List<Attribute> attributes = null;
152
        try {
153
            attributes = getAttributesAndSetUdfs(pipe, payment.getMerchantTxnId());
154
        } catch (TransactionServiceException e1) {
155
            log.error("Error while setting udfs to payment.", e1);
156
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
157
        } catch (TException e1) {
158
            log.error("Error while setting udfs to payment.", e1);
159
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
160
        }
161
 
162
        try {
163
            if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
164
                log.error("Error sending Payment Initialization Request: ");
165
                handler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
166
            } else {
167
                log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
168
                String paymentID = pipe.getPaymentId();
169
                handler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
170
 
171
                String payURL = pipe.getPaymentPage();
172
                return payURL + "?PaymentID=" + paymentID;
173
            }
174
        } catch (NotEnoughDataException e) {
175
            log.error("Error while initializing payment.", e);
176
        }catch (Exception e) {
177
            log.error("Error while initializing payment.", e);
178
        }
179
        //If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
180
        //Throw the exception so that any failovers can happen.
181
        throw new PaymentException(115, "Unable to initialize HDFC payment");
182
    }
183
 
184
    private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, long txnId) throws TransactionServiceException, TException{
185
        StringBuilder orderDetails = new StringBuilder();
186
        StringBuilder billingAddress = new StringBuilder();
187
        String email = "";
188
        String contactNumber = "";
189
 
190
        //get udfs
191
        Transaction transaction;
192
        TransactionClient transactionServiceClient = null;
193
        try {
194
            transactionServiceClient = new TransactionClient();
195
        } catch (Exception e) {
196
            log.error("Unable to get transaction details", e);
197
        }
198
 
199
        in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
200
        transaction = txnClient.getTransaction(txnId);
201
        orderDetails.append(transaction.getOrdersSize() + " ");
202
        for (Order order : transaction.getOrders()) {
203
            contactNumber= order.getCustomer_mobilenumber();
204
            email = order.getCustomer_email();
205
            billingAddress.append(" ");
206
            if(order.getCustomer_pincode()!=null){
207
                billingAddress.append(order.getCustomer_pincode());
208
            }
209
            if(order.getCustomer_city()!=null){
210
                billingAddress.append(" " + order.getCustomer_city());
211
            }
212
            if(order.getCustomer_address1()!=null){
213
                billingAddress.append(" " + order.getCustomer_address1());
214
            }
215
            if(order.getCustomer_address2()!=null){
216
                billingAddress.append(" " + order.getCustomer_address2());
217
            }
218
            if(order.getCustomer_state()!=null){
219
                billingAddress.append(" " + order.getCustomer_state());
220
            }
221
 
222
 
223
            for(LineItem line: order.getLineitems()){
224
                if(line.getBrand() != null){
225
                    orderDetails.append(line.getBrand());
226
                }
227
                if(line.getModel_name() != null){
228
                    orderDetails.append(line.getModel_name()); 
229
                }
230
                if(line.getModel_number() != null){
231
                    orderDetails.append(line.getModel_number());
232
                }
233
                if(line.getColor() != null){
234
                    orderDetails.append(line.getColor());
235
                }
236
                orderDetails.append(" ");
237
            }
238
 
239
        }
240
 
241
        Random random = new Random();
242
        String merchantInfo = ""+random.nextLong(); 
243
 
244
        String udf1 = formatUdf(orderDetails.toString()); 
245
        String udf2 = formatUdf(email);
246
        String udf3 = formatUdf(contactNumber);
247
        String udf4 = formatUdf(billingAddress.toString());
248
        String udf5 = merchantInfo;
249
 
250
        log.info("udf1:"  + udf1);
251
        log.info("udf2:"  + udf2);
252
        log.info("udf3:"  + udf3);
253
        log.info("udf4:"  + udf4);
254
        log.info("udf5:"  + udf5);
255
 
256
 
257
        pipe.setUdf1(udf1);      // UDF 1 - Order details
258
        pipe.setUdf2(udf2);      // UDF 2 - Email ID
259
        pipe.setUdf3(udf3);      // UDF 3 - Contact Number. 
260
        pipe.setUdf4(udf4);      // UDF 4 - Billing Address
261
        pipe.setUdf5(udf5);      // UDF 5 - Merchant specific
262
 
263
        List<Attribute> attributes = new ArrayList<Attribute>();
264
        Attribute attribute1 = new Attribute("udf1",udf1);
265
        Attribute attribute2 = new Attribute("udf2",udf2);
266
        Attribute attribute3 = new Attribute("udf3",udf3);
267
        Attribute attribute4 = new Attribute("udf4",udf4);
268
        Attribute attribute5 = new Attribute("udf5",udf5);
269
 
270
        attributes.add(attribute1);
271
        attributes.add(attribute2);
272
        attributes.add(attribute3);
273
        attributes.add(attribute4);
274
        attributes.add(attribute5);
275
 
276
        return attributes;
277
    }
278
 
279
    private static void initializePayment(e24PaymentPipe pipe, long merchantPaymentId, double amounta) throws ShoppingCartException, TException{
280
        String amount = (new Double(amounta)).toString();
281
 
282
        //Following is the code which initilize e24PaymentPipe with proper value
283
        pipe.setResourcePath(resourceFilePath); //mandatory 
284
        String as = pipe.getResourcePath();
285
        log.info("Resource= " +as);
286
 
287
        pipe.setAlias(aliasName);           //mandatory 
288
        String ab=pipe.getAlias();
289
        log.info("Alias= " +ab);
290
 
291
        pipe.setAction(ActionType.AUTH.value());            //mandatory 
292
        String ac=pipe.getAction();
293
        log.info("Action= " +ac);
294
 
295
        pipe.setResponseURL( responseURL ); //mandatory
296
        String at=pipe.getResponseURL();
297
        log.info("ResponseURL= "+at);
298
 
299
        //pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );     //mandatory
300
        pipe.setErrorURL( errorURL);
301
        String ak=pipe.getErrorURL();
302
        log.info("ErrorURL= " + ak);
303
 
304
 
305
        pipe.setAmt(amount);        
306
        String ap=pipe.getAmt();
307
        log.info("Amt= " + ap);
308
 
309
        pipe.setCurrency(currencyCode);
310
        String a=pipe.getCurrency();
311
        log.info("Currency= " + a);
312
 
313
        pipe.setLanguage("USA");
314
        String p=pipe.getLanguage();
315
        log.info("Language= "+ p);
316
 
317
        pipe.setTrackId((new Long(merchantPaymentId)).toString());
318
    }
319
 
320
    private static String formatUdf(String udfString){
321
        udfString = udfString.replaceAll(regex, replacement);
322
        if(udfString.length() > MAX_UDF_LENGTH){
323
            udfString = udfString.substring(0, MAX_UDF_LENGTH);
324
        }
325
        return udfString;
326
    }
327
}