Subversion Repositories SmartDukaan

Rev

Rev 4617 | Rev 4643 | 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
 
4641 rajveer 16
import java.io.File;
17
import java.io.FileNotFoundException;
18
import java.io.FileOutputStream;
19
import java.io.IOException;
20
import java.io.InputStream;
21
import java.io.OutputStream;
2391 chandransh 22
import java.util.ArrayList;
23
import java.util.HashMap;
24
import java.util.List;
25
import java.util.Map;
26
import java.util.Random;
27
 
28
import org.apache.log4j.Logger;
29
import org.apache.thrift.TException;
30
 
31
import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
32
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;
33
import com.aciworldwide.commerce.gateway.plugins.e24TranPipe;
34
 
3010 chandransh 35
public class HdfcPaymentHandler implements IPaymentHandler {
4421 mandeep.dh 36
	private static final int CAPTURE_STATUS_FOR_CONNECTION_ISSUE = -1;
37
 
38
    private static Logger log = Logger.getLogger(HdfcPaymentHandler.class);
2391 chandransh 39
 
40
	private static String aliasName;
41
	private static String responseURL;
42
	private static String errorURL;
43
	private static final String regex = "[^a-zA-Z0-9\\s\\-\\@\\/\\.]";
44
	private static final String replacement = " ";
45
	private static final int MAX_UDF_LENGTH = 30;
46
	private static final String currencyCode = "356";
4641 rajveer 47
	private static String resourceDirPath = "/tmp/resource";
48
	private static final String resourceFileName = "resource.cgn";
2391 chandransh 49
 
50
	private enum ActionType{
51
		PURCHASE("1"),
52
		AUTH ("4"),
53
		CAPTURE("5");
54
		private String value;
55
		ActionType(String value) {
56
			this.value = value;
57
		}
58
		public String value(){
59
			return this.value;
60
		}
61
	}
62
 
63
	public HdfcPaymentHandler() {
64
		// TODO Auto-generated constructor stub
65
	}
66
 
67
	static{
68
		try {
4641 rajveer 69
			InputStream inputStream = Class.class.getResourceAsStream(ConfigClient.getClient().get("payment_resource_file_path") + resourceFileName);
70
			File resourceDir = new File(resourceDirPath);
71
			if(!resourceDir.exists()){
72
				resourceDir.mkdir();
73
			}
74
 
75
			OutputStream outStream = new FileOutputStream(resourceDirPath + File.separator + resourceFileName);
76
			byte buf[]=new byte[1024];
77
			int len;
78
			while((len=inputStream.read(buf))>0)
79
				outStream.write(buf,0,len);
80
			outStream.close();
81
			inputStream.close();
82
 
4617 rajveer 83
	        aliasName  = ConfigClient.getClient().get("payment_alias_name");
2391 chandransh 84
			responseURL = ConfigClient.getClient().get("payment_response_url");
85
			errorURL = ConfigClient.getClient().get("payment_error_url");
86
		} catch (ConfigException e) {
87
			log.error("Unable to get data from config server.");
4641 rajveer 88
		} catch (FileNotFoundException e) {
89
			// TODO Auto-generated catch block
90
			e.printStackTrace();
91
		} catch (IOException e) {
92
			// TODO Auto-generated catch block
93
			e.printStackTrace();
2391 chandransh 94
		}
95
	}
96
 
97
	public static Map<String, String> capturePayment(Payment payment){
98
		String amount = "" + payment.getAmount();
99
		String gatewayPaymentId = payment.getGatewayPaymentId();
100
		log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
101
 
102
		//Prepare resultMap to elicit failure behaviour in case anything goes wrong.
103
		Map<String, String> resultMap = new HashMap<String, String>();
4421 mandeep.dh 104
	    resultMap.put(STATUS, Errors.CAPTURE_FAILURE.code);
105
        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
106
        resultMap.put(ERROR, Errors.CAPTURE_FAILURE.message);
2391 chandransh 107
 
108
		e24TranPipe pipe = new e24TranPipe();
4641 rajveer 109
		pipe.setResourcePath(resourceDirPath);
2391 chandransh 110
		pipe.setAlias(aliasName);
111
		pipe.setAction(ActionType.CAPTURE.value());
112
		pipe.setAmt(amount);
113
		pipe.setTrackId("" + payment.getId());
114
		pipe.setMember("SAHOLIC");
115
		pipe.setCurrencyCode(currencyCode);
116
		pipe.setTransId(payment.getGatewayTxnId());
117
 
118
		//Check if the values have been set properly
119
		log.info("Pipe Amount: " + pipe.getAmt());
120
		log.info("Pipe Action Code: " + pipe.getAction());
121
		log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
122
		log.info("Pipe Track Id: " + pipe.getTrackId());
123
		log.info("Pipe Trans Id:" + pipe.getTransId());
124
 
125
		int captureStatus = e24TranPipe.FAILURE;
126
		try {
127
			captureStatus = pipe.performTransaction();
128
 
129
			log.info("Capture Status: " + captureStatus);
130
			log.info("Gateway Txn Status: " + pipe.getResult());
131
			log.info("Debug Msg: " + pipe.getDebugMsg());
132
			log.info("Auth: " + pipe.getAuth());
133
			log.info("Ref: " + pipe.getRef());
134
			log.info("TransId:" + pipe.getTransId());
135
			log.info("Amount: " + pipe.getAmt());
136
 
137
			resultMap.put(STATUS, "" + captureStatus);
138
			String result = pipe.getResult();
139
			resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());		//This will return the result of the transaction. (Successful or Failed)
140
			if(captureStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){
141
				resultMap.put(ERROR, pipe.getErrorMsg());				// In case of any error, we only need to get the error message
4421 mandeep.dh 142
 
143
				if (captureStatus == CAPTURE_STATUS_FOR_CONNECTION_ISSUE) {
144
	                resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
145
	            }
146
			}
147
			else {
2391 chandransh 148
				resultMap.put(CAPTURE_AUTH_ID, pipe.getAuth());			// Unique ID generated by Authorizer of the transaction
149
				resultMap.put(CAPTURE_REF_ID, pipe.getRef());			// Unique reference number generated during the transaction
150
				resultMap.put(CAPTURE_TXN_ID, pipe.getTransId());		// Unique Transaction ID generated after every successful transaction
151
				resultMap.put(CAPTURE_AMNT, pipe.getAmt());			// Original Amount of the transaction
152
			}
153
		} catch (NotEnoughDataException e) {
4421 mandeep.dh 154
            log.error(Errors.CAPTURE_FAILURE.message, e);
155
            resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
156
            resultMap.put(ERROR, e.getMessage());
2391 chandransh 157
		}
158
 
159
		return resultMap;
160
	}
161
 
162
	public static String initializeHdfcPayment(Payment payment, PaymentServiceHandler handler) throws Exception{
163
		long merchantPaymentId = payment.getId();
164
		double amount = payment.getAmount();
165
		e24PaymentPipe pipe = new e24PaymentPipe();
166
 
167
		try {
168
			initializePayment(pipe, merchantPaymentId, amount);
169
		} catch (ShoppingCartException e1) {
170
			log.error("Error while creating hdfc payment.", e1);
171
			throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
172
		} catch (TException e1) {
173
			log.error("Error while creating hdfc payment.", e1);
174
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
175
		}
176
 
177
		List<Attribute> attributes = null;
178
		try {
179
			attributes = getAttributesAndSetUdfs(pipe, payment.getMerchantTxnId());
180
		} catch (TransactionServiceException e1) {
181
			log.error("Error while setting udfs to payment.", e1);
182
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
183
		} catch (TException e1) {
184
			log.error("Error while setting udfs to payment.", e1);
185
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
186
		}
187
 
188
		try {
189
			if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
190
				log.error("Error sending Payment Initialization Request: ");
191
				handler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
192
			} else {
193
				log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
194
				String paymentID = pipe.getPaymentId();
195
				handler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
196
 
197
				String payURL = pipe.getPaymentPage();
3046 chandransh 198
				return payURL + "?PaymentID=" + paymentID;
2391 chandransh 199
			}
200
		} catch (NotEnoughDataException e) {
201
			log.error("Error while initializing payment.", e);
202
		}catch (Exception e) {
203
			log.error("Error while initializing payment.", e);
204
		}
3046 chandransh 205
		//If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
206
		//Throw the exception so that any failovers can happen.
207
		throw new PaymentException(115, "Unable to initialize HDFC payment");
2391 chandransh 208
	}
209
 
210
	private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, long txnId) throws TransactionServiceException, TException{
211
		StringBuilder orderDetails = new StringBuilder();
212
		StringBuilder billingAddress = new StringBuilder();
213
		String email = "";
214
		String contactNumber = "";
215
 
216
		//get udfs
217
		Transaction transaction;
3128 rajveer 218
		TransactionClient transactionServiceClient = null;
2391 chandransh 219
		try {
3128 rajveer 220
			transactionServiceClient = new TransactionClient();
2391 chandransh 221
		} catch (Exception e) {
222
			log.error("Unable to get transaction details", e);
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 static void initializePayment(e24PaymentPipe pipe, long merchantPaymentId, double amounta) throws ShoppingCartException, TException{
306
		String amount = (new Double(amounta)).toString();
307
 
308
		//Following is the code which initilize e24PaymentPipe with proper value
4641 rajveer 309
		pipe.setResourcePath(resourceDirPath);	//mandatory 
2391 chandransh 310
		String as = pipe.getResourcePath();
311
		log.info("Resource= " +as);
312
 
313
		pipe.setAlias(aliasName);			//mandatory 
314
		String ab=pipe.getAlias();
315
		log.info("Alias= " +ab);
316
 
2757 chandransh 317
		pipe.setAction(ActionType.AUTH.value());			//mandatory 
2391 chandransh 318
		String ac=pipe.getAction();
319
		log.info("Action= " +ac);
320
 
321
		pipe.setResponseURL( responseURL );	//mandatory
322
		String at=pipe.getResponseURL();
323
		log.info("ResponseURL= "+at);
324
 
325
		//pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );		//mandatory
326
		pipe.setErrorURL( errorURL);
327
	    String ak=pipe.getErrorURL();
328
	    log.info("ErrorURL= " + ak);
329
 
330
 
331
		pipe.setAmt(amount);		
332
		String ap=pipe.getAmt();
333
		log.info("Amt= " + ap);
334
 
2761 chandransh 335
		pipe.setCurrency(currencyCode);
2391 chandransh 336
		String a=pipe.getCurrency();
337
		log.info("Currency= " + a);
338
 
339
		pipe.setLanguage("USA");
340
		String p=pipe.getLanguage();
341
		log.info("Language= "+ p);
342
 
343
		pipe.setTrackId((new Long(merchantPaymentId)).toString());
344
	}
345
 
346
	private static String formatUdf(String udfString){
347
		udfString = udfString.replaceAll(regex, replacement);
348
		if(udfString.length() > MAX_UDF_LENGTH){
349
			udfString = udfString.substring(0, MAX_UDF_LENGTH);
350
		}
351
		return udfString;
352
	}
353
}