Subversion Repositories SmartDukaan

Rev

Rev 6503 | 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
 
4641 rajveer 16
import java.io.File;
17
import java.io.FileNotFoundException;
18
import java.io.FileOutputStream;
19
import java.io.IOException;
20
import java.io.InputStream;
21
import java.io.OutputStream;
3583 chandransh 22
import java.util.ArrayList;
23
import java.util.HashMap;
24
import java.util.List;
25
import java.util.Map;
26
import java.util.Random;
27
 
28
import org.apache.log4j.Logger;
29
import org.apache.thrift.TException;
30
 
31
import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
32
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;
33
import com.aciworldwide.commerce.gateway.plugins.e24TranPipe;
34
 
35
public class HdfcEmiPaymentHandler implements IPaymentHandler {
4421 mandeep.dh 36
    private static final int CAPTURE_STATUS_FOR_CONNECTION_ISSUE = -1;
37
 
3583 chandransh 38
    private static Logger log = Logger.getLogger(HdfcEmiPaymentHandler.class);
4421 mandeep.dh 39
 
3583 chandransh 40
    private static String responseURL;
41
    private static String errorURL;
42
    private static final String regex = "[^a-zA-Z0-9\\s\\-\\@\\/\\.]";
43
    private static final String replacement = " ";
44
    private static final int MAX_UDF_LENGTH = 30;
45
    private static final String currencyCode = "356";
4641 rajveer 46
	private static final String resourceFileName = "resource.cgn";
6401 rajveer 47
 
3583 chandransh 48
    private enum ActionType{
49
        PURCHASE("1"),
6491 rajveer 50
        REFUND ("2"),
3583 chandransh 51
        AUTH ("4"),
52
        CAPTURE("5");
53
        private String value;
54
        ActionType(String value) {
55
            this.value = value;
56
        }
57
        public String value(){
58
            return this.value;
59
        }
60
    }
61
 
62
    public HdfcEmiPaymentHandler() {
63
        // TODO Auto-generated constructor stub
64
    }
65
 
66
    static{
6420 rajveer 67
    	File resourceBaseDir = new File("/tmp/emi-resource/");
68
    	if(!resourceBaseDir.exists()){
69
    		resourceBaseDir.mkdir();
70
		}
6983 rajveer 71
    	int []  gatewayIds = {5,10,11,12,14};
6401 rajveer 72
    	for(int gatewayId: gatewayIds){
73
    		String resourceDirPath = "/tmp/emi-resource/" + gatewayId + "/";
74
	        try {
6402 rajveer 75
				InputStream inputStream = Class.class.getResourceAsStream(ConfigClient.getClient().get("emi_payment_resource_file_path") + gatewayId + File.separator + resourceFileName);
6401 rajveer 76
				File resourceDir = new File(resourceDirPath);
77
				if(!resourceDir.exists()){
78
					resourceDir.mkdir();
79
				}
80
 
81
				OutputStream outStream = new FileOutputStream(resourceDirPath  + resourceFileName);
82
				byte buf[]=new byte[1024];
83
				int len;
84
				while((len=inputStream.read(buf))>0)
85
					outStream.write(buf,0,len);
86
				outStream.close();
87
				inputStream.close();
88
 
89
				responseURL = ConfigClient.getClient().get("emi_payment_response_url");
90
	            errorURL = ConfigClient.getClient().get("emi_payment_error_url");
91
	        } catch (ConfigException e) {
92
	            log.error("Unable to get data from config server.");
93
	        } catch (FileNotFoundException e) {
94
				// TODO Auto-generated catch block
95
				e.printStackTrace();
96
			} catch (IOException e) {
97
				// TODO Auto-generated catch block
98
				e.printStackTrace();
4641 rajveer 99
			}
6401 rajveer 100
    	}
3583 chandransh 101
    }
102
 
103
    public static Map<String, String> capturePayment(Payment payment){
104
        String amount = "" + payment.getAmount();
105
        String gatewayPaymentId = payment.getGatewayPaymentId();
106
        log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
107
 
6401 rajveer 108
        String aliasName = null;
109
		try {
110
			aliasName = ConfigClient.getClient().get("emi_payment_alias_name" + payment.getGatewayId());
111
		} catch (ConfigException e1) {
112
			e1.printStackTrace();
113
		}
114
		String resourceDirPath = "/tmp/emi-resource/" + payment.getGatewayId() + "/";
115
 
3583 chandransh 116
        //Prepare resultMap to elicit failure behaviour in case anything goes wrong.
117
        Map<String, String> resultMap = new HashMap<String, String>();
4421 mandeep.dh 118
        resultMap.put(STATUS, Errors.CAPTURE_FAILURE.code);
119
        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
120
        resultMap.put(ERROR, Errors.CAPTURE_FAILURE.message);
3583 chandransh 121
 
122
        e24TranPipe pipe = new e24TranPipe();
4641 rajveer 123
        pipe.setResourcePath(resourceDirPath);
3583 chandransh 124
        pipe.setAlias(aliasName);
125
        pipe.setAction(ActionType.CAPTURE.value());
126
        pipe.setAmt(amount);
127
        pipe.setTrackId("" + payment.getId());
128
        pipe.setMember("SAHOLIC");
129
        pipe.setCurrencyCode(currencyCode);
130
        pipe.setTransId(payment.getGatewayTxnId());
131
 
132
        //Check if the values have been set properly
133
        log.info("Pipe Amount: " + pipe.getAmt());
134
        log.info("Pipe Action Code: " + pipe.getAction());
135
        log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
136
        log.info("Pipe Track Id: " + pipe.getTrackId());
137
        log.info("Pipe Trans Id:" + pipe.getTransId());
138
 
139
        int captureStatus = e24TranPipe.FAILURE;
140
        try {
141
            captureStatus = pipe.performTransaction();
142
 
143
            log.info("Capture Status: " + captureStatus);
144
            log.info("Gateway Txn Status: " + pipe.getResult());
145
            log.info("Debug Msg: " + pipe.getDebugMsg());
146
            log.info("Auth: " + pipe.getAuth());
147
            log.info("Ref: " + pipe.getRef());
148
            log.info("TransId:" + pipe.getTransId());
149
            log.info("Amount: " + pipe.getAmt());
150
 
151
            resultMap.put(STATUS, "" + captureStatus);
152
            String result = pipe.getResult();
153
            resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());       //This will return the result of the transaction. (Successful or Failed)
154
            if(captureStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){
155
                resultMap.put(ERROR, pipe.getErrorMsg());               // In case of any error, we only need to get the error message
4421 mandeep.dh 156
 
157
                if (captureStatus == CAPTURE_STATUS_FOR_CONNECTION_ISSUE) {
158
                    resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
159
                }
160
            }
161
            else {
3583 chandransh 162
                resultMap.put(CAPTURE_AUTH_ID, pipe.getAuth());         // Unique ID generated by Authorizer of the transaction
163
                resultMap.put(CAPTURE_REF_ID, pipe.getRef());           // Unique reference number generated during the transaction
164
                resultMap.put(CAPTURE_TXN_ID, pipe.getTransId());       // Unique Transaction ID generated after every successful transaction
165
                resultMap.put(CAPTURE_AMNT, pipe.getAmt());         // Original Amount of the transaction
166
            }
167
        } catch (NotEnoughDataException e) {
4421 mandeep.dh 168
            log.error(Errors.CAPTURE_FAILURE.message, e);
169
            resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
170
            resultMap.put(ERROR, e.getMessage());
3583 chandransh 171
        }
172
 
173
        return resultMap;
174
    }
175
 
6491 rajveer 176
    public static Map<String, String> refundPayment(Payment payment, double amount){
177
    	String ramount = "" + amount;
178
        String gatewayPaymentId = payment.getGatewayPaymentId();
179
        log.info("Refunding amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
180
 
181
        String aliasName = null;
182
		try {
183
			aliasName = ConfigClient.getClient().get("emi_payment_alias_name" + payment.getGatewayId());
184
		} catch (ConfigException e1) {
185
			e1.printStackTrace();
186
		}
187
		String resourceDirPath = "/tmp/emi-resource/" + payment.getGatewayId() + "/";
188
 
189
        //Prepare resultMap to elicit failure behaviour in case anything goes wrong.
190
        Map<String, String> resultMap = new HashMap<String, String>();
191
        resultMap.put(STATUS, Errors.CAPTURE_FAILURE.code);
192
        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
193
        resultMap.put(ERROR, Errors.CAPTURE_FAILURE.message);
194
 
195
        e24TranPipe pipe = new e24TranPipe();
196
        pipe.setResourcePath(resourceDirPath);
197
        pipe.setAlias(aliasName);
198
        pipe.setAction(ActionType.REFUND.value());
199
        pipe.setAmt(ramount);
200
        pipe.setTrackId("" + payment.getId());
201
        pipe.setMember("SAHOLIC");
202
        pipe.setCurrencyCode(currencyCode);
203
        pipe.setTransId(payment.getGatewayTxnId());
204
 
205
        //Check if the values have been set properly
206
        log.info("Pipe Amount: " + pipe.getAmt());
207
        log.info("Pipe Action Code: " + pipe.getAction());
208
        log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
209
        log.info("Pipe Track Id: " + pipe.getTrackId());
210
        log.info("Pipe Trans Id:" + pipe.getTransId());
211
 
212
        int refundStatus = e24TranPipe.FAILURE;
213
        try {
214
            refundStatus = pipe.performTransaction();
215
 
216
            log.info("Refund Status: " + refundStatus);
217
            log.info("Gateway Txn Status: " + pipe.getResult());
218
            log.info("Debug Msg: " + pipe.getDebugMsg());
219
            log.info("Auth: " + pipe.getAuth());
220
            log.info("Ref: " + pipe.getRef());
221
            log.info("TransId:" + pipe.getTransId());
222
            log.info("Amount: " + pipe.getAmt());
223
 
224
            resultMap.put(STATUS, "" + refundStatus);
225
            String result = pipe.getResult();
226
            resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());       //This will return the result of the transaction. (Successful or Failed)
227
            if(refundStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){
228
                resultMap.put(ERROR, pipe.getErrorMsg());               // In case of any error, we only need to get the error message
229
 
230
                if (refundStatus == CAPTURE_STATUS_FOR_CONNECTION_ISSUE) {
231
                    resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
232
                }
233
            }
234
            else {
6503 rajveer 235
                resultMap.put(REFUND_AUTH_ID, pipe.getAuth());         // Unique ID generated by Authorizer of the transaction
236
                resultMap.put(REFUND_REF_ID, pipe.getRef());           // Unique reference number generated during the transaction
237
                resultMap.put(REFUND_TXN_ID, pipe.getTransId());       // Unique Transaction ID generated after every successful transaction
238
                resultMap.put(REFUND_AMNT, pipe.getAmt());         // Original Amount of the transaction
6491 rajveer 239
            }
240
        } catch (NotEnoughDataException e) {
241
            log.error(Errors.CAPTURE_FAILURE.message, e);
242
            resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
243
            resultMap.put(ERROR, e.getMessage());
244
        }
245
 
246
        return resultMap;
247
    }
248
 
249
 
3583 chandransh 250
    public static String initializeHdfcPayment(Payment payment, PaymentServiceHandler handler) throws Exception{
251
        long merchantPaymentId = payment.getId();
252
        double amount = payment.getAmount();
253
        e24PaymentPipe pipe = new e24PaymentPipe();
254
 
255
        try {
6401 rajveer 256
            initializePayment(pipe, merchantPaymentId, amount, payment.getGatewayId());
3583 chandransh 257
        } catch (ShoppingCartException e1) {
258
            log.error("Error while creating hdfc payment.", e1);
259
            throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
260
        } catch (TException e1) {
261
            log.error("Error while creating hdfc payment.", e1);
262
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
263
        }
264
 
265
        List<Attribute> attributes = null;
266
        try {
267
            attributes = getAttributesAndSetUdfs(pipe, payment.getMerchantTxnId());
268
        } catch (TransactionServiceException e1) {
269
            log.error("Error while setting udfs to payment.", e1);
270
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
271
        } catch (TException e1) {
272
            log.error("Error while setting udfs to payment.", e1);
273
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
274
        }
275
 
276
        try {
277
            if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
278
                log.error("Error sending Payment Initialization Request: ");
279
                handler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
280
            } else {
281
                log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
282
                String paymentID = pipe.getPaymentId();
283
                handler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
284
 
285
                String payURL = pipe.getPaymentPage();
286
                return payURL + "?PaymentID=" + paymentID;
287
            }
288
        } catch (NotEnoughDataException e) {
289
            log.error("Error while initializing payment.", e);
290
        }catch (Exception e) {
291
            log.error("Error while initializing payment.", e);
292
        }
293
        //If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
294
        //Throw the exception so that any failovers can happen.
295
        throw new PaymentException(115, "Unable to initialize HDFC payment");
296
    }
297
 
298
    private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, long txnId) throws TransactionServiceException, TException{
299
        StringBuilder orderDetails = new StringBuilder();
300
        StringBuilder billingAddress = new StringBuilder();
301
        String email = "";
302
        String contactNumber = "";
303
 
304
        //get udfs
305
        Transaction transaction;
306
        TransactionClient transactionServiceClient = null;
307
        try {
308
            transactionServiceClient = new TransactionClient();
309
        } catch (Exception e) {
310
            log.error("Unable to get transaction details", e);
311
        }
312
 
313
        in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
314
        transaction = txnClient.getTransaction(txnId);
315
        orderDetails.append(transaction.getOrdersSize() + " ");
316
        for (Order order : transaction.getOrders()) {
317
            contactNumber= order.getCustomer_mobilenumber();
318
            email = order.getCustomer_email();
319
            billingAddress.append(" ");
320
            if(order.getCustomer_pincode()!=null){
321
                billingAddress.append(order.getCustomer_pincode());
322
            }
323
            if(order.getCustomer_city()!=null){
324
                billingAddress.append(" " + order.getCustomer_city());
325
            }
326
            if(order.getCustomer_address1()!=null){
327
                billingAddress.append(" " + order.getCustomer_address1());
328
            }
329
            if(order.getCustomer_address2()!=null){
330
                billingAddress.append(" " + order.getCustomer_address2());
331
            }
332
            if(order.getCustomer_state()!=null){
333
                billingAddress.append(" " + order.getCustomer_state());
334
            }
335
 
336
 
337
            for(LineItem line: order.getLineitems()){
338
                if(line.getBrand() != null){
339
                    orderDetails.append(line.getBrand());
340
                }
341
                if(line.getModel_name() != null){
342
                    orderDetails.append(line.getModel_name()); 
343
                }
344
                if(line.getModel_number() != null){
345
                    orderDetails.append(line.getModel_number());
346
                }
347
                if(line.getColor() != null){
348
                    orderDetails.append(line.getColor());
349
                }
350
                orderDetails.append(" ");
351
            }
352
 
353
        }
354
 
355
        Random random = new Random();
356
        String merchantInfo = ""+random.nextLong(); 
357
 
358
        String udf1 = formatUdf(orderDetails.toString()); 
359
        String udf2 = formatUdf(email);
360
        String udf3 = formatUdf(contactNumber);
361
        String udf4 = formatUdf(billingAddress.toString());
362
        String udf5 = merchantInfo;
363
 
364
        log.info("udf1:"  + udf1);
365
        log.info("udf2:"  + udf2);
366
        log.info("udf3:"  + udf3);
367
        log.info("udf4:"  + udf4);
368
        log.info("udf5:"  + udf5);
369
 
370
 
371
        pipe.setUdf1(udf1);      // UDF 1 - Order details
372
        pipe.setUdf2(udf2);      // UDF 2 - Email ID
373
        pipe.setUdf3(udf3);      // UDF 3 - Contact Number. 
374
        pipe.setUdf4(udf4);      // UDF 4 - Billing Address
375
        pipe.setUdf5(udf5);      // UDF 5 - Merchant specific
376
 
377
        List<Attribute> attributes = new ArrayList<Attribute>();
378
        Attribute attribute1 = new Attribute("udf1",udf1);
379
        Attribute attribute2 = new Attribute("udf2",udf2);
380
        Attribute attribute3 = new Attribute("udf3",udf3);
381
        Attribute attribute4 = new Attribute("udf4",udf4);
382
        Attribute attribute5 = new Attribute("udf5",udf5);
383
 
384
        attributes.add(attribute1);
385
        attributes.add(attribute2);
386
        attributes.add(attribute3);
387
        attributes.add(attribute4);
388
        attributes.add(attribute5);
389
 
390
        return attributes;
391
    }
392
 
6401 rajveer 393
    private static void initializePayment(e24PaymentPipe pipe, long merchantPaymentId, double amounta, long gatewayId) throws ShoppingCartException, TException{
394
    	String aliasName = null;
395
		try {
396
			aliasName = ConfigClient.getClient().get("emi_payment_alias_name" + gatewayId);
397
		} catch (ConfigException e1) {
398
			e1.printStackTrace();
399
		}
400
		String resourceDirPath = "/tmp/emi-resource/" + gatewayId + "/";
3583 chandransh 401
        String amount = (new Double(amounta)).toString();
402
 
403
        //Following is the code which initilize e24PaymentPipe with proper value
4641 rajveer 404
        pipe.setResourcePath(resourceDirPath); //mandatory 
3583 chandransh 405
        String as = pipe.getResourcePath();
406
        log.info("Resource= " +as);
407
 
408
        pipe.setAlias(aliasName);           //mandatory 
409
        String ab=pipe.getAlias();
410
        log.info("Alias= " +ab);
411
 
412
        pipe.setAction(ActionType.AUTH.value());            //mandatory 
413
        String ac=pipe.getAction();
414
        log.info("Action= " +ac);
415
 
416
        pipe.setResponseURL( responseURL ); //mandatory
417
        String at=pipe.getResponseURL();
418
        log.info("ResponseURL= "+at);
419
 
420
        //pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );     //mandatory
421
        pipe.setErrorURL( errorURL);
422
        String ak=pipe.getErrorURL();
423
        log.info("ErrorURL= " + ak);
424
 
425
 
426
        pipe.setAmt(amount);        
427
        String ap=pipe.getAmt();
428
        log.info("Amt= " + ap);
429
 
430
        pipe.setCurrency(currencyCode);
431
        String a=pipe.getCurrency();
432
        log.info("Currency= " + a);
433
 
434
        pipe.setLanguage("USA");
435
        String p=pipe.getLanguage();
436
        log.info("Language= "+ p);
437
 
438
        pipe.setTrackId((new Long(merchantPaymentId)).toString());
439
    }
440
 
441
    private static String formatUdf(String udfString){
442
        udfString = udfString.replaceAll(regex, replacement);
443
        if(udfString.length() > MAX_UDF_LENGTH){
444
            udfString = udfString.substring(0, MAX_UDF_LENGTH);
445
        }
446
        return udfString;
447
    }
448
}