Subversion Repositories SmartDukaan

Rev

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