Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
1318 rajveer 1
package in.shop2020.serving.services;
2
 
3
import java.util.ArrayList;
2334 chandransh 4
import java.util.HashMap;
1318 rajveer 5
import java.util.List;
2334 chandransh 6
import java.util.Map;
1318 rajveer 7
import java.util.Random;
8
 
9
import org.apache.log4j.Logger;
10
import org.apache.thrift.TException;
11
 
12
import in.shop2020.config.ConfigException;
13
import in.shop2020.model.v1.order.LineItem;
14
import in.shop2020.model.v1.order.Order;
15
import in.shop2020.model.v1.order.Transaction;
16
import in.shop2020.model.v1.order.TransactionServiceException;
17
import in.shop2020.model.v1.user.ShoppingCartException;
18
import in.shop2020.payments.Attribute;
2334 chandransh 19
import in.shop2020.payments.Payment;
1318 rajveer 20
import in.shop2020.payments.PaymentStatus;
2707 chandransh 21
import in.shop2020.payments.PaymentService.Client;
1318 rajveer 22
import in.shop2020.thrift.clients.PaymentServiceClient;
23
import in.shop2020.thrift.clients.TransactionServiceClient;
24
import in.shop2020.thrift.clients.config.ConfigClient;
25
 
26
import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
27
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;
2334 chandransh 28
import com.aciworldwide.commerce.gateway.plugins.e24TranPipe;
1318 rajveer 29
 
1905 chandransh 30
public class HdfcPaymentService implements IPaymentService {
1318 rajveer 31
	private static final long serialVersionUID = 1L;
32
	private static Logger log = Logger.getLogger(Class.class);
33
 
34
	private static String resourceFilePath;
35
	private static String aliasName;
36
	private static String responseURL;
37
	private static String errorURL;
38
	private static final String regex = "[^a-zA-Z0-9\\s\\-\\@\\/\\.]";
39
	private static final String replacement = " ";
40
	private static final int MAX_UDF_LENGTH = 30;
2334 chandransh 41
	private static final String currencyCode = "356";
1318 rajveer 42
	private String redirectURL;
43
	private e24PaymentPipe pipe = null;
44
 
45
	private double amount;
46
	private int gatewayId=1;
47
 
48
	private long paymentId;
49
 
50
	private enum ActionType{
51
		PURCHASE("1"),
2334 chandransh 52
		AUTH ("4"),
53
		CAPTURE("5");
1318 rajveer 54
		private String value;
55
		ActionType(String value) {
56
			this.value = value;
57
		}
58
		public String value(){
59
			return this.value;
60
		}
61
	}
62
 
63
	public HdfcPaymentService() {
64
 
65
	}
66
 
67
	static{
68
		try {
69
			resourceFilePath = ConfigClient.getClient().get("payment_resource_file_path");
70
			aliasName  = ConfigClient.getClient().get("payment_alias_name");
71
			responseURL = ConfigClient.getClient().get("payment_response_url");
72
			errorURL = ConfigClient.getClient().get("payment_error_url");
73
		} catch (ConfigException e) {
74
			log.error("Unable to get data from config server.");
75
		}
76
	}
77
 
78
 
2159 chandransh 79
	public long createPayment(long currentCartId, long userId, long txnId, String paymentOption){
2199 chandransh 80
		log.info("Creating payment for the txn#: " + txnId + " for the user: " + userId + " for processing through HDFC");
1905 chandransh 81
		CommonPaymentService cps = new CommonPaymentService();
82
		if(!cps.createPayment(currentCartId, userId, txnId, gatewayId)){
83
			log.error("Error while creating the basic payment");
84
			return PAYMENT_NOT_CREATED;
1318 rajveer 85
		}
86
 
1905 chandransh 87
		paymentId = cps.getPaymentId();
88
		amount = cps.getAmount();
1318 rajveer 89
 
90
		try {
1905 chandransh 91
			initializePayment(paymentId, amount);
1318 rajveer 92
		} catch (ShoppingCartException e1) {
93
			log.error("Error while creating hdfc payment.");
94
			e1.printStackTrace();
1905 chandransh 95
			return PAYMENT_NOT_CREATED;
1318 rajveer 96
		} catch (TException e1) {
97
			log.error("Error while creating hdfc payment.");
98
			e1.printStackTrace();
1905 chandransh 99
			return PAYMENT_NOT_CREATED;
1318 rajveer 100
		}
101
 
102
		List<Attribute> attributes = null;
103
		try {
104
			attributes = getAttributesAndSetUdfs(txnId);
2159 chandransh 105
			attributes.add(new Attribute(IPaymentService.PAYMENT_METHOD, paymentOption));
1318 rajveer 106
		} catch (TransactionServiceException e1) {
107
			log.error("Error while setting udfs to payment.");
108
			e1.printStackTrace();
1905 chandransh 109
			return PAYMENT_NOT_CREATED;
1318 rajveer 110
		} catch (TException e1) {
111
			log.error("Error while setting udfs to payment.");
112
			e1.printStackTrace();
1905 chandransh 113
			return PAYMENT_NOT_CREATED;
1318 rajveer 114
		}
115
 
1905 chandransh 116
		PaymentServiceClient paymentServiceClient = null;
117
		try {
118
			paymentServiceClient = new PaymentServiceClient();
119
		} catch (Exception e) {
120
			log.error("Error while getting payment client");
121
			e.printStackTrace();
122
			return PAYMENT_NOT_CREATED;
123
		}
1318 rajveer 124
 
125
		try {
2199 chandransh 126
			//TODO: Put this in a timed block.
127
			short status = pipe.performPaymentInitialization();
128
			if(status != e24PaymentPipe.SUCCESS) {
1905 chandransh 129
				log.error("Error sending Payment Initialization Request: ");
130
				paymentServiceClient.getClient().updatePaymentDetails(paymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
131
				redirectURL = errorURL + "?paymentId="+ paymentId + "&ErrorText="+pipe.getErrorMsg();
2199 chandransh 132
				return PAYMENT_NOT_CREATED;
2334 chandransh 133
			} else {
1905 chandransh 134
				log.info("Payment Initialization Request processed successfully for payment Id: " + paymentId);
135
				String paymentID = pipe.getPaymentId();
136
				paymentServiceClient.getClient().updatePaymentDetails(paymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
137
 
138
				String payURL = pipe.getPaymentPage();
139
				redirectURL = payURL + "?PaymentID=" + paymentID;
2199 chandransh 140
				return paymentId;
1905 chandransh 141
			}
1318 rajveer 142
		} catch (NotEnoughDataException e) {
2334 chandransh 143
			log.error("Error while initializing payment.", e);
1318 rajveer 144
		}catch (Exception e) {
2334 chandransh 145
			log.error("Error while initializing payment.", e);
1318 rajveer 146
		}
147
 
148
		redirectURL = errorURL + "?paymentId="+paymentId + "?ErrorText=Error while initializing payment.";
1905 chandransh 149
		return PAYMENT_NOT_CREATED;
1318 rajveer 150
	}
151
 
2334 chandransh 152
	public static Map<String, String> capturePayment(Payment payment, String gatewayTxnId){
153
		String amount = "" + payment.getAmount();
154
		String gatewayPaymentId = payment.getGatewayPaymentId();
155
		log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
156
 
157
		//Prepare resultMap to elicit failure behaviour in case anything goes wrong.
158
		Map<String, String> resultMap = new HashMap<String, String>();
159
	    resultMap.put(STATUS, "-2");
160
 
161
		try {
2707 chandransh 162
			PaymentServiceClient paymentServiceClient = new PaymentServiceClient();
163
			Client paymentClient = paymentServiceClient.getClient();
164
			resultMap = paymentClient.captureHdfcPayment(payment.getPaymentId());
165
		} catch (Exception e) {
2334 chandransh 166
			log.error("Unable to capture payment", e);
167
			resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
168
			resultMap.put(ERROR, "Unable to capture transaction.");
169
		}
2707 chandransh 170
 
2334 chandransh 171
		return resultMap;
2707 chandransh 172
//		
173
//		
174
//		
175
//
176
//	    
177
//		e24TranPipe pipe = new e24TranPipe();
178
//		pipe.setResourcePath(resourceFilePath);
179
//		pipe.setAlias(aliasName);
180
//		pipe.setAction(ActionType.CAPTURE.value());
181
//		pipe.setAmt(amount);
182
//		pipe.setTrackId("" + payment.getPaymentId());
183
//		pipe.setMember("SAHOLIC");
184
//		pipe.setCurrencyCode(currencyCode);
185
//		pipe.setTransId(gatewayTxnId);
186
//		
187
//		//Check if the values have been set properly
188
//		log.info("Pipe Amount: " + pipe.getAmt());
189
//		log.info("Pipe Action Code: " + pipe.getAction());
190
//		log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
191
//		log.info("Pipe Track Id: " + pipe.getTrackId());
192
//		log.info("Pipe Trans Id:" + pipe.getTransId());
193
//		
194
//		int captureStatus = e24TranPipe.FAILURE;
195
//		try {
196
//			captureStatus = pipe.performTransaction();
197
//			
198
//			log.info("Capture Status: " + captureStatus);
199
//			log.info("Gateway Txn Status: " + pipe.getResult());
200
//			log.info("Debug Msg: " + pipe.getDebugMsg());
201
//			log.info("Auth: " + pipe.getAuth());
202
//			log.info("Ref: " + pipe.getRef());
203
//			log.info("TransId:" + pipe.getTransId());
204
//			log.info("Amount: " + pipe.getAmt());
205
//			
206
//			resultMap.put(STATUS, "" + captureStatus);
207
//			String result = pipe.getResult();
208
//			resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());		//This will return the result of the transaction. (Successful or Failed)
209
//			if(captureStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){
210
//				resultMap.put(ERROR, pipe.getErrorMsg());				// In case of any error, we only need to get the error message
211
//			}else{
212
//				resultMap.put(CAPTURE_AUTH_ID, pipe.getAuth());			// Unique ID generated by Authorizer of the transaction
213
//				resultMap.put(CAPTURE_REF_ID, pipe.getRef());			// Unique reference number generated during the transaction
214
//				resultMap.put(CAPTURE_TXN_ID, pipe.getTransId());		// Unique Transaction ID generated after every successful transaction
215
//				resultMap.put(CAPTURE_AMNT, pipe.getAmt());			// Original Amount of the transaction
216
//			}
217
//		} catch (NotEnoughDataException e) {
218
//			log.error("Unable to capture payment", e);
219
//			resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
220
//			resultMap.put(ERROR, "Unable to capture transaction.");
221
//		}
222
//		        		
223
//		return resultMap;
2334 chandransh 224
	}
225
 
1318 rajveer 226
	private List<Attribute> getAttributesAndSetUdfs(long txnId) throws TransactionServiceException, TException{
227
		StringBuilder orderDetails = new StringBuilder();
228
		StringBuilder billingAddress = new StringBuilder();
229
		String email = "";
230
		String contactNumber = "";
231
 
232
		//get udfs
233
		Transaction transaction;
234
		TransactionServiceClient transactionServiceClient = null;
235
		try {
236
			transactionServiceClient = new TransactionServiceClient();
237
		} catch (Exception e) {
238
			// TODO Auto-generated catch block
239
			e.printStackTrace();
240
		}
241
 
242
		in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
243
		transaction = txnClient.getTransaction(txnId);
244
		orderDetails.append(transaction.getOrdersSize() + " ");
245
		for (Order order : transaction.getOrders()) {
246
			contactNumber= order.getCustomer_mobilenumber();
247
			email = order.getCustomer_email();
248
			billingAddress.append(" ");
249
			if(order.getCustomer_pincode()!=null){
250
				billingAddress.append(order.getCustomer_pincode());
251
			}
252
			if(order.getCustomer_city()!=null){
253
				billingAddress.append(" " + order.getCustomer_city());
254
			}
255
			if(order.getCustomer_address1()!=null){
256
				billingAddress.append(" " + order.getCustomer_address1());
257
			}
258
			if(order.getCustomer_address2()!=null){
259
				billingAddress.append(" " + order.getCustomer_address2());
260
			}
261
			if(order.getCustomer_state()!=null){
262
				billingAddress.append(" " + order.getCustomer_state());
263
			}
264
 
265
 
266
			for(LineItem line: order.getLineitems()){
267
				if(line.getBrand() != null){
268
					orderDetails.append(line.getBrand());
269
				}
270
				if(line.getModel_name() != null){
271
					orderDetails.append(line.getModel_name()); 
272
				}
273
				if(line.getModel_number() != null){
274
					orderDetails.append(line.getModel_number());
275
				}
276
				if(line.getColor() != null){
277
					orderDetails.append(line.getColor());
278
				}
279
				orderDetails.append(" ");
280
			}
281
 
282
		}
283
 
284
		Random random = new Random();
285
		String merchantInfo = ""+random.nextLong(); 
286
 
287
	    String udf1 = formatUdf(orderDetails.toString()); 
288
	    String udf2 = formatUdf(email);
289
	    String udf3 = formatUdf(contactNumber);
290
	    String udf4 = formatUdf(billingAddress.toString());
291
	    String udf5 = merchantInfo;
292
 
293
	    log.info("udf1:"  + udf1);
294
	    log.info("udf2:"  + udf2);
295
	    log.info("udf3:"  + udf3);
296
	    log.info("udf4:"  + udf4);
297
	    log.info("udf5:"  + udf5);
298
 
299
 
300
	    pipe.setUdf1(udf1);       //	UDF 1 - Order details
301
		pipe.setUdf2(udf2);        	  				//	UDF 2 - Email ID
302
		pipe.setUdf3(udf3);      			//	UDF 3 - Contact Number. 
303
		pipe.setUdf4(udf4);     //	UDF 4 - Billing Address
304
		pipe.setUdf5(udf5);		  						//	UDF 5 - Merchant specific
305
 
306
		List<Attribute> attributes = new ArrayList<Attribute>();
307
		Attribute attribute1 = new Attribute("udf1",udf1);
308
		Attribute attribute2 = new Attribute("udf2",udf2);
309
		Attribute attribute3 = new Attribute("udf3",udf3);
310
		Attribute attribute4 = new Attribute("udf4",udf4);
311
		Attribute attribute5 = new Attribute("udf5",udf5);
312
 
313
		attributes.add(attribute1);
314
		attributes.add(attribute2);
315
		attributes.add(attribute3);
316
		attributes.add(attribute4);
317
		attributes.add(attribute5);
318
 
319
		return attributes;
320
	}
321
 
322
	private void initializePayment(long merchantPaymentId, double amounta) throws ShoppingCartException, TException{
323
		String amount;
324
 
325
		amount = (new Double(amounta)).toString();
326
 
327
		//Following is the code which initilize e24PaymentPipe with proper value		
328
		pipe=new e24PaymentPipe();
329
		pipe.setResourcePath(resourceFilePath);	//mandatory 
330
		String as = pipe.getResourcePath();
331
		log.info("Resource= " +as);
332
 
333
		pipe.setAlias(aliasName);			//mandatory 
334
		String ab=pipe.getAlias();
335
		log.info("Alias= " +ab);
336
 
2334 chandransh 337
		pipe.setAction(ActionType.AUTH.value());			//mandatory 
1318 rajveer 338
		String ac=pipe.getAction();
339
		log.info("Action= " +ac);
340
 
341
		pipe.setResponseURL( responseURL );	//mandatory
342
		String at=pipe.getResponseURL();
343
		log.info("ResponseURL= "+at);
344
 
2692 rajveer 345
		// Removed payment url parameter, as adding parameters stops payment from initialisation with hdfc jar.
346
		// It gives following error. 
347
		// Payment Initialization returned an invalid response: !ERROR!-PY20011-Invalid Merchant Error URL.
348
		pipe.setErrorURL( errorURL );		//mandatory
1318 rajveer 349
	    String ak=pipe.getErrorURL();
350
	    log.info("ErrorURL= " + ak);
351
 
352
 
353
		pipe.setAmt(amount);		
354
		String ap=pipe.getAmt();
355
		log.info("Amt= " + ap);
356
 
2334 chandransh 357
		pipe.setCurrency(currencyCode);
1318 rajveer 358
		String a=pipe.getCurrency();
359
		log.info("Currency= " + a);
360
 
361
		pipe.setLanguage("USA");
362
		String p=pipe.getLanguage();
363
		log.info("Language= "+ p);
364
 
365
		pipe.setTrackId((new Long(merchantPaymentId)).toString());
366
 
367
	}
368
 
369
	String formatUdf(String udfString){
370
		udfString = udfString.replaceAll(regex, replacement);
371
		if(udfString.length() > MAX_UDF_LENGTH){
372
			udfString = udfString.substring(0, MAX_UDF_LENGTH);
373
		}
374
		return udfString;
375
	}
376
 
377
	public String getRedirectUrl(){
378
		return this.redirectURL;
379
	}
2334 chandransh 380
 
381
	public static void main(String args[]){
382
		Payment payment = new Payment();
383
		payment.setPaymentId(216);
384
		payment.setAmount(40000);
385
		payment.setGatewayPaymentId("TESTSTSTS");
386
 
387
		//This test checks what happens when the txn id is left blank
388
		capturePayment(payment, "");					//Result: !ERROR!-GW00205-Invalid Subsequent Transaction.
389
 
390
		//This test checks what happends with an invalid txn id 
391
		capturePayment(payment, "6022630101411740"); 	//Result: !ERROR!-GW00201-Transaction not found.
392
 
393
		//The next three tests require a valid AUTH transaction id.
394
		//This test checks what happens when we attempt to capture an amount greater than what was authorized.
395
		capturePayment(payment, "9644960021411730");	//Result: !ERROR!-GW00177-Failed Capture Greater Than Auth check.
396
 
397
		//This test checks what happens when we attempt to capture a valid transaction with the right amount. This transaction should be CAPTURED.
398
		payment.setAmount(21698);
399
		capturePayment(payment, "9644960021411730");	//Result: CAPTURED
400
 
401
		//This test tries to capture an already captured payment.
402
		capturePayment(payment, "9644960021411730");	//Result: !ERROR!-GW00177-Failed Capture Greater Than Auth check.
403
	}
1318 rajveer 404
}
405