Subversion Repositories SmartDukaan

Rev

Rev 1905 | Go to most recent revision | Details | 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;
4
import java.util.List;
5
import java.util.Random;
6
 
7
import org.apache.log4j.Logger;
8
import org.apache.struts2.convention.annotation.Result;
9
import org.apache.struts2.convention.annotation.Results;
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.Cart;
18
import in.shop2020.model.v1.user.Line;
19
import in.shop2020.model.v1.user.ShoppingCartException;
20
import in.shop2020.payments.Attribute;
21
import in.shop2020.payments.PaymentException;
22
import in.shop2020.payments.PaymentStatus;
23
import in.shop2020.payments.PaymentService.Client;
24
import in.shop2020.serving.utils.Utils;
25
import in.shop2020.thrift.clients.PaymentServiceClient;
26
import in.shop2020.thrift.clients.TransactionServiceClient;
27
import in.shop2020.thrift.clients.UserContextServiceClient;
28
import in.shop2020.thrift.clients.config.ConfigClient;
29
 
30
 
31
 
32
import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
33
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;
34
@Results({
35
	@Result(name="redirect", type="redirectAction", 
36
			params = {"actionName" , "${url}"}),
37
	@Result(name="shipping-redirect", type="redirectAction", 
38
    		params = {"actionName" , "shipping"})
39
})
40
 
41
public class HdfcPaymentService {
42
	private static final long serialVersionUID = 1L;
43
	private static Logger log = Logger.getLogger(Class.class);
44
 
45
	private static String resourceFilePath;
46
	private static String aliasName;
47
	private static String responseURL;
48
	private static String errorURL;
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 String redirectURL;
53
	private e24PaymentPipe pipe = null;
54
 
55
	private double amount;
56
	private int gatewayId=1;
57
 
58
	private long paymentId;
59
 
60
	private enum ActionType{
61
		PURCHASE("1"),
62
		AUTH ("4");
63
		private String value;
64
		ActionType(String value) {
65
			this.value = value;
66
		}
67
		public String value(){
68
			return this.value;
69
		}
70
	}
71
 
72
	public HdfcPaymentService() {
73
 
74
	}
75
 
76
	static{
77
		try {
78
			resourceFilePath = ConfigClient.getClient().get("payment_resource_file_path");
79
			aliasName  = ConfigClient.getClient().get("payment_alias_name");
80
			responseURL = ConfigClient.getClient().get("payment_response_url");
81
			errorURL = ConfigClient.getClient().get("payment_error_url");
82
		} catch (ConfigException e) {
83
			log.error("Unable to get data from config server.");
84
		}
85
	}
86
 
87
 
88
	public boolean createPayment(long currentCartId, long userId, long txnId){
89
 
90
		PaymentServiceClient paymentServiceClient = null;
91
		try {
92
			paymentServiceClient = new PaymentServiceClient();
93
		} catch (Exception e) {
94
			log.error("Error while getting payment client");
95
			e.printStackTrace();
96
			return false;
97
		}
98
 
99
 
100
		try {
101
			amount = getPaymentAmount(currentCartId);
102
		} catch (ShoppingCartException e1) {
103
			log.error("Not able to fetch payment amount from cart id." + e1.getId() + e1.getMessage());
104
			e1.printStackTrace();
105
			return false;
106
		} catch (TException e1) {
107
			log.error("Not able to fetch payment amount." + e1.getMessage());
108
			e1.printStackTrace();
109
			return false;
110
		}
111
 
112
		Client paymentClient = paymentServiceClient.getClient();
113
		try {
114
			this.paymentId = paymentClient.createPayment(userId, amount, gatewayId, txnId);
115
		} catch (PaymentException e1) {
116
			log.error("Not able to create payment object." + e1.getError_code() + e1.getMessage());
117
			e1.printStackTrace();
118
			return false;
119
		} catch (TException e) {
120
			log.error("Not able to create payment object." + e.getMessage());
121
			e.printStackTrace();
122
			return false;
123
		}
124
 
125
 
126
		try {
127
			initializePayment(paymentId,amount);
128
		} catch (ShoppingCartException e1) {
129
			//addActionError("We are experiencing some problems. Please try later.");
130
			log.error("Error while creating hdfc payment.");
131
			e1.printStackTrace();
132
			return false;
133
		} catch (TException e1) {
134
			//addActionError("We are experiencing some problems. Please try later.");
135
			log.error("Error while creating hdfc payment.");
136
			e1.printStackTrace();
137
			return false;
138
		}
139
 
140
		List<Attribute> attributes = null;
141
		try {
142
			attributes = getAttributesAndSetUdfs(txnId);
143
		} catch (TransactionServiceException e1) {
144
			//addActionError("We are experiencing some problems. Please try later.");
145
			log.error("Error while setting udfs to payment.");
146
			e1.printStackTrace();
147
			return false;
148
		} catch (TException e1) {
149
			//addActionError("We are experiencing some problems. Please try later.");
150
			log.error("Error while setting udfs to payment.");
151
			e1.printStackTrace();
152
			return false;
153
		}
154
 
155
 
156
		try {
157
			if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) 
158
				{
159
					System.out.println("Error sending Payment Initialization Request: ");
160
					paymentServiceClient.getClient().updatePaymentDetails(paymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
161
					//response.sendRedirect(response.encodeRedirectURL( errorURL + "?ErrorText="+pipe.getErrorMsg()+"&paymentId="+merchantPaymentId));
162
					redirectURL = errorURL + "?paymentId="+ paymentId + "&ErrorText="+pipe.getErrorMsg();
163
					//response.setHeader("Location", redirectURL);
164
					//response.setStatus(HttpServletResponse.SC_FOUND);
165
				}
166
			else
167
				{
168
					String paymentID = pipe.getPaymentId();
169
					// Update of payment information
170
					paymentServiceClient.getClient().updatePaymentDetails(paymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
171
 
172
					String payURL = pipe.getPaymentPage();
173
					redirectURL = payURL + "?PaymentID=" + paymentID;
174
					//response.sendRedirect(response.encodeRedirectURL( redirectURL ));
175
 
176
					//response.setHeader("Location", redirectURL);
177
					//response.setStatus(HttpServletResponse.SC_FOUND);
178
				}
179
			return true;
180
		} catch (NotEnoughDataException e) {
181
			log.error("Error while initializing payment." + e.getMessage());
182
			e.printStackTrace();
183
		}catch (Exception e) {
184
			log.error("Error while initializing payment." + e.getMessage());
185
			e.printStackTrace();
186
		}
187
 
188
		redirectURL = errorURL + "?paymentId="+paymentId + "?ErrorText=Error while initializing payment.";
189
		return false;
190
	}
191
 
192
 
193
	private double getPaymentAmount(long cartId) throws ShoppingCartException, TException{
194
		double totalAmount = 0;
195
		Cart cart;
196
		UserContextServiceClient userContextServiceClient = null;
197
		try {
198
			userContextServiceClient = new UserContextServiceClient();
199
		} catch (Exception e) {
200
			e.printStackTrace();
201
		}
202
		in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
203
		cart = userClient.getCart(cartId);
204
 
205
		List<Line> lineItems = cart.getLines(); 
206
 
207
		for (Line line : lineItems) {
208
			long productId = line.getItemId();
209
			totalAmount =  totalAmount + line.getQuantity() * Utils.getItemPrice(productId);
210
		}
211
 
212
		return totalAmount;
213
	}
214
 
215
 
216
	private List<Attribute> getAttributesAndSetUdfs(long txnId) throws TransactionServiceException, TException{
217
		StringBuilder orderDetails = new StringBuilder();
218
		StringBuilder billingAddress = new StringBuilder();
219
		String email = "";
220
		String contactNumber = "";
221
 
222
		//get udfs
223
		Transaction transaction;
224
		TransactionServiceClient transactionServiceClient = null;
225
		try {
226
			transactionServiceClient = new TransactionServiceClient();
227
		} catch (Exception e) {
228
			// TODO Auto-generated catch block
229
			e.printStackTrace();
230
		}
231
 
232
		in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
233
		transaction = txnClient.getTransaction(txnId);
234
		orderDetails.append(transaction.getOrdersSize() + " ");
235
		for (Order order : transaction.getOrders()) {
236
			contactNumber= order.getCustomer_mobilenumber();
237
			email = order.getCustomer_email();
238
			billingAddress.append(" ");
239
			if(order.getCustomer_pincode()!=null){
240
				billingAddress.append(order.getCustomer_pincode());
241
			}
242
			if(order.getCustomer_city()!=null){
243
				billingAddress.append(" " + order.getCustomer_city());
244
			}
245
			if(order.getCustomer_address1()!=null){
246
				billingAddress.append(" " + order.getCustomer_address1());
247
			}
248
			if(order.getCustomer_address2()!=null){
249
				billingAddress.append(" " + order.getCustomer_address2());
250
			}
251
			if(order.getCustomer_state()!=null){
252
				billingAddress.append(" " + order.getCustomer_state());
253
			}
254
 
255
 
256
			for(LineItem line: order.getLineitems()){
257
				if(line.getBrand() != null){
258
					orderDetails.append(line.getBrand());
259
				}
260
				if(line.getModel_name() != null){
261
					orderDetails.append(line.getModel_name()); 
262
				}
263
				if(line.getModel_number() != null){
264
					orderDetails.append(line.getModel_number());
265
				}
266
				if(line.getColor() != null){
267
					orderDetails.append(line.getColor());
268
				}
269
				orderDetails.append(" ");
270
			}
271
 
272
		}
273
 
274
		Random random = new Random();
275
		String merchantInfo = ""+random.nextLong(); 
276
 
277
	    String udf1 = formatUdf(orderDetails.toString()); 
278
	    String udf2 = formatUdf(email);
279
	    String udf3 = formatUdf(contactNumber);
280
	    String udf4 = formatUdf(billingAddress.toString());
281
	    String udf5 = merchantInfo;
282
 
283
	    log.info("udf1:"  + udf1);
284
	    log.info("udf2:"  + udf2);
285
	    log.info("udf3:"  + udf3);
286
	    log.info("udf4:"  + udf4);
287
	    log.info("udf5:"  + udf5);
288
 
289
 
290
	    pipe.setUdf1(udf1);       //	UDF 1 - Order details
291
		pipe.setUdf2(udf2);        	  				//	UDF 2 - Email ID
292
		pipe.setUdf3(udf3);      			//	UDF 3 - Contact Number. 
293
		pipe.setUdf4(udf4);     //	UDF 4 - Billing Address
294
		pipe.setUdf5(udf5);		  						//	UDF 5 - Merchant specific
295
 
296
		List<Attribute> attributes = new ArrayList<Attribute>();
297
		Attribute attribute1 = new Attribute("udf1",udf1);
298
		Attribute attribute2 = new Attribute("udf2",udf2);
299
		Attribute attribute3 = new Attribute("udf3",udf3);
300
		Attribute attribute4 = new Attribute("udf4",udf4);
301
		Attribute attribute5 = new Attribute("udf5",udf5);
302
 
303
		attributes.add(attribute1);
304
		attributes.add(attribute2);
305
		attributes.add(attribute3);
306
		attributes.add(attribute4);
307
		attributes.add(attribute5);
308
 
309
		return attributes;
310
	}
311
 
312
 
313
 
314
	private void initializePayment(long merchantPaymentId, double amounta) throws ShoppingCartException, TException{
315
		String amount;
316
 
317
		amount = (new Double(amounta)).toString();
318
 
319
		//Following is the code which initilize e24PaymentPipe with proper value		
320
		pipe=new e24PaymentPipe();
321
		pipe.setResourcePath(resourceFilePath);	//mandatory 
322
		String as = pipe.getResourcePath();
323
		log.info("Resource= " +as);
324
 
325
		pipe.setAlias(aliasName);			//mandatory 
326
		String ab=pipe.getAlias();
327
		log.info("Alias= " +ab);
328
 
329
		pipe.setAction(ActionType.PURCHASE.value());			//mandatory 
330
		String ac=pipe.getAction();
331
		log.info("Action= " +ac);
332
 
333
		pipe.setResponseURL( responseURL );	//mandatory
334
		String at=pipe.getResponseURL();
335
		log.info("ResponseURL= "+at);
336
 
337
		//pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );		//mandatory
338
		pipe.setErrorURL( errorURL);
339
	    String ak=pipe.getErrorURL();
340
	    log.info("ErrorURL= " + ak);
341
 
342
 
343
		pipe.setAmt(amount);		
344
		String ap=pipe.getAmt();
345
		log.info("Amt= " + ap);
346
 
347
		pipe.setCurrency("356");
348
		String a=pipe.getCurrency();
349
		log.info("Currency= " + a);
350
 
351
		pipe.setLanguage("USA");
352
		String p=pipe.getLanguage();
353
		log.info("Language= "+ p);
354
 
355
		pipe.setTrackId((new Long(merchantPaymentId)).toString());
356
 
357
	}
358
 
359
	String formatUdf(String udfString){
360
		udfString = udfString.replaceAll(regex, replacement);
361
		if(udfString.length() > MAX_UDF_LENGTH){
362
			udfString = udfString.substring(0, MAX_UDF_LENGTH);
363
		}
364
		return udfString;
365
	}
366
 
367
	public String getRedirectUrl(){
368
		return this.redirectURL;
369
	}
370
 
371
}
372