Subversion Repositories SmartDukaan

Rev

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