Subversion Repositories SmartDukaan

Rev

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