Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
2391 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;
6050 anupam.sin 6
import in.shop2020.model.v1.order.RechargeOrder;
2391 chandransh 7
import in.shop2020.model.v1.order.Transaction;
8
import in.shop2020.model.v1.order.TransactionServiceException;
6050 anupam.sin 9
import in.shop2020.model.v1.user.Address;
2391 chandransh 10
import in.shop2020.model.v1.user.ShoppingCartException;
11
import in.shop2020.payment.domain.Payment;
8907 rajveer 12
import in.shop2020.payment.service.handler.PaymentServiceHandler.HdfcPaymentReturnStatus;
2391 chandransh 13
import in.shop2020.payments.Attribute;
3046 chandransh 14
import in.shop2020.payments.PaymentException;
2391 chandransh 15
import in.shop2020.payments.PaymentStatus;
3128 rajveer 16
import in.shop2020.thrift.clients.TransactionClient;
6050 anupam.sin 17
import in.shop2020.thrift.clients.UserClient;
2391 chandransh 18
import in.shop2020.thrift.clients.config.ConfigClient;
19
 
4641 rajveer 20
import java.io.File;
21
import java.io.FileNotFoundException;
22
import java.io.FileOutputStream;
23
import java.io.IOException;
24
import java.io.InputStream;
25
import java.io.OutputStream;
2391 chandransh 26
import java.util.ArrayList;
27
import java.util.HashMap;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.Random;
31
 
32
import org.apache.log4j.Logger;
33
import org.apache.thrift.TException;
34
 
35
import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
36
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;
37
import com.aciworldwide.commerce.gateway.plugins.e24TranPipe;
38
 
3010 chandransh 39
public class HdfcPaymentHandler implements IPaymentHandler {
4421 mandeep.dh 40
	private static final int CAPTURE_STATUS_FOR_CONNECTION_ISSUE = -1;
41
 
42
    private static Logger log = Logger.getLogger(HdfcPaymentHandler.class);
2391 chandransh 43
 
44
	private static String aliasName;
45
	private static String responseURL;
46
	private static String errorURL;
47
	private static final String regex = "[^a-zA-Z0-9\\s\\-\\@\\/\\.]";
48
	private static final String replacement = " ";
49
	private static final int MAX_UDF_LENGTH = 30;
50
	private static final String currencyCode = "356";
4643 rajveer 51
	private static String resourceDirPath = "/tmp/resource/";
6050 anupam.sin 52
 
53
    private static String responseURLforRecharge;
54
 
55
    private static String errorURLforRecharge;
4641 rajveer 56
	private static final String resourceFileName = "resource.cgn";
2391 chandransh 57
 
58
	private enum ActionType{
59
		PURCHASE("1"),
6482 rajveer 60
		REFUND("2"),
2391 chandransh 61
		AUTH ("4"),
8907 rajveer 62
		CAPTURE("5"),
63
		INQUIRY("8");
2391 chandransh 64
		private String value;
65
		ActionType(String value) {
66
			this.value = value;
67
		}
68
		public String value(){
69
			return this.value;
70
		}
71
	}
72
 
73
	public HdfcPaymentHandler() {
74
		// TODO Auto-generated constructor stub
75
	}
76
 
77
	static{
78
		try {
4641 rajveer 79
			InputStream inputStream = Class.class.getResourceAsStream(ConfigClient.getClient().get("payment_resource_file_path") + resourceFileName);
80
			File resourceDir = new File(resourceDirPath);
81
			if(!resourceDir.exists()){
82
				resourceDir.mkdir();
83
			}
84
 
4643 rajveer 85
			OutputStream outStream = new FileOutputStream(resourceDirPath + resourceFileName);
4641 rajveer 86
			byte buf[]=new byte[1024];
87
			int len;
88
			while((len=inputStream.read(buf))>0)
89
				outStream.write(buf,0,len);
90
			outStream.close();
91
			inputStream.close();
92
 
4617 rajveer 93
	        aliasName  = ConfigClient.getClient().get("payment_alias_name");
2391 chandransh 94
			responseURL = ConfigClient.getClient().get("payment_response_url");
95
			errorURL = ConfigClient.getClient().get("payment_error_url");
6050 anupam.sin 96
			responseURLforRecharge = ConfigClient.getClient().get("payment_response_url_for_recharge");
97
			errorURLforRecharge = ConfigClient.getClient().get("recharge_success_url");
2391 chandransh 98
		} catch (ConfigException e) {
99
			log.error("Unable to get data from config server.");
4641 rajveer 100
		} catch (FileNotFoundException e) {
101
			// TODO Auto-generated catch block
102
			e.printStackTrace();
103
		} catch (IOException e) {
104
			// TODO Auto-generated catch block
105
			e.printStackTrace();
2391 chandransh 106
		}
107
	}
108
 
109
	public static Map<String, String> capturePayment(Payment payment){
110
		String amount = "" + payment.getAmount();
111
		String gatewayPaymentId = payment.getGatewayPaymentId();
112
		log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
113
 
114
		//Prepare resultMap to elicit failure behaviour in case anything goes wrong.
115
		Map<String, String> resultMap = new HashMap<String, String>();
4421 mandeep.dh 116
	    resultMap.put(STATUS, Errors.CAPTURE_FAILURE.code);
117
        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
118
        resultMap.put(ERROR, Errors.CAPTURE_FAILURE.message);
2391 chandransh 119
 
120
		e24TranPipe pipe = new e24TranPipe();
4641 rajveer 121
		pipe.setResourcePath(resourceDirPath);
2391 chandransh 122
		pipe.setAlias(aliasName);
123
		pipe.setAction(ActionType.CAPTURE.value());
124
		pipe.setAmt(amount);
125
		pipe.setTrackId("" + payment.getId());
126
		pipe.setMember("SAHOLIC");
127
		pipe.setCurrencyCode(currencyCode);
128
		pipe.setTransId(payment.getGatewayTxnId());
129
 
130
		//Check if the values have been set properly
131
		log.info("Pipe Amount: " + pipe.getAmt());
132
		log.info("Pipe Action Code: " + pipe.getAction());
133
		log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
134
		log.info("Pipe Track Id: " + pipe.getTrackId());
135
		log.info("Pipe Trans Id:" + pipe.getTransId());
136
 
137
		int captureStatus = e24TranPipe.FAILURE;
138
		try {
139
			captureStatus = pipe.performTransaction();
140
 
141
			log.info("Capture Status: " + captureStatus);
142
			log.info("Gateway Txn Status: " + pipe.getResult());
143
			log.info("Debug Msg: " + pipe.getDebugMsg());
144
			log.info("Auth: " + pipe.getAuth());
145
			log.info("Ref: " + pipe.getRef());
146
			log.info("TransId:" + pipe.getTransId());
147
			log.info("Amount: " + pipe.getAmt());
148
 
149
			resultMap.put(STATUS, "" + captureStatus);
150
			String result = pipe.getResult();
151
			resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());		//This will return the result of the transaction. (Successful or Failed)
152
			if(captureStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){
153
				resultMap.put(ERROR, pipe.getErrorMsg());				// In case of any error, we only need to get the error message
4421 mandeep.dh 154
 
155
				if (captureStatus == CAPTURE_STATUS_FOR_CONNECTION_ISSUE) {
156
	                resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
157
	            }
158
			}
159
			else {
2391 chandransh 160
				resultMap.put(CAPTURE_AUTH_ID, pipe.getAuth());			// Unique ID generated by Authorizer of the transaction
161
				resultMap.put(CAPTURE_REF_ID, pipe.getRef());			// Unique reference number generated during the transaction
162
				resultMap.put(CAPTURE_TXN_ID, pipe.getTransId());		// Unique Transaction ID generated after every successful transaction
163
				resultMap.put(CAPTURE_AMNT, pipe.getAmt());			// Original Amount of the transaction
164
			}
165
		} catch (NotEnoughDataException e) {
4421 mandeep.dh 166
            log.error(Errors.CAPTURE_FAILURE.message, e);
167
            resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
168
            resultMap.put(ERROR, e.getMessage());
2391 chandransh 169
		}
170
 
171
		return resultMap;
172
	}
173
 
6482 rajveer 174
	public static Map<String, String> refundPayment(Payment payment, double amount){
6489 rajveer 175
		String ramount = "" + amount;
6482 rajveer 176
		String gatewayPaymentId = payment.getGatewayPaymentId();
177
		log.info("Refunding amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
178
 
179
		//Prepare resultMap to elicit failure behaviour in case anything goes wrong.
180
		Map<String, String> resultMap = new HashMap<String, String>();
181
	    resultMap.put(STATUS, Errors.CAPTURE_FAILURE.code);
182
        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
183
        resultMap.put(ERROR, Errors.CAPTURE_FAILURE.message);
184
 
185
		e24TranPipe pipe = new e24TranPipe();
186
		pipe.setResourcePath(resourceDirPath);
187
		pipe.setAlias(aliasName);
188
		pipe.setAction(ActionType.REFUND.value());
189
		pipe.setAmt(ramount);
190
		pipe.setTrackId("" + payment.getId());
191
		pipe.setMember("SAHOLIC");
192
		pipe.setCurrencyCode(currencyCode);
193
		pipe.setTransId(payment.getGatewayTxnId());
194
 
195
		//Check if the values have been set properly
196
		log.info("Pipe Amount: " + pipe.getAmt());
197
		log.info("Pipe Action Code: " + pipe.getAction());
198
		log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
199
		log.info("Pipe Track Id: " + pipe.getTrackId());
200
		log.info("Pipe Trans Id:" + pipe.getTransId());
201
 
202
		int refundStatus = e24TranPipe.FAILURE;
203
		try {
204
			refundStatus = pipe.performTransaction();
205
 
206
			log.info("Refund Status: " + refundStatus);
207
			log.info("Gateway Txn Status: " + pipe.getResult());
208
			log.info("Debug Msg: " + pipe.getDebugMsg());
209
			log.info("Auth: " + pipe.getAuth());
210
			log.info("Ref: " + pipe.getRef());
211
			log.info("TransId:" + pipe.getTransId());
212
			log.info("Amount: " + pipe.getAmt());
213
 
214
			resultMap.put(STATUS, "" + refundStatus);
215
			String result = pipe.getResult();
216
			log.info("Result: " + pipe.getResult());
217
			resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());		//This will return the result of the transaction. (Successful or Failed)
218
			if(refundStatus != e24TranPipe.SUCCESS){
219
				resultMap.put(ERROR, pipe.getErrorMsg());				// In case of any error, we only need to get the error message
220
 
221
				if (refundStatus == CAPTURE_STATUS_FOR_CONNECTION_ISSUE) {
222
	                resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
223
	            }
224
			}
225
			else {
6503 rajveer 226
				resultMap.put(REFUND_AUTH_ID, pipe.getAuth());			// Unique ID generated by Authorizer of the transaction
227
				resultMap.put(REFUND_REF_ID, pipe.getRef());			// Unique reference number generated during the transaction
228
				resultMap.put(REFUND_TXN_ID, pipe.getTransId());		// Unique Transaction ID generated after every successful transaction
229
				resultMap.put(REFUND_AMNT, pipe.getAmt());			// Original Amount of the transaction
6482 rajveer 230
			}
231
		} catch (NotEnoughDataException e) {
232
            log.error(Errors.CAPTURE_FAILURE.message, e);
233
            resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
234
            resultMap.put(ERROR, e.getMessage());
235
		}
236
 
237
		return resultMap;
238
	}
239
 
8914 rajveer 240
	public static PaymentStatus validateHdfcPayment(Payment payment, double amount){
8907 rajveer 241
		String ramount = "" + amount;
242
		//String gatewayPaymentId = payment.getGatewayPaymentId();
243
 
244
		e24TranPipe pipe = new e24TranPipe();
245
		pipe.setResourcePath(resourceDirPath);
246
		pipe.setAlias(aliasName);
247
		pipe.setAction(ActionType.INQUIRY.value());
248
		pipe.setAmt(ramount);
249
		pipe.setTrackId("" + payment.getId());
250
		pipe.setMember("SAHOLIC");
251
		pipe.setCurrencyCode(currencyCode);
252
		pipe.setTransId(payment.getGatewayTxnId());
253
 
254
		//Check if the values have been set properly
255
		log.info("Pipe Amount: " + pipe.getAmt());
256
		log.info("Pipe Action Code: " + pipe.getAction());
257
		log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
258
		log.info("Pipe Track Id: " + pipe.getTrackId());
259
		log.info("Pipe Trans Id:" + pipe.getTransId());
260
 
261
		int refundStatus = e24TranPipe.FAILURE;
262
		String gatewayStatus = "";
263
		try {
264
			refundStatus = pipe.performTransaction();
265
 
266
			log.info("Inquiry Status: " + refundStatus);
267
			log.info("Gateway Txn Status: " + pipe.getResult());
268
			log.info("Debug Msg: " + pipe.getDebugMsg());
269
			log.info("Auth: " + pipe.getAuth());
270
			log.info("Ref: " + pipe.getRef());
271
			log.info("TransId:" + pipe.getTransId());
272
			log.info("Amount: " + pipe.getAmt());
273
 
274
			String result = pipe.getResult();
275
			log.info("Result: " + pipe.getResult());
276
			gatewayStatus = result.substring(0, Math.min(result.length(), 20)).trim();		//This will return the result of the transaction. (Successful or Failed)
8914 rajveer 277
 
278
			if ((""+refundStatus).trim().equals("0")) {
279
				if(HdfcPaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)){
280
					return PaymentStatus.SUCCESS;
281
				}
282
				if(HdfcPaymentReturnStatus.APPROVED.value().equals(gatewayStatus)){
283
					return PaymentStatus.AUTHORIZED;
284
				}
285
				if(HdfcPaymentReturnStatus.NOT_CAPTURED.value().equals(gatewayStatus)){
286
					return PaymentStatus.FAILED;
287
				}
288
				if(HdfcPaymentReturnStatus.NOT_APPROVED.value().equals(gatewayStatus)){
289
					return PaymentStatus.FAILED;
290
				}
8907 rajveer 291
			}
292
		} catch (NotEnoughDataException e) {
293
            log.error(Errors.CAPTURE_FAILURE.message, e);
294
		}	
8914 rajveer 295
		return PaymentStatus.INIT;
8907 rajveer 296
	}
297
 
2391 chandransh 298
	public static String initializeHdfcPayment(Payment payment, PaymentServiceHandler handler) throws Exception{
299
		long merchantPaymentId = payment.getId();
300
		double amount = payment.getAmount();
301
		e24PaymentPipe pipe = new e24PaymentPipe();
302
 
303
		try {
6050 anupam.sin 304
			initializePayment(pipe, merchantPaymentId, amount, false);
2391 chandransh 305
		} catch (ShoppingCartException e1) {
306
			log.error("Error while creating hdfc payment.", e1);
307
			throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
308
		} catch (TException e1) {
309
			log.error("Error while creating hdfc payment.", e1);
310
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
311
		}
312
 
313
		List<Attribute> attributes = null;
314
		try {
315
			attributes = getAttributesAndSetUdfs(pipe, payment.getMerchantTxnId());
316
		} catch (TransactionServiceException e1) {
317
			log.error("Error while setting udfs to payment.", e1);
318
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
319
		} catch (TException e1) {
320
			log.error("Error while setting udfs to payment.", e1);
321
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
322
		}
323
 
324
		try {
325
			if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
326
				log.error("Error sending Payment Initialization Request: ");
327
				handler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
328
			} else {
329
				log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
330
				String paymentID = pipe.getPaymentId();
331
				handler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
332
 
333
				String payURL = pipe.getPaymentPage();
3046 chandransh 334
				return payURL + "?PaymentID=" + paymentID;
2391 chandransh 335
			}
336
		} catch (NotEnoughDataException e) {
337
			log.error("Error while initializing payment.", e);
338
		}catch (Exception e) {
339
			log.error("Error while initializing payment.", e);
340
		}
3046 chandransh 341
		//If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
342
		//Throw the exception so that any failovers can happen.
343
		throw new PaymentException(115, "Unable to initialize HDFC payment");
2391 chandransh 344
	}
345
 
346
	private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, long txnId) throws TransactionServiceException, TException{
347
		StringBuilder orderDetails = new StringBuilder();
348
		StringBuilder billingAddress = new StringBuilder();
349
		String email = "";
350
		String contactNumber = "";
351
 
352
		//get udfs
353
		Transaction transaction;
3128 rajveer 354
		TransactionClient transactionServiceClient = null;
2391 chandransh 355
		try {
3128 rajveer 356
			transactionServiceClient = new TransactionClient();
2391 chandransh 357
		} catch (Exception e) {
358
			log.error("Unable to get transaction details", e);
359
		}
360
 
361
		in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
362
		transaction = txnClient.getTransaction(txnId);
363
		orderDetails.append(transaction.getOrdersSize() + " ");
364
		for (Order order : transaction.getOrders()) {
365
			contactNumber= order.getCustomer_mobilenumber();
366
			email = order.getCustomer_email();
367
			billingAddress.append(" ");
368
			if(order.getCustomer_pincode()!=null){
369
				billingAddress.append(order.getCustomer_pincode());
370
			}
371
			if(order.getCustomer_city()!=null){
372
				billingAddress.append(" " + order.getCustomer_city());
373
			}
374
			if(order.getCustomer_address1()!=null){
375
				billingAddress.append(" " + order.getCustomer_address1());
376
			}
377
			if(order.getCustomer_address2()!=null){
378
				billingAddress.append(" " + order.getCustomer_address2());
379
			}
380
			if(order.getCustomer_state()!=null){
381
				billingAddress.append(" " + order.getCustomer_state());
382
			}
383
 
384
 
385
			for(LineItem line: order.getLineitems()){
386
				if(line.getBrand() != null){
387
					orderDetails.append(line.getBrand());
388
				}
389
				if(line.getModel_name() != null){
390
					orderDetails.append(line.getModel_name()); 
391
				}
392
				if(line.getModel_number() != null){
393
					orderDetails.append(line.getModel_number());
394
				}
395
				if(line.getColor() != null){
396
					orderDetails.append(line.getColor());
397
				}
398
				orderDetails.append(" ");
399
			}
400
 
401
		}
402
 
403
		Random random = new Random();
404
		String merchantInfo = ""+random.nextLong(); 
405
 
406
	    String udf1 = formatUdf(orderDetails.toString()); 
407
	    String udf2 = formatUdf(email);
408
	    String udf3 = formatUdf(contactNumber);
409
	    String udf4 = formatUdf(billingAddress.toString());
410
	    String udf5 = merchantInfo;
411
 
412
	    log.info("udf1:"  + udf1);
413
	    log.info("udf2:"  + udf2);
414
	    log.info("udf3:"  + udf3);
415
	    log.info("udf4:"  + udf4);
416
	    log.info("udf5:"  + udf5);
417
 
418
 
419
	    pipe.setUdf1(udf1);      //	UDF 1 - Order details
420
		pipe.setUdf2(udf2);      //	UDF 2 - Email ID
421
		pipe.setUdf3(udf3);      //	UDF 3 - Contact Number. 
422
		pipe.setUdf4(udf4);      //	UDF 4 - Billing Address
423
		pipe.setUdf5(udf5);		 //	UDF 5 - Merchant specific
424
 
425
		List<Attribute> attributes = new ArrayList<Attribute>();
426
		Attribute attribute1 = new Attribute("udf1",udf1);
427
		Attribute attribute2 = new Attribute("udf2",udf2);
428
		Attribute attribute3 = new Attribute("udf3",udf3);
429
		Attribute attribute4 = new Attribute("udf4",udf4);
430
		Attribute attribute5 = new Attribute("udf5",udf5);
431
 
432
		attributes.add(attribute1);
433
		attributes.add(attribute2);
434
		attributes.add(attribute3);
435
		attributes.add(attribute4);
436
		attributes.add(attribute5);
437
 
438
		return attributes;
439
	}
440
 
6050 anupam.sin 441
	private static void initializePayment(e24PaymentPipe pipe, long merchantPaymentId, double amounta, boolean isDigital) throws ShoppingCartException, TException{
2391 chandransh 442
		String amount = (new Double(amounta)).toString();
443
 
444
		//Following is the code which initilize e24PaymentPipe with proper value
4641 rajveer 445
		pipe.setResourcePath(resourceDirPath);	//mandatory 
2391 chandransh 446
		String as = pipe.getResourcePath();
447
		log.info("Resource= " +as);
448
 
449
		pipe.setAlias(aliasName);			//mandatory 
450
		String ab=pipe.getAlias();
451
		log.info("Alias= " +ab);
452
 
6091 anupam.sin 453
 
2391 chandransh 454
		String ac=pipe.getAction();
455
		log.info("Action= " +ac);
6050 anupam.sin 456
 
457
		if(isDigital) {
6091 anupam.sin 458
		    pipe.setAction(ActionType.PURCHASE.value());          //mandatory
6050 anupam.sin 459
		    pipe.setResponseURL( responseURLforRecharge );   //mandatory
460
		    pipe.setErrorURL( errorURLforRecharge); //mandatory
461
		} else {
6091 anupam.sin 462
		    pipe.setAction(ActionType.AUTH.value());          //mandatory
6050 anupam.sin 463
		    pipe.setResponseURL( responseURL );
464
		    pipe.setErrorURL( errorURL);
465
		}
2391 chandransh 466
		String at=pipe.getResponseURL();
467
		log.info("ResponseURL= "+at);
468
 
469
		//pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );		//mandatory
470
	    String ak=pipe.getErrorURL();
471
	    log.info("ErrorURL= " + ak);
472
 
473
 
474
		pipe.setAmt(amount);		
475
		String ap=pipe.getAmt();
476
		log.info("Amt= " + ap);
477
 
2761 chandransh 478
		pipe.setCurrency(currencyCode);
2391 chandransh 479
		String a=pipe.getCurrency();
480
		log.info("Currency= " + a);
481
 
482
		pipe.setLanguage("USA");
483
		String p=pipe.getLanguage();
484
		log.info("Language= "+ p);
485
 
486
		pipe.setTrackId((new Long(merchantPaymentId)).toString());
487
	}
488
 
489
	private static String formatUdf(String udfString){
490
		udfString = udfString.replaceAll(regex, replacement);
491
		if(udfString.length() > MAX_UDF_LENGTH){
492
			udfString = udfString.substring(0, MAX_UDF_LENGTH);
493
		}
494
		return udfString;
495
	}
6050 anupam.sin 496
 
497
    public static String initializeHdfcPayment(in.shop2020.payment.domain.Payment payment, RechargeOrder rechargeOrder,
6228 anupam.sin 498
            String phone, PaymentServiceHandler paymentServiceHandler) throws Exception {
6233 anupam.sin 499
        Long merchantPaymentId = payment.getId();
6050 anupam.sin 500
        double amount = payment.getAmount();
501
        e24PaymentPipe pipe = new e24PaymentPipe();
502
 
503
        try {
504
            initializePayment(pipe, merchantPaymentId, amount, true);
505
        } catch (ShoppingCartException e1) {
506
            log.error("Error while creating hdfc payment.", e1);
507
            throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
508
        } catch (TException e1) {
509
            log.error("Error while creating hdfc payment.", e1);
510
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
511
        }
512
 
513
        List<Attribute> attributes = null;
514
        try {
6233 anupam.sin 515
            attributes = getAttributesAndSetUdfs(pipe, rechargeOrder, merchantPaymentId.toString(), phone);
6050 anupam.sin 516
        } catch (TransactionServiceException e1) {
517
            log.error("Error while setting udfs to payment.", e1);
518
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
519
        } catch (TException e1) {
520
            log.error("Error while setting udfs to payment.", e1);
521
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
522
        }
523
 
524
        try {
525
            if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
526
                log.error("Error sending Payment Initialization Request: ");
527
                paymentServiceHandler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
528
            } else {
529
                log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
530
                String paymentID = pipe.getPaymentId();
531
                paymentServiceHandler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
532
 
533
                String payURL = pipe.getPaymentPage();
534
                return payURL + "?PaymentID=" + paymentID;
535
            }
536
        } catch (NotEnoughDataException e) {
537
            log.error("Error while initializing payment.", e);
538
        }catch (Exception e) {
539
            log.error("Error while initializing payment.", e);
540
        }
541
        //If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
542
        //Throw the exception so that any failovers can happen.
543
        throw new PaymentException(115, "Unable to initialize HDFC payment");
544
    }
545
 
6233 anupam.sin 546
    private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, RechargeOrder rechargeOrder, String merchantPaymentId, String phone) throws TransactionServiceException, TException {
6228 anupam.sin 547
 
6050 anupam.sin 548
        StringBuilder orderDetails = new StringBuilder();
549
        StringBuilder billingAddress = new StringBuilder();
550
        String email = "";
551
        String contactNumber = "";
6228 anupam.sin 552
        Address address = null;
6050 anupam.sin 553
        //get udfs
6233 anupam.sin 554
        if (!(phone == null) && !(phone.isEmpty())) {
6228 anupam.sin 555
            //Remember in RechargePaymentController we kept phone set only for a specific case.
6233 anupam.sin 556
            //This is the case where we don't need to get the address and can safely set the phone number only.
6228 anupam.sin 557
 
558
            contactNumber = phone;
559
            email = rechargeOrder.getUserEmailId();
560
            billingAddress.append(" ");
561
            billingAddress.append("110001");
562
            billingAddress.append(" " + "Delhi");//city
6233 anupam.sin 563
            billingAddress.append(" " + merchantPaymentId);//line1
564
            billingAddress.append(" " + merchantPaymentId);//line2
565
            billingAddress.append(" " + merchantPaymentId);//state
6228 anupam.sin 566
        } else {
567
            try {
568
                UserClient userClient = new UserClient();
569
                address = userClient.getClient().getAddressById(userClient.getClient().getDefaultAddressId(rechargeOrder.getUserId()));
570
            } catch (Exception e) {
571
                log.error("Unable to get transaction details", e);
572
            }
573
 
574
 
575
            contactNumber= address.getPhone();
576
            email = rechargeOrder.getUserEmailId();
577
            billingAddress.append(" ");
578
            if(address.getPin()!=null){
579
                billingAddress.append(address.getPin());
580
            }
581
            if(address.getCity()!=null){
582
                billingAddress.append(" " + address.getCity());
583
            }
584
            if(address.getLine1()!=null){
585
                billingAddress.append(" " + address.getLine1());
586
            }
587
            if(address.getLine2()!=null){
588
                billingAddress.append(" " + address.getLine2());
589
            }
590
            if(address.getState()!=null){
591
                billingAddress.append(" " + address.getState());
592
            }
593
 
6050 anupam.sin 594
        }
595
        orderDetails.append("Recharge : " + rechargeOrder.getDisplayId());
596
        orderDetails.append(" ");
597
 
598
        Random random = new Random();
599
        String merchantInfo = ""+random.nextLong(); 
600
 
601
        String udf1 = formatUdf(orderDetails.toString()); 
602
        String udf2 = formatUdf(email);
603
        String udf3 = formatUdf(contactNumber);
604
        String udf4 = formatUdf(billingAddress.toString());
605
        String udf5 = merchantInfo;
606
 
607
        log.info("udf1:"  + udf1);
608
        log.info("udf2:"  + udf2);
609
        log.info("udf3:"  + udf3);
610
        log.info("udf4:"  + udf4);
611
        log.info("udf5:"  + udf5);
612
 
613
 
614
        pipe.setUdf1(udf1);      // UDF 1 - Order details
615
        pipe.setUdf2(udf2);      // UDF 2 - Email ID
616
        pipe.setUdf3(udf3);      // UDF 3 - Contact Number. 
617
        pipe.setUdf4(udf4);      // UDF 4 - Billing Address
618
        pipe.setUdf5(udf5);      // UDF 5 - Merchant specific
619
 
620
        List<Attribute> attributes = new ArrayList<Attribute>();
621
        Attribute attribute1 = new Attribute("udf1",udf1);
622
        Attribute attribute2 = new Attribute("udf2",udf2);
623
        Attribute attribute3 = new Attribute("udf3",udf3);
624
        Attribute attribute4 = new Attribute("udf4",udf4);
625
        Attribute attribute5 = new Attribute("udf5",udf5);
626
 
627
        attributes.add(attribute1);
628
        attributes.add(attribute2);
629
        attributes.add(attribute3);
630
        attributes.add(attribute4);
631
        attributes.add(attribute5);
632
 
633
        return attributes;
634
    }
2391 chandransh 635
}