Subversion Repositories SmartDukaan

Rev

Rev 6503 | Rev 8914 | 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
 
8907 rajveer 240
	public static boolean validateHdfcPayment(Payment payment, double amount){
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)
277
			if ((""+refundStatus).trim().equals("0") && HdfcPaymentReturnStatus.SUCCESS.value().equals(gatewayStatus)) {
278
				return true;
279
			}
280
			else {
281
				return false;
282
			}
283
		} catch (NotEnoughDataException e) {
284
            log.error(Errors.CAPTURE_FAILURE.message, e);
285
		}	
286
		return false;
287
	}
288
 
2391 chandransh 289
	public static String initializeHdfcPayment(Payment payment, PaymentServiceHandler handler) throws Exception{
290
		long merchantPaymentId = payment.getId();
291
		double amount = payment.getAmount();
292
		e24PaymentPipe pipe = new e24PaymentPipe();
293
 
294
		try {
6050 anupam.sin 295
			initializePayment(pipe, merchantPaymentId, amount, false);
2391 chandransh 296
		} catch (ShoppingCartException e1) {
297
			log.error("Error while creating hdfc payment.", e1);
298
			throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
299
		} catch (TException e1) {
300
			log.error("Error while creating hdfc payment.", e1);
301
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
302
		}
303
 
304
		List<Attribute> attributes = null;
305
		try {
306
			attributes = getAttributesAndSetUdfs(pipe, payment.getMerchantTxnId());
307
		} catch (TransactionServiceException e1) {
308
			log.error("Error while setting udfs to payment.", e1);
309
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
310
		} catch (TException e1) {
311
			log.error("Error while setting udfs to payment.", e1);
312
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
313
		}
314
 
315
		try {
316
			if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
317
				log.error("Error sending Payment Initialization Request: ");
318
				handler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
319
			} else {
320
				log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
321
				String paymentID = pipe.getPaymentId();
322
				handler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
323
 
324
				String payURL = pipe.getPaymentPage();
3046 chandransh 325
				return payURL + "?PaymentID=" + paymentID;
2391 chandransh 326
			}
327
		} catch (NotEnoughDataException e) {
328
			log.error("Error while initializing payment.", e);
329
		}catch (Exception e) {
330
			log.error("Error while initializing payment.", e);
331
		}
3046 chandransh 332
		//If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
333
		//Throw the exception so that any failovers can happen.
334
		throw new PaymentException(115, "Unable to initialize HDFC payment");
2391 chandransh 335
	}
336
 
337
	private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, long txnId) throws TransactionServiceException, TException{
338
		StringBuilder orderDetails = new StringBuilder();
339
		StringBuilder billingAddress = new StringBuilder();
340
		String email = "";
341
		String contactNumber = "";
342
 
343
		//get udfs
344
		Transaction transaction;
3128 rajveer 345
		TransactionClient transactionServiceClient = null;
2391 chandransh 346
		try {
3128 rajveer 347
			transactionServiceClient = new TransactionClient();
2391 chandransh 348
		} catch (Exception e) {
349
			log.error("Unable to get transaction details", e);
350
		}
351
 
352
		in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
353
		transaction = txnClient.getTransaction(txnId);
354
		orderDetails.append(transaction.getOrdersSize() + " ");
355
		for (Order order : transaction.getOrders()) {
356
			contactNumber= order.getCustomer_mobilenumber();
357
			email = order.getCustomer_email();
358
			billingAddress.append(" ");
359
			if(order.getCustomer_pincode()!=null){
360
				billingAddress.append(order.getCustomer_pincode());
361
			}
362
			if(order.getCustomer_city()!=null){
363
				billingAddress.append(" " + order.getCustomer_city());
364
			}
365
			if(order.getCustomer_address1()!=null){
366
				billingAddress.append(" " + order.getCustomer_address1());
367
			}
368
			if(order.getCustomer_address2()!=null){
369
				billingAddress.append(" " + order.getCustomer_address2());
370
			}
371
			if(order.getCustomer_state()!=null){
372
				billingAddress.append(" " + order.getCustomer_state());
373
			}
374
 
375
 
376
			for(LineItem line: order.getLineitems()){
377
				if(line.getBrand() != null){
378
					orderDetails.append(line.getBrand());
379
				}
380
				if(line.getModel_name() != null){
381
					orderDetails.append(line.getModel_name()); 
382
				}
383
				if(line.getModel_number() != null){
384
					orderDetails.append(line.getModel_number());
385
				}
386
				if(line.getColor() != null){
387
					orderDetails.append(line.getColor());
388
				}
389
				orderDetails.append(" ");
390
			}
391
 
392
		}
393
 
394
		Random random = new Random();
395
		String merchantInfo = ""+random.nextLong(); 
396
 
397
	    String udf1 = formatUdf(orderDetails.toString()); 
398
	    String udf2 = formatUdf(email);
399
	    String udf3 = formatUdf(contactNumber);
400
	    String udf4 = formatUdf(billingAddress.toString());
401
	    String udf5 = merchantInfo;
402
 
403
	    log.info("udf1:"  + udf1);
404
	    log.info("udf2:"  + udf2);
405
	    log.info("udf3:"  + udf3);
406
	    log.info("udf4:"  + udf4);
407
	    log.info("udf5:"  + udf5);
408
 
409
 
410
	    pipe.setUdf1(udf1);      //	UDF 1 - Order details
411
		pipe.setUdf2(udf2);      //	UDF 2 - Email ID
412
		pipe.setUdf3(udf3);      //	UDF 3 - Contact Number. 
413
		pipe.setUdf4(udf4);      //	UDF 4 - Billing Address
414
		pipe.setUdf5(udf5);		 //	UDF 5 - Merchant specific
415
 
416
		List<Attribute> attributes = new ArrayList<Attribute>();
417
		Attribute attribute1 = new Attribute("udf1",udf1);
418
		Attribute attribute2 = new Attribute("udf2",udf2);
419
		Attribute attribute3 = new Attribute("udf3",udf3);
420
		Attribute attribute4 = new Attribute("udf4",udf4);
421
		Attribute attribute5 = new Attribute("udf5",udf5);
422
 
423
		attributes.add(attribute1);
424
		attributes.add(attribute2);
425
		attributes.add(attribute3);
426
		attributes.add(attribute4);
427
		attributes.add(attribute5);
428
 
429
		return attributes;
430
	}
431
 
6050 anupam.sin 432
	private static void initializePayment(e24PaymentPipe pipe, long merchantPaymentId, double amounta, boolean isDigital) throws ShoppingCartException, TException{
2391 chandransh 433
		String amount = (new Double(amounta)).toString();
434
 
435
		//Following is the code which initilize e24PaymentPipe with proper value
4641 rajveer 436
		pipe.setResourcePath(resourceDirPath);	//mandatory 
2391 chandransh 437
		String as = pipe.getResourcePath();
438
		log.info("Resource= " +as);
439
 
440
		pipe.setAlias(aliasName);			//mandatory 
441
		String ab=pipe.getAlias();
442
		log.info("Alias= " +ab);
443
 
6091 anupam.sin 444
 
2391 chandransh 445
		String ac=pipe.getAction();
446
		log.info("Action= " +ac);
6050 anupam.sin 447
 
448
		if(isDigital) {
6091 anupam.sin 449
		    pipe.setAction(ActionType.PURCHASE.value());          //mandatory
6050 anupam.sin 450
		    pipe.setResponseURL( responseURLforRecharge );   //mandatory
451
		    pipe.setErrorURL( errorURLforRecharge); //mandatory
452
		} else {
6091 anupam.sin 453
		    pipe.setAction(ActionType.AUTH.value());          //mandatory
6050 anupam.sin 454
		    pipe.setResponseURL( responseURL );
455
		    pipe.setErrorURL( errorURL);
456
		}
2391 chandransh 457
		String at=pipe.getResponseURL();
458
		log.info("ResponseURL= "+at);
459
 
460
		//pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );		//mandatory
461
	    String ak=pipe.getErrorURL();
462
	    log.info("ErrorURL= " + ak);
463
 
464
 
465
		pipe.setAmt(amount);		
466
		String ap=pipe.getAmt();
467
		log.info("Amt= " + ap);
468
 
2761 chandransh 469
		pipe.setCurrency(currencyCode);
2391 chandransh 470
		String a=pipe.getCurrency();
471
		log.info("Currency= " + a);
472
 
473
		pipe.setLanguage("USA");
474
		String p=pipe.getLanguage();
475
		log.info("Language= "+ p);
476
 
477
		pipe.setTrackId((new Long(merchantPaymentId)).toString());
478
	}
479
 
480
	private static String formatUdf(String udfString){
481
		udfString = udfString.replaceAll(regex, replacement);
482
		if(udfString.length() > MAX_UDF_LENGTH){
483
			udfString = udfString.substring(0, MAX_UDF_LENGTH);
484
		}
485
		return udfString;
486
	}
6050 anupam.sin 487
 
488
    public static String initializeHdfcPayment(in.shop2020.payment.domain.Payment payment, RechargeOrder rechargeOrder,
6228 anupam.sin 489
            String phone, PaymentServiceHandler paymentServiceHandler) throws Exception {
6233 anupam.sin 490
        Long merchantPaymentId = payment.getId();
6050 anupam.sin 491
        double amount = payment.getAmount();
492
        e24PaymentPipe pipe = new e24PaymentPipe();
493
 
494
        try {
495
            initializePayment(pipe, merchantPaymentId, amount, true);
496
        } catch (ShoppingCartException e1) {
497
            log.error("Error while creating hdfc payment.", e1);
498
            throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
499
        } catch (TException e1) {
500
            log.error("Error while creating hdfc payment.", e1);
501
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
502
        }
503
 
504
        List<Attribute> attributes = null;
505
        try {
6233 anupam.sin 506
            attributes = getAttributesAndSetUdfs(pipe, rechargeOrder, merchantPaymentId.toString(), phone);
6050 anupam.sin 507
        } catch (TransactionServiceException e1) {
508
            log.error("Error while setting udfs to payment.", e1);
509
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
510
        } catch (TException e1) {
511
            log.error("Error while setting udfs to payment.", e1);
512
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
513
        }
514
 
515
        try {
516
            if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
517
                log.error("Error sending Payment Initialization Request: ");
518
                paymentServiceHandler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
519
            } else {
520
                log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
521
                String paymentID = pipe.getPaymentId();
522
                paymentServiceHandler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
523
 
524
                String payURL = pipe.getPaymentPage();
525
                return payURL + "?PaymentID=" + paymentID;
526
            }
527
        } catch (NotEnoughDataException e) {
528
            log.error("Error while initializing payment.", e);
529
        }catch (Exception e) {
530
            log.error("Error while initializing payment.", e);
531
        }
532
        //If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
533
        //Throw the exception so that any failovers can happen.
534
        throw new PaymentException(115, "Unable to initialize HDFC payment");
535
    }
536
 
6233 anupam.sin 537
    private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, RechargeOrder rechargeOrder, String merchantPaymentId, String phone) throws TransactionServiceException, TException {
6228 anupam.sin 538
 
6050 anupam.sin 539
        StringBuilder orderDetails = new StringBuilder();
540
        StringBuilder billingAddress = new StringBuilder();
541
        String email = "";
542
        String contactNumber = "";
6228 anupam.sin 543
        Address address = null;
6050 anupam.sin 544
        //get udfs
6233 anupam.sin 545
        if (!(phone == null) && !(phone.isEmpty())) {
6228 anupam.sin 546
            //Remember in RechargePaymentController we kept phone set only for a specific case.
6233 anupam.sin 547
            //This is the case where we don't need to get the address and can safely set the phone number only.
6228 anupam.sin 548
 
549
            contactNumber = phone;
550
            email = rechargeOrder.getUserEmailId();
551
            billingAddress.append(" ");
552
            billingAddress.append("110001");
553
            billingAddress.append(" " + "Delhi");//city
6233 anupam.sin 554
            billingAddress.append(" " + merchantPaymentId);//line1
555
            billingAddress.append(" " + merchantPaymentId);//line2
556
            billingAddress.append(" " + merchantPaymentId);//state
6228 anupam.sin 557
        } else {
558
            try {
559
                UserClient userClient = new UserClient();
560
                address = userClient.getClient().getAddressById(userClient.getClient().getDefaultAddressId(rechargeOrder.getUserId()));
561
            } catch (Exception e) {
562
                log.error("Unable to get transaction details", e);
563
            }
564
 
565
 
566
            contactNumber= address.getPhone();
567
            email = rechargeOrder.getUserEmailId();
568
            billingAddress.append(" ");
569
            if(address.getPin()!=null){
570
                billingAddress.append(address.getPin());
571
            }
572
            if(address.getCity()!=null){
573
                billingAddress.append(" " + address.getCity());
574
            }
575
            if(address.getLine1()!=null){
576
                billingAddress.append(" " + address.getLine1());
577
            }
578
            if(address.getLine2()!=null){
579
                billingAddress.append(" " + address.getLine2());
580
            }
581
            if(address.getState()!=null){
582
                billingAddress.append(" " + address.getState());
583
            }
584
 
6050 anupam.sin 585
        }
586
        orderDetails.append("Recharge : " + rechargeOrder.getDisplayId());
587
        orderDetails.append(" ");
588
 
589
        Random random = new Random();
590
        String merchantInfo = ""+random.nextLong(); 
591
 
592
        String udf1 = formatUdf(orderDetails.toString()); 
593
        String udf2 = formatUdf(email);
594
        String udf3 = formatUdf(contactNumber);
595
        String udf4 = formatUdf(billingAddress.toString());
596
        String udf5 = merchantInfo;
597
 
598
        log.info("udf1:"  + udf1);
599
        log.info("udf2:"  + udf2);
600
        log.info("udf3:"  + udf3);
601
        log.info("udf4:"  + udf4);
602
        log.info("udf5:"  + udf5);
603
 
604
 
605
        pipe.setUdf1(udf1);      // UDF 1 - Order details
606
        pipe.setUdf2(udf2);      // UDF 2 - Email ID
607
        pipe.setUdf3(udf3);      // UDF 3 - Contact Number. 
608
        pipe.setUdf4(udf4);      // UDF 4 - Billing Address
609
        pipe.setUdf5(udf5);      // UDF 5 - Merchant specific
610
 
611
        List<Attribute> attributes = new ArrayList<Attribute>();
612
        Attribute attribute1 = new Attribute("udf1",udf1);
613
        Attribute attribute2 = new Attribute("udf2",udf2);
614
        Attribute attribute3 = new Attribute("udf3",udf3);
615
        Attribute attribute4 = new Attribute("udf4",udf4);
616
        Attribute attribute5 = new Attribute("udf5",udf5);
617
 
618
        attributes.add(attribute1);
619
        attributes.add(attribute2);
620
        attributes.add(attribute3);
621
        attributes.add(attribute4);
622
        attributes.add(attribute5);
623
 
624
        return attributes;
625
    }
2391 chandransh 626
}