Subversion Repositories SmartDukaan

Rev

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