Subversion Repositories SmartDukaan

Rev

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