Subversion Repositories SmartDukaan

Rev

Rev 4643 | Rev 6091 | 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;
6050 anupam.sin 6
import in.shop2020.model.v1.order.RechargeOrder;
2391 chandransh 7
import in.shop2020.model.v1.order.Transaction;
8
import in.shop2020.model.v1.order.TransactionServiceException;
6050 anupam.sin 9
import in.shop2020.model.v1.user.Address;
2391 chandransh 10
import in.shop2020.model.v1.user.ShoppingCartException;
11
import in.shop2020.payment.domain.Payment;
12
import in.shop2020.payments.Attribute;
3046 chandransh 13
import in.shop2020.payments.PaymentException;
2391 chandransh 14
import in.shop2020.payments.PaymentStatus;
3128 rajveer 15
import in.shop2020.thrift.clients.TransactionClient;
6050 anupam.sin 16
import in.shop2020.thrift.clients.UserClient;
2391 chandransh 17
import in.shop2020.thrift.clients.config.ConfigClient;
18
 
4641 rajveer 19
import java.io.File;
20
import java.io.FileNotFoundException;
21
import java.io.FileOutputStream;
22
import java.io.IOException;
23
import java.io.InputStream;
24
import java.io.OutputStream;
2391 chandransh 25
import java.util.ArrayList;
26
import java.util.HashMap;
27
import java.util.List;
28
import java.util.Map;
29
import java.util.Random;
30
 
31
import org.apache.log4j.Logger;
32
import org.apache.thrift.TException;
33
 
34
import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;
35
import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;
36
import com.aciworldwide.commerce.gateway.plugins.e24TranPipe;
37
 
3010 chandransh 38
public class HdfcPaymentHandler implements IPaymentHandler {
4421 mandeep.dh 39
	private static final int CAPTURE_STATUS_FOR_CONNECTION_ISSUE = -1;
40
 
41
    private static Logger log = Logger.getLogger(HdfcPaymentHandler.class);
2391 chandransh 42
 
43
	private static String aliasName;
44
	private static String responseURL;
45
	private static String errorURL;
46
	private static final String regex = "[^a-zA-Z0-9\\s\\-\\@\\/\\.]";
47
	private static final String replacement = " ";
48
	private static final int MAX_UDF_LENGTH = 30;
49
	private static final String currencyCode = "356";
4643 rajveer 50
	private static String resourceDirPath = "/tmp/resource/";
6050 anupam.sin 51
 
52
    private static String responseURLforRecharge;
53
 
54
    private static String errorURLforRecharge;
4641 rajveer 55
	private static final String resourceFileName = "resource.cgn";
2391 chandransh 56
 
57
	private enum ActionType{
58
		PURCHASE("1"),
59
		AUTH ("4"),
60
		CAPTURE("5");
61
		private String value;
62
		ActionType(String value) {
63
			this.value = value;
64
		}
65
		public String value(){
66
			return this.value;
67
		}
68
	}
69
 
70
	public HdfcPaymentHandler() {
71
		// TODO Auto-generated constructor stub
72
	}
73
 
74
	static{
75
		try {
4641 rajveer 76
			InputStream inputStream = Class.class.getResourceAsStream(ConfigClient.getClient().get("payment_resource_file_path") + resourceFileName);
77
			File resourceDir = new File(resourceDirPath);
78
			if(!resourceDir.exists()){
79
				resourceDir.mkdir();
80
			}
81
 
4643 rajveer 82
			OutputStream outStream = new FileOutputStream(resourceDirPath + resourceFileName);
4641 rajveer 83
			byte buf[]=new byte[1024];
84
			int len;
85
			while((len=inputStream.read(buf))>0)
86
				outStream.write(buf,0,len);
87
			outStream.close();
88
			inputStream.close();
89
 
4617 rajveer 90
	        aliasName  = ConfigClient.getClient().get("payment_alias_name");
2391 chandransh 91
			responseURL = ConfigClient.getClient().get("payment_response_url");
92
			errorURL = ConfigClient.getClient().get("payment_error_url");
6050 anupam.sin 93
			responseURLforRecharge = ConfigClient.getClient().get("payment_response_url_for_recharge");
94
			errorURLforRecharge = ConfigClient.getClient().get("recharge_success_url");
2391 chandransh 95
		} catch (ConfigException e) {
96
			log.error("Unable to get data from config server.");
4641 rajveer 97
		} catch (FileNotFoundException e) {
98
			// TODO Auto-generated catch block
99
			e.printStackTrace();
100
		} catch (IOException e) {
101
			// TODO Auto-generated catch block
102
			e.printStackTrace();
2391 chandransh 103
		}
104
	}
105
 
106
	public static Map<String, String> capturePayment(Payment payment){
107
		String amount = "" + payment.getAmount();
108
		String gatewayPaymentId = payment.getGatewayPaymentId();
109
		log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
110
 
111
		//Prepare resultMap to elicit failure behaviour in case anything goes wrong.
112
		Map<String, String> resultMap = new HashMap<String, String>();
4421 mandeep.dh 113
	    resultMap.put(STATUS, Errors.CAPTURE_FAILURE.code);
114
        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
115
        resultMap.put(ERROR, Errors.CAPTURE_FAILURE.message);
2391 chandransh 116
 
117
		e24TranPipe pipe = new e24TranPipe();
4641 rajveer 118
		pipe.setResourcePath(resourceDirPath);
2391 chandransh 119
		pipe.setAlias(aliasName);
120
		pipe.setAction(ActionType.CAPTURE.value());
121
		pipe.setAmt(amount);
122
		pipe.setTrackId("" + payment.getId());
123
		pipe.setMember("SAHOLIC");
124
		pipe.setCurrencyCode(currencyCode);
125
		pipe.setTransId(payment.getGatewayTxnId());
126
 
127
		//Check if the values have been set properly
128
		log.info("Pipe Amount: " + pipe.getAmt());
129
		log.info("Pipe Action Code: " + pipe.getAction());
130
		log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
131
		log.info("Pipe Track Id: " + pipe.getTrackId());
132
		log.info("Pipe Trans Id:" + pipe.getTransId());
133
 
134
		int captureStatus = e24TranPipe.FAILURE;
135
		try {
136
			captureStatus = pipe.performTransaction();
137
 
138
			log.info("Capture Status: " + captureStatus);
139
			log.info("Gateway Txn Status: " + pipe.getResult());
140
			log.info("Debug Msg: " + pipe.getDebugMsg());
141
			log.info("Auth: " + pipe.getAuth());
142
			log.info("Ref: " + pipe.getRef());
143
			log.info("TransId:" + pipe.getTransId());
144
			log.info("Amount: " + pipe.getAmt());
145
 
146
			resultMap.put(STATUS, "" + captureStatus);
147
			String result = pipe.getResult();
148
			resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());		//This will return the result of the transaction. (Successful or Failed)
149
			if(captureStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){
150
				resultMap.put(ERROR, pipe.getErrorMsg());				// In case of any error, we only need to get the error message
4421 mandeep.dh 151
 
152
				if (captureStatus == CAPTURE_STATUS_FOR_CONNECTION_ISSUE) {
153
	                resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
154
	            }
155
			}
156
			else {
2391 chandransh 157
				resultMap.put(CAPTURE_AUTH_ID, pipe.getAuth());			// Unique ID generated by Authorizer of the transaction
158
				resultMap.put(CAPTURE_REF_ID, pipe.getRef());			// Unique reference number generated during the transaction
159
				resultMap.put(CAPTURE_TXN_ID, pipe.getTransId());		// Unique Transaction ID generated after every successful transaction
160
				resultMap.put(CAPTURE_AMNT, pipe.getAmt());			// Original Amount of the transaction
161
			}
162
		} catch (NotEnoughDataException e) {
4421 mandeep.dh 163
            log.error(Errors.CAPTURE_FAILURE.message, e);
164
            resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
165
            resultMap.put(ERROR, e.getMessage());
2391 chandransh 166
		}
167
 
168
		return resultMap;
169
	}
170
 
171
	public static String initializeHdfcPayment(Payment payment, PaymentServiceHandler handler) throws Exception{
172
		long merchantPaymentId = payment.getId();
173
		double amount = payment.getAmount();
174
		e24PaymentPipe pipe = new e24PaymentPipe();
175
 
176
		try {
6050 anupam.sin 177
			initializePayment(pipe, merchantPaymentId, amount, false);
2391 chandransh 178
		} catch (ShoppingCartException e1) {
179
			log.error("Error while creating hdfc payment.", e1);
180
			throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
181
		} catch (TException e1) {
182
			log.error("Error while creating hdfc payment.", e1);
183
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
184
		}
185
 
186
		List<Attribute> attributes = null;
187
		try {
188
			attributes = getAttributesAndSetUdfs(pipe, payment.getMerchantTxnId());
189
		} catch (TransactionServiceException e1) {
190
			log.error("Error while setting udfs to payment.", e1);
191
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
192
		} catch (TException e1) {
193
			log.error("Error while setting udfs to payment.", e1);
194
			throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
195
		}
196
 
197
		try {
198
			if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
199
				log.error("Error sending Payment Initialization Request: ");
200
				handler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
201
			} else {
202
				log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
203
				String paymentID = pipe.getPaymentId();
204
				handler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
205
 
206
				String payURL = pipe.getPaymentPage();
3046 chandransh 207
				return payURL + "?PaymentID=" + paymentID;
2391 chandransh 208
			}
209
		} catch (NotEnoughDataException e) {
210
			log.error("Error while initializing payment.", e);
211
		}catch (Exception e) {
212
			log.error("Error while initializing payment.", e);
213
		}
3046 chandransh 214
		//If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
215
		//Throw the exception so that any failovers can happen.
216
		throw new PaymentException(115, "Unable to initialize HDFC payment");
2391 chandransh 217
	}
218
 
219
	private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, long txnId) throws TransactionServiceException, TException{
220
		StringBuilder orderDetails = new StringBuilder();
221
		StringBuilder billingAddress = new StringBuilder();
222
		String email = "";
223
		String contactNumber = "";
224
 
225
		//get udfs
226
		Transaction transaction;
3128 rajveer 227
		TransactionClient transactionServiceClient = null;
2391 chandransh 228
		try {
3128 rajveer 229
			transactionServiceClient = new TransactionClient();
2391 chandransh 230
		} catch (Exception e) {
231
			log.error("Unable to get transaction details", e);
232
		}
233
 
234
		in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
235
		transaction = txnClient.getTransaction(txnId);
236
		orderDetails.append(transaction.getOrdersSize() + " ");
237
		for (Order order : transaction.getOrders()) {
238
			contactNumber= order.getCustomer_mobilenumber();
239
			email = order.getCustomer_email();
240
			billingAddress.append(" ");
241
			if(order.getCustomer_pincode()!=null){
242
				billingAddress.append(order.getCustomer_pincode());
243
			}
244
			if(order.getCustomer_city()!=null){
245
				billingAddress.append(" " + order.getCustomer_city());
246
			}
247
			if(order.getCustomer_address1()!=null){
248
				billingAddress.append(" " + order.getCustomer_address1());
249
			}
250
			if(order.getCustomer_address2()!=null){
251
				billingAddress.append(" " + order.getCustomer_address2());
252
			}
253
			if(order.getCustomer_state()!=null){
254
				billingAddress.append(" " + order.getCustomer_state());
255
			}
256
 
257
 
258
			for(LineItem line: order.getLineitems()){
259
				if(line.getBrand() != null){
260
					orderDetails.append(line.getBrand());
261
				}
262
				if(line.getModel_name() != null){
263
					orderDetails.append(line.getModel_name()); 
264
				}
265
				if(line.getModel_number() != null){
266
					orderDetails.append(line.getModel_number());
267
				}
268
				if(line.getColor() != null){
269
					orderDetails.append(line.getColor());
270
				}
271
				orderDetails.append(" ");
272
			}
273
 
274
		}
275
 
276
		Random random = new Random();
277
		String merchantInfo = ""+random.nextLong(); 
278
 
279
	    String udf1 = formatUdf(orderDetails.toString()); 
280
	    String udf2 = formatUdf(email);
281
	    String udf3 = formatUdf(contactNumber);
282
	    String udf4 = formatUdf(billingAddress.toString());
283
	    String udf5 = merchantInfo;
284
 
285
	    log.info("udf1:"  + udf1);
286
	    log.info("udf2:"  + udf2);
287
	    log.info("udf3:"  + udf3);
288
	    log.info("udf4:"  + udf4);
289
	    log.info("udf5:"  + udf5);
290
 
291
 
292
	    pipe.setUdf1(udf1);      //	UDF 1 - Order details
293
		pipe.setUdf2(udf2);      //	UDF 2 - Email ID
294
		pipe.setUdf3(udf3);      //	UDF 3 - Contact Number. 
295
		pipe.setUdf4(udf4);      //	UDF 4 - Billing Address
296
		pipe.setUdf5(udf5);		 //	UDF 5 - Merchant specific
297
 
298
		List<Attribute> attributes = new ArrayList<Attribute>();
299
		Attribute attribute1 = new Attribute("udf1",udf1);
300
		Attribute attribute2 = new Attribute("udf2",udf2);
301
		Attribute attribute3 = new Attribute("udf3",udf3);
302
		Attribute attribute4 = new Attribute("udf4",udf4);
303
		Attribute attribute5 = new Attribute("udf5",udf5);
304
 
305
		attributes.add(attribute1);
306
		attributes.add(attribute2);
307
		attributes.add(attribute3);
308
		attributes.add(attribute4);
309
		attributes.add(attribute5);
310
 
311
		return attributes;
312
	}
313
 
6050 anupam.sin 314
	private static void initializePayment(e24PaymentPipe pipe, long merchantPaymentId, double amounta, boolean isDigital) throws ShoppingCartException, TException{
2391 chandransh 315
		String amount = (new Double(amounta)).toString();
316
 
317
		//Following is the code which initilize e24PaymentPipe with proper value
4641 rajveer 318
		pipe.setResourcePath(resourceDirPath);	//mandatory 
2391 chandransh 319
		String as = pipe.getResourcePath();
320
		log.info("Resource= " +as);
321
 
322
		pipe.setAlias(aliasName);			//mandatory 
323
		String ab=pipe.getAlias();
324
		log.info("Alias= " +ab);
325
 
2757 chandransh 326
		pipe.setAction(ActionType.AUTH.value());			//mandatory 
2391 chandransh 327
		String ac=pipe.getAction();
328
		log.info("Action= " +ac);
6050 anupam.sin 329
 
330
		if(isDigital) {
331
		    pipe.setResponseURL( responseURLforRecharge );   //mandatory
332
		    pipe.setErrorURL( errorURLforRecharge); //mandatory
333
		} else {
334
		    pipe.setResponseURL( responseURL );
335
		    pipe.setErrorURL( errorURL);
336
		}
2391 chandransh 337
		String at=pipe.getResponseURL();
338
		log.info("ResponseURL= "+at);
339
 
340
		//pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );		//mandatory
341
	    String ak=pipe.getErrorURL();
342
	    log.info("ErrorURL= " + ak);
343
 
344
 
345
		pipe.setAmt(amount);		
346
		String ap=pipe.getAmt();
347
		log.info("Amt= " + ap);
348
 
2761 chandransh 349
		pipe.setCurrency(currencyCode);
2391 chandransh 350
		String a=pipe.getCurrency();
351
		log.info("Currency= " + a);
352
 
353
		pipe.setLanguage("USA");
354
		String p=pipe.getLanguage();
355
		log.info("Language= "+ p);
356
 
357
		pipe.setTrackId((new Long(merchantPaymentId)).toString());
358
	}
359
 
360
	private static String formatUdf(String udfString){
361
		udfString = udfString.replaceAll(regex, replacement);
362
		if(udfString.length() > MAX_UDF_LENGTH){
363
			udfString = udfString.substring(0, MAX_UDF_LENGTH);
364
		}
365
		return udfString;
366
	}
6050 anupam.sin 367
 
368
    public static String initializeHdfcPayment(in.shop2020.payment.domain.Payment payment, RechargeOrder rechargeOrder,
369
            PaymentServiceHandler paymentServiceHandler) throws Exception {
370
        long merchantPaymentId = payment.getId();
371
        double amount = payment.getAmount();
372
        e24PaymentPipe pipe = new e24PaymentPipe();
373
 
374
        try {
375
            initializePayment(pipe, merchantPaymentId, amount, true);
376
        } catch (ShoppingCartException e1) {
377
            log.error("Error while creating hdfc payment.", e1);
378
            throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
379
        } catch (TException e1) {
380
            log.error("Error while creating hdfc payment.", e1);
381
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
382
        }
383
 
384
        List<Attribute> attributes = null;
385
        try {
386
            attributes = getAttributesAndSetUdfs(pipe, rechargeOrder);
387
        } catch (TransactionServiceException e1) {
388
            log.error("Error while setting udfs to payment.", e1);
389
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
390
        } catch (TException e1) {
391
            log.error("Error while setting udfs to payment.", e1);
392
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
393
        }
394
 
395
        try {
396
            if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
397
                log.error("Error sending Payment Initialization Request: ");
398
                paymentServiceHandler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
399
            } else {
400
                log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
401
                String paymentID = pipe.getPaymentId();
402
                paymentServiceHandler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
403
 
404
                String payURL = pipe.getPaymentPage();
405
                return payURL + "?PaymentID=" + paymentID;
406
            }
407
        } catch (NotEnoughDataException e) {
408
            log.error("Error while initializing payment.", e);
409
        }catch (Exception e) {
410
            log.error("Error while initializing payment.", e);
411
        }
412
        //If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
413
        //Throw the exception so that any failovers can happen.
414
        throw new PaymentException(115, "Unable to initialize HDFC payment");
415
    }
416
 
417
    private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, RechargeOrder rechargeOrder) throws TransactionServiceException, TException {
418
 
419
        StringBuilder orderDetails = new StringBuilder();
420
        StringBuilder billingAddress = new StringBuilder();
421
        String email = "";
422
        String contactNumber = "";
423
 
424
        //get udfs
425
        Address address = null;
426
        try {
427
            UserClient userClient = new UserClient();
428
            address = userClient.getClient().getAddressById(userClient.getClient().getDefaultAddressId(rechargeOrder.getUserId()));
429
        } catch (Exception e) {
430
            log.error("Unable to get transaction details", e);
431
        }
432
 
433
        contactNumber= address.getPhone();
434
        email = rechargeOrder.getUserEmailId();
435
        billingAddress.append(" ");
436
        if(address.getPin()!=null){
437
            billingAddress.append(address.getPin());
438
        }
439
        if(address.getCity()!=null){
440
            billingAddress.append(" " + address.getCity());
441
        }
442
        if(address.getLine1()!=null){
443
            billingAddress.append(" " + address.getLine1());
444
        }
445
        if(address.getLine2()!=null){
446
            billingAddress.append(" " + address.getLine2());
447
        }
448
        if(address.getState()!=null){
449
            billingAddress.append(" " + address.getState());
450
        }
451
        orderDetails.append("Recharge : " + rechargeOrder.getDisplayId());
452
        orderDetails.append(" ");
453
 
454
        Random random = new Random();
455
        String merchantInfo = ""+random.nextLong(); 
456
 
457
        String udf1 = formatUdf(orderDetails.toString()); 
458
        String udf2 = formatUdf(email);
459
        String udf3 = formatUdf(contactNumber);
460
        String udf4 = formatUdf(billingAddress.toString());
461
        String udf5 = merchantInfo;
462
 
463
        log.info("udf1:"  + udf1);
464
        log.info("udf2:"  + udf2);
465
        log.info("udf3:"  + udf3);
466
        log.info("udf4:"  + udf4);
467
        log.info("udf5:"  + udf5);
468
 
469
 
470
        pipe.setUdf1(udf1);      // UDF 1 - Order details
471
        pipe.setUdf2(udf2);      // UDF 2 - Email ID
472
        pipe.setUdf3(udf3);      // UDF 3 - Contact Number. 
473
        pipe.setUdf4(udf4);      // UDF 4 - Billing Address
474
        pipe.setUdf5(udf5);      // UDF 5 - Merchant specific
475
 
476
        List<Attribute> attributes = new ArrayList<Attribute>();
477
        Attribute attribute1 = new Attribute("udf1",udf1);
478
        Attribute attribute2 = new Attribute("udf2",udf2);
479
        Attribute attribute3 = new Attribute("udf3",udf3);
480
        Attribute attribute4 = new Attribute("udf4",udf4);
481
        Attribute attribute5 = new Attribute("udf5",udf5);
482
 
483
        attributes.add(attribute1);
484
        attributes.add(attribute2);
485
        attributes.add(attribute3);
486
        attributes.add(attribute4);
487
        attributes.add(attribute5);
488
 
489
        return attributes;
490
    }
2391 chandransh 491
}