Subversion Repositories SmartDukaan

Rev

Rev 2757 | Go to most recent revision | Details | 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;
6
import in.shop2020.model.v1.order.Transaction;
7
import in.shop2020.model.v1.order.TransactionServiceException;
8
import in.shop2020.model.v1.user.ShoppingCartException;
9
import in.shop2020.payment.domain.Payment;
10
import in.shop2020.payments.Attribute;
11
import in.shop2020.payments.PaymentStatus;
12
import in.shop2020.thrift.clients.TransactionServiceClient;
13
import in.shop2020.thrift.clients.config.ConfigClient;
14
 
15
import java.util.ArrayList;
16
import java.util.HashMap;
17
import java.util.List;
18
import java.util.Map;
19
import java.util.Random;
20
 
21
import org.apache.log4j.Logger;
22
import org.apache.thrift.TException;
23
 
24
import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
25
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;
26
import com.aciworldwide.commerce.gateway.plugins.e24TranPipe;
27
 
28
public class HdfcPaymentHandler {
29
	private static Logger log = Logger.getLogger(Class.class);
30
 
31
	private static long gatewayId=1;
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;
40
	private static final String currencyCode = "356";
41
 
42
	private static final String STATUS = "status";
43
	private static final String GATEWAY_STATUS = "gatewayTxnStatus";
44
	private static final String ERR_CODE = "errorCode";
45
	private static final String ERROR = "error";
46
 
47
	private static final String CAPTURE_AUTH_ID = "CaptureAuthId";
48
	private static final String CAPTURE_REF_ID = "CatureRefId";
49
	private static final String CAPTURE_TXN_ID = "CaptureTxnId";
50
	private static final String CAPTURE_TIME = "CaptureTime";
51
	private static final String CAPTURE_AMNT = "CaptureAmount";
52
 
53
	enum Errors{
54
		CONN_FAILURE("-1", "Unable to initialize connection to the API server"),
55
		CAPTURE_FAILURE("-2", "Error while capturing payment");
56
 
57
		public final String code;
58
		public final String message;
59
 
60
		Errors(String code, String message){
61
			this.code = code;
62
			this.message = message;
63
		}
64
	}
65
 
66
	private enum ActionType{
67
		PURCHASE("1"),
68
		AUTH ("4"),
69
		CAPTURE("5");
70
		private String value;
71
		ActionType(String value) {
72
			this.value = value;
73
		}
74
		public String value(){
75
			return this.value;
76
		}
77
	}
78
 
79
	public HdfcPaymentHandler() {
80
		// TODO Auto-generated constructor stub
81
	}
82
 
83
	static{
84
		try {
85
			resourceFilePath = ConfigClient.getClient().get("payment_resource_file_path");
86
			aliasName  = ConfigClient.getClient().get("payment_alias_name");
87
			responseURL = ConfigClient.getClient().get("payment_response_url");
88
			errorURL = ConfigClient.getClient().get("payment_error_url");
89
		} catch (ConfigException e) {
90
			log.error("Unable to get data from config server.");
91
		}
92
	}
93
 
94
	public static Map<String, String> capturePayment(Payment payment){
95
		String amount = "" + payment.getAmount();
96
		String gatewayPaymentId = payment.getGatewayPaymentId();
97
		log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
98
 
99
		//Prepare resultMap to elicit failure behaviour in case anything goes wrong.
100
		Map<String, String> resultMap = new HashMap<String, String>();
101
	    resultMap.put(STATUS, "-2");
102
 
103
		e24TranPipe pipe = new e24TranPipe();
104
		pipe.setResourcePath(resourceFilePath);
105
		pipe.setAlias(aliasName);
106
		pipe.setAction(ActionType.CAPTURE.value());
107
		pipe.setAmt(amount);
108
		pipe.setTrackId("" + payment.getId());
109
		pipe.setMember("SAHOLIC");
110
		pipe.setCurrencyCode(currencyCode);
111
		pipe.setTransId(payment.getGatewayTxnId());
112
 
113
		//Check if the values have been set properly
114
		log.info("Pipe Amount: " + pipe.getAmt());
115
		log.info("Pipe Action Code: " + pipe.getAction());
116
		log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
117
		log.info("Pipe Track Id: " + pipe.getTrackId());
118
		log.info("Pipe Trans Id:" + pipe.getTransId());
119
 
120
		int captureStatus = e24TranPipe.FAILURE;
121
		try {
122
			captureStatus = pipe.performTransaction();
123
 
124
			log.info("Capture Status: " + captureStatus);
125
			log.info("Gateway Txn Status: " + pipe.getResult());
126
			log.info("Debug Msg: " + pipe.getDebugMsg());
127
			log.info("Auth: " + pipe.getAuth());
128
			log.info("Ref: " + pipe.getRef());
129
			log.info("TransId:" + pipe.getTransId());
130
			log.info("Amount: " + pipe.getAmt());
131
 
132
			resultMap.put(STATUS, "" + captureStatus);
133
			String result = pipe.getResult();
134
			resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());		//This will return the result of the transaction. (Successful or Failed)
135
			if(captureStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){
136
				resultMap.put(ERROR, pipe.getErrorMsg());				// In case of any error, we only need to get the error message
137
			}else{
138
				resultMap.put(CAPTURE_AUTH_ID, pipe.getAuth());			// Unique ID generated by Authorizer of the transaction
139
				resultMap.put(CAPTURE_REF_ID, pipe.getRef());			// Unique reference number generated during the transaction
140
				resultMap.put(CAPTURE_TXN_ID, pipe.getTransId());		// Unique Transaction ID generated after every successful transaction
141
				resultMap.put(CAPTURE_AMNT, pipe.getAmt());			// Original Amount of the transaction
142
			}
143
		} catch (NotEnoughDataException e) {
144
			log.error("Unable to capture payment", e);
145
			resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
146
			resultMap.put(ERROR, "Unable to capture transaction.");
147
		}
148
 
149
		return resultMap;
150
	}
151
 
152
	public static String initializeHdfcPayment(Payment payment, PaymentServiceHandler handler) throws Exception{
153
		long merchantPaymentId = payment.getId();
154
		double amount = payment.getAmount();
155
		e24PaymentPipe pipe = new e24PaymentPipe();
156
		String redirectURL;
157
 
158
		try {
159
			initializePayment(pipe, merchantPaymentId, amount);
160
		} catch (ShoppingCartException e1) {
161
			log.error("Error while creating hdfc payment.", e1);
162
			throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
163
		} catch (TException e1) {
164
			log.error("Error while creating hdfc payment.", e1);
165
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
166
		}
167
 
168
		List<Attribute> attributes = null;
169
		try {
170
			attributes = getAttributesAndSetUdfs(pipe, payment.getMerchantTxnId());
171
		} catch (TransactionServiceException e1) {
172
			log.error("Error while setting udfs to payment.", e1);
173
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
174
		} catch (TException e1) {
175
			log.error("Error while setting udfs to payment.", e1);
176
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
177
		}
178
 
179
		try {
180
			if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
181
				log.error("Error sending Payment Initialization Request: ");
182
				handler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
183
				redirectURL = errorURL + "?paymentId="+ merchantPaymentId + "&ErrorText="+pipe.getErrorMsg();
184
			} else {
185
				log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
186
				String paymentID = pipe.getPaymentId();
187
				handler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
188
 
189
				String payURL = pipe.getPaymentPage();
190
				redirectURL = payURL + "?PaymentID=" + paymentID;
191
			}
192
			return redirectURL;
193
		} catch (NotEnoughDataException e) {
194
			log.error("Error while initializing payment.", e);
195
		}catch (Exception e) {
196
			log.error("Error while initializing payment.", e);
197
		}
198
 
199
		redirectURL = errorURL + "?paymentId="+merchantPaymentId + "?ErrorText=Error while initializing payment.";
200
		return redirectURL;
201
	}
202
 
203
	private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, long txnId) throws TransactionServiceException, TException{
204
		StringBuilder orderDetails = new StringBuilder();
205
		StringBuilder billingAddress = new StringBuilder();
206
		String email = "";
207
		String contactNumber = "";
208
 
209
		//get udfs
210
		Transaction transaction;
211
		TransactionServiceClient transactionServiceClient = null;
212
		try {
213
			transactionServiceClient = new TransactionServiceClient();
214
		} catch (Exception e) {
215
			log.error("Unable to get transaction details", e);
216
		}
217
 
218
		in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
219
		transaction = txnClient.getTransaction(txnId);
220
		orderDetails.append(transaction.getOrdersSize() + " ");
221
		for (Order order : transaction.getOrders()) {
222
			contactNumber= order.getCustomer_mobilenumber();
223
			email = order.getCustomer_email();
224
			billingAddress.append(" ");
225
			if(order.getCustomer_pincode()!=null){
226
				billingAddress.append(order.getCustomer_pincode());
227
			}
228
			if(order.getCustomer_city()!=null){
229
				billingAddress.append(" " + order.getCustomer_city());
230
			}
231
			if(order.getCustomer_address1()!=null){
232
				billingAddress.append(" " + order.getCustomer_address1());
233
			}
234
			if(order.getCustomer_address2()!=null){
235
				billingAddress.append(" " + order.getCustomer_address2());
236
			}
237
			if(order.getCustomer_state()!=null){
238
				billingAddress.append(" " + order.getCustomer_state());
239
			}
240
 
241
 
242
			for(LineItem line: order.getLineitems()){
243
				if(line.getBrand() != null){
244
					orderDetails.append(line.getBrand());
245
				}
246
				if(line.getModel_name() != null){
247
					orderDetails.append(line.getModel_name()); 
248
				}
249
				if(line.getModel_number() != null){
250
					orderDetails.append(line.getModel_number());
251
				}
252
				if(line.getColor() != null){
253
					orderDetails.append(line.getColor());
254
				}
255
				orderDetails.append(" ");
256
			}
257
 
258
		}
259
 
260
		Random random = new Random();
261
		String merchantInfo = ""+random.nextLong(); 
262
 
263
	    String udf1 = formatUdf(orderDetails.toString()); 
264
	    String udf2 = formatUdf(email);
265
	    String udf3 = formatUdf(contactNumber);
266
	    String udf4 = formatUdf(billingAddress.toString());
267
	    String udf5 = merchantInfo;
268
 
269
	    log.info("udf1:"  + udf1);
270
	    log.info("udf2:"  + udf2);
271
	    log.info("udf3:"  + udf3);
272
	    log.info("udf4:"  + udf4);
273
	    log.info("udf5:"  + udf5);
274
 
275
 
276
	    pipe.setUdf1(udf1);      //	UDF 1 - Order details
277
		pipe.setUdf2(udf2);      //	UDF 2 - Email ID
278
		pipe.setUdf3(udf3);      //	UDF 3 - Contact Number. 
279
		pipe.setUdf4(udf4);      //	UDF 4 - Billing Address
280
		pipe.setUdf5(udf5);		 //	UDF 5 - Merchant specific
281
 
282
		List<Attribute> attributes = new ArrayList<Attribute>();
283
		Attribute attribute1 = new Attribute("udf1",udf1);
284
		Attribute attribute2 = new Attribute("udf2",udf2);
285
		Attribute attribute3 = new Attribute("udf3",udf3);
286
		Attribute attribute4 = new Attribute("udf4",udf4);
287
		Attribute attribute5 = new Attribute("udf5",udf5);
288
 
289
		attributes.add(attribute1);
290
		attributes.add(attribute2);
291
		attributes.add(attribute3);
292
		attributes.add(attribute4);
293
		attributes.add(attribute5);
294
 
295
		return attributes;
296
	}
297
 
298
	private static void initializePayment(e24PaymentPipe pipe, long merchantPaymentId, double amounta) throws ShoppingCartException, TException{
299
		String amount = (new Double(amounta)).toString();
300
 
301
		//Following is the code which initilize e24PaymentPipe with proper value
302
		pipe.setResourcePath(resourceFilePath);	//mandatory 
303
		String as = pipe.getResourcePath();
304
		log.info("Resource= " +as);
305
 
306
		pipe.setAlias(aliasName);			//mandatory 
307
		String ab=pipe.getAlias();
308
		log.info("Alias= " +ab);
309
 
310
		pipe.setAction(ActionType.PURCHASE.value());			//mandatory 
311
		String ac=pipe.getAction();
312
		log.info("Action= " +ac);
313
 
314
		pipe.setResponseURL( responseURL );	//mandatory
315
		String at=pipe.getResponseURL();
316
		log.info("ResponseURL= "+at);
317
 
318
		//pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );		//mandatory
319
		pipe.setErrorURL( errorURL);
320
	    String ak=pipe.getErrorURL();
321
	    log.info("ErrorURL= " + ak);
322
 
323
 
324
		pipe.setAmt(amount);		
325
		String ap=pipe.getAmt();
326
		log.info("Amt= " + ap);
327
 
328
		pipe.setCurrency("356");
329
		String a=pipe.getCurrency();
330
		log.info("Currency= " + a);
331
 
332
		pipe.setLanguage("USA");
333
		String p=pipe.getLanguage();
334
		log.info("Language= "+ p);
335
 
336
		pipe.setTrackId((new Long(merchantPaymentId)).toString());
337
	}
338
 
339
	private static String formatUdf(String udfString){
340
		udfString = udfString.replaceAll(regex, replacement);
341
		if(udfString.length() > MAX_UDF_LENGTH){
342
			udfString = udfString.substring(0, MAX_UDF_LENGTH);
343
		}
344
		return udfString;
345
	}
346
}