Subversion Repositories SmartDukaan

Rev

Rev 6402 | Rev 6491 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3583 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.PaymentException;
12
import in.shop2020.payments.PaymentStatus;
13
import in.shop2020.thrift.clients.TransactionClient;
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;
3583 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
 
35
public class HdfcEmiPaymentHandler implements IPaymentHandler {
4421 mandeep.dh 36
    private static final int CAPTURE_STATUS_FOR_CONNECTION_ISSUE = -1;
37
 
3583 chandransh 38
    private static Logger log = Logger.getLogger(HdfcEmiPaymentHandler.class);
4421 mandeep.dh 39
 
3583 chandransh 40
    private static String responseURL;
41
    private static String errorURL;
42
    private static final String regex = "[^a-zA-Z0-9\\s\\-\\@\\/\\.]";
43
    private static final String replacement = " ";
44
    private static final int MAX_UDF_LENGTH = 30;
45
    private static final String currencyCode = "356";
4641 rajveer 46
	private static final String resourceFileName = "resource.cgn";
6401 rajveer 47
 
3583 chandransh 48
    private enum ActionType{
49
        PURCHASE("1"),
50
        AUTH ("4"),
51
        CAPTURE("5");
52
        private String value;
53
        ActionType(String value) {
54
            this.value = value;
55
        }
56
        public String value(){
57
            return this.value;
58
        }
59
    }
60
 
61
    public HdfcEmiPaymentHandler() {
62
        // TODO Auto-generated constructor stub
63
    }
64
 
65
    static{
6420 rajveer 66
    	File resourceBaseDir = new File("/tmp/emi-resource/");
67
    	if(!resourceBaseDir.exists()){
68
    		resourceBaseDir.mkdir();
69
		}
6401 rajveer 70
    	int []  gatewayIds = {5,10,11,12};
71
    	for(int gatewayId: gatewayIds){
72
    		String resourceDirPath = "/tmp/emi-resource/" + gatewayId + "/";
73
	        try {
6402 rajveer 74
				InputStream inputStream = Class.class.getResourceAsStream(ConfigClient.getClient().get("emi_payment_resource_file_path") + gatewayId + File.separator + resourceFileName);
6401 rajveer 75
				File resourceDir = new File(resourceDirPath);
76
				if(!resourceDir.exists()){
77
					resourceDir.mkdir();
78
				}
79
 
80
				OutputStream outStream = new FileOutputStream(resourceDirPath  + resourceFileName);
81
				byte buf[]=new byte[1024];
82
				int len;
83
				while((len=inputStream.read(buf))>0)
84
					outStream.write(buf,0,len);
85
				outStream.close();
86
				inputStream.close();
87
 
88
				responseURL = ConfigClient.getClient().get("emi_payment_response_url");
89
	            errorURL = ConfigClient.getClient().get("emi_payment_error_url");
90
	        } catch (ConfigException e) {
91
	            log.error("Unable to get data from config server.");
92
	        } catch (FileNotFoundException e) {
93
				// TODO Auto-generated catch block
94
				e.printStackTrace();
95
			} catch (IOException e) {
96
				// TODO Auto-generated catch block
97
				e.printStackTrace();
4641 rajveer 98
			}
6401 rajveer 99
    	}
3583 chandransh 100
    }
101
 
102
    public static Map<String, String> capturePayment(Payment payment){
103
        String amount = "" + payment.getAmount();
104
        String gatewayPaymentId = payment.getGatewayPaymentId();
105
        log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
106
 
6401 rajveer 107
        String aliasName = null;
108
		try {
109
			aliasName = ConfigClient.getClient().get("emi_payment_alias_name" + payment.getGatewayId());
110
		} catch (ConfigException e1) {
111
			e1.printStackTrace();
112
		}
113
		String resourceDirPath = "/tmp/emi-resource/" + payment.getGatewayId() + "/";
114
 
3583 chandransh 115
        //Prepare resultMap to elicit failure behaviour in case anything goes wrong.
116
        Map<String, String> resultMap = new HashMap<String, String>();
4421 mandeep.dh 117
        resultMap.put(STATUS, Errors.CAPTURE_FAILURE.code);
118
        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
119
        resultMap.put(ERROR, Errors.CAPTURE_FAILURE.message);
3583 chandransh 120
 
121
        e24TranPipe pipe = new e24TranPipe();
4641 rajveer 122
        pipe.setResourcePath(resourceDirPath);
3583 chandransh 123
        pipe.setAlias(aliasName);
124
        pipe.setAction(ActionType.CAPTURE.value());
125
        pipe.setAmt(amount);
126
        pipe.setTrackId("" + payment.getId());
127
        pipe.setMember("SAHOLIC");
128
        pipe.setCurrencyCode(currencyCode);
129
        pipe.setTransId(payment.getGatewayTxnId());
130
 
131
        //Check if the values have been set properly
132
        log.info("Pipe Amount: " + pipe.getAmt());
133
        log.info("Pipe Action Code: " + pipe.getAction());
134
        log.info("Pipe Currency Code: " + pipe.getCurrencyCode());
135
        log.info("Pipe Track Id: " + pipe.getTrackId());
136
        log.info("Pipe Trans Id:" + pipe.getTransId());
137
 
138
        int captureStatus = e24TranPipe.FAILURE;
139
        try {
140
            captureStatus = pipe.performTransaction();
141
 
142
            log.info("Capture Status: " + captureStatus);
143
            log.info("Gateway Txn Status: " + pipe.getResult());
144
            log.info("Debug Msg: " + pipe.getDebugMsg());
145
            log.info("Auth: " + pipe.getAuth());
146
            log.info("Ref: " + pipe.getRef());
147
            log.info("TransId:" + pipe.getTransId());
148
            log.info("Amount: " + pipe.getAmt());
149
 
150
            resultMap.put(STATUS, "" + captureStatus);
151
            String result = pipe.getResult();
152
            resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim());       //This will return the result of the transaction. (Successful or Failed)
153
            if(captureStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){
154
                resultMap.put(ERROR, pipe.getErrorMsg());               // In case of any error, we only need to get the error message
4421 mandeep.dh 155
 
156
                if (captureStatus == CAPTURE_STATUS_FOR_CONNECTION_ISSUE) {
157
                    resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
158
                }
159
            }
160
            else {
3583 chandransh 161
                resultMap.put(CAPTURE_AUTH_ID, pipe.getAuth());         // Unique ID generated by Authorizer of the transaction
162
                resultMap.put(CAPTURE_REF_ID, pipe.getRef());           // Unique reference number generated during the transaction
163
                resultMap.put(CAPTURE_TXN_ID, pipe.getTransId());       // Unique Transaction ID generated after every successful transaction
164
                resultMap.put(CAPTURE_AMNT, pipe.getAmt());         // Original Amount of the transaction
165
            }
166
        } catch (NotEnoughDataException e) {
4421 mandeep.dh 167
            log.error(Errors.CAPTURE_FAILURE.message, e);
168
            resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
169
            resultMap.put(ERROR, e.getMessage());
3583 chandransh 170
        }
171
 
172
        return resultMap;
173
    }
174
 
175
    public static String initializeHdfcPayment(Payment payment, PaymentServiceHandler handler) throws Exception{
176
        long merchantPaymentId = payment.getId();
177
        double amount = payment.getAmount();
178
        e24PaymentPipe pipe = new e24PaymentPipe();
179
 
180
        try {
6401 rajveer 181
            initializePayment(pipe, merchantPaymentId, amount, payment.getGatewayId());
3583 chandransh 182
        } catch (ShoppingCartException e1) {
183
            log.error("Error while creating hdfc payment.", e1);
184
            throw e1;    //Payment couldn't be initialized. Will be redirected to the shipping page.
185
        } catch (TException e1) {
186
            log.error("Error while creating hdfc payment.", e1);
187
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
188
        }
189
 
190
        List<Attribute> attributes = null;
191
        try {
192
            attributes = getAttributesAndSetUdfs(pipe, payment.getMerchantTxnId());
193
        } catch (TransactionServiceException e1) {
194
            log.error("Error while setting udfs to payment.", e1);
195
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
196
        } catch (TException e1) {
197
            log.error("Error while setting udfs to payment.", e1);
198
            throw e1;   //Payment couldn't be initialized. Will be redirected to the shipping page.
199
        }
200
 
201
        try {
202
            if(pipe.performPaymentInitialization() != e24PaymentPipe.SUCCESS) {
203
                log.error("Error sending Payment Initialization Request: ");
204
                handler.updatePaymentDetails(merchantPaymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);
205
            } else {
206
                log.info("Payment Initialization Request processed successfully for payment Id: " + merchantPaymentId);
207
                String paymentID = pipe.getPaymentId();
208
                handler.updatePaymentDetails(merchantPaymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);
209
 
210
                String payURL = pipe.getPaymentPage();
211
                return payURL + "?PaymentID=" + paymentID;
212
            }
213
        } catch (NotEnoughDataException e) {
214
            log.error("Error while initializing payment.", e);
215
        }catch (Exception e) {
216
            log.error("Error while initializing payment.", e);
217
        }
218
        //If the code reaches here, the payment initialization was not successful and we've not returned the redirect URL.
219
        //Throw the exception so that any failovers can happen.
220
        throw new PaymentException(115, "Unable to initialize HDFC payment");
221
    }
222
 
223
    private static List<Attribute> getAttributesAndSetUdfs(e24PaymentPipe pipe, long txnId) throws TransactionServiceException, TException{
224
        StringBuilder orderDetails = new StringBuilder();
225
        StringBuilder billingAddress = new StringBuilder();
226
        String email = "";
227
        String contactNumber = "";
228
 
229
        //get udfs
230
        Transaction transaction;
231
        TransactionClient transactionServiceClient = null;
232
        try {
233
            transactionServiceClient = new TransactionClient();
234
        } catch (Exception e) {
235
            log.error("Unable to get transaction details", e);
236
        }
237
 
238
        in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();
239
        transaction = txnClient.getTransaction(txnId);
240
        orderDetails.append(transaction.getOrdersSize() + " ");
241
        for (Order order : transaction.getOrders()) {
242
            contactNumber= order.getCustomer_mobilenumber();
243
            email = order.getCustomer_email();
244
            billingAddress.append(" ");
245
            if(order.getCustomer_pincode()!=null){
246
                billingAddress.append(order.getCustomer_pincode());
247
            }
248
            if(order.getCustomer_city()!=null){
249
                billingAddress.append(" " + order.getCustomer_city());
250
            }
251
            if(order.getCustomer_address1()!=null){
252
                billingAddress.append(" " + order.getCustomer_address1());
253
            }
254
            if(order.getCustomer_address2()!=null){
255
                billingAddress.append(" " + order.getCustomer_address2());
256
            }
257
            if(order.getCustomer_state()!=null){
258
                billingAddress.append(" " + order.getCustomer_state());
259
            }
260
 
261
 
262
            for(LineItem line: order.getLineitems()){
263
                if(line.getBrand() != null){
264
                    orderDetails.append(line.getBrand());
265
                }
266
                if(line.getModel_name() != null){
267
                    orderDetails.append(line.getModel_name()); 
268
                }
269
                if(line.getModel_number() != null){
270
                    orderDetails.append(line.getModel_number());
271
                }
272
                if(line.getColor() != null){
273
                    orderDetails.append(line.getColor());
274
                }
275
                orderDetails.append(" ");
276
            }
277
 
278
        }
279
 
280
        Random random = new Random();
281
        String merchantInfo = ""+random.nextLong(); 
282
 
283
        String udf1 = formatUdf(orderDetails.toString()); 
284
        String udf2 = formatUdf(email);
285
        String udf3 = formatUdf(contactNumber);
286
        String udf4 = formatUdf(billingAddress.toString());
287
        String udf5 = merchantInfo;
288
 
289
        log.info("udf1:"  + udf1);
290
        log.info("udf2:"  + udf2);
291
        log.info("udf3:"  + udf3);
292
        log.info("udf4:"  + udf4);
293
        log.info("udf5:"  + udf5);
294
 
295
 
296
        pipe.setUdf1(udf1);      // UDF 1 - Order details
297
        pipe.setUdf2(udf2);      // UDF 2 - Email ID
298
        pipe.setUdf3(udf3);      // UDF 3 - Contact Number. 
299
        pipe.setUdf4(udf4);      // UDF 4 - Billing Address
300
        pipe.setUdf5(udf5);      // UDF 5 - Merchant specific
301
 
302
        List<Attribute> attributes = new ArrayList<Attribute>();
303
        Attribute attribute1 = new Attribute("udf1",udf1);
304
        Attribute attribute2 = new Attribute("udf2",udf2);
305
        Attribute attribute3 = new Attribute("udf3",udf3);
306
        Attribute attribute4 = new Attribute("udf4",udf4);
307
        Attribute attribute5 = new Attribute("udf5",udf5);
308
 
309
        attributes.add(attribute1);
310
        attributes.add(attribute2);
311
        attributes.add(attribute3);
312
        attributes.add(attribute4);
313
        attributes.add(attribute5);
314
 
315
        return attributes;
316
    }
317
 
6401 rajveer 318
    private static void initializePayment(e24PaymentPipe pipe, long merchantPaymentId, double amounta, long gatewayId) throws ShoppingCartException, TException{
319
    	String aliasName = null;
320
		try {
321
			aliasName = ConfigClient.getClient().get("emi_payment_alias_name" + gatewayId);
322
		} catch (ConfigException e1) {
323
			e1.printStackTrace();
324
		}
325
		String resourceDirPath = "/tmp/emi-resource/" + gatewayId + "/";
3583 chandransh 326
        String amount = (new Double(amounta)).toString();
327
 
328
        //Following is the code which initilize e24PaymentPipe with proper value
4641 rajveer 329
        pipe.setResourcePath(resourceDirPath); //mandatory 
3583 chandransh 330
        String as = pipe.getResourcePath();
331
        log.info("Resource= " +as);
332
 
333
        pipe.setAlias(aliasName);           //mandatory 
334
        String ab=pipe.getAlias();
335
        log.info("Alias= " +ab);
336
 
337
        pipe.setAction(ActionType.AUTH.value());            //mandatory 
338
        String ac=pipe.getAction();
339
        log.info("Action= " +ac);
340
 
341
        pipe.setResponseURL( responseURL ); //mandatory
342
        String at=pipe.getResponseURL();
343
        log.info("ResponseURL= "+at);
344
 
345
        //pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );     //mandatory
346
        pipe.setErrorURL( errorURL);
347
        String ak=pipe.getErrorURL();
348
        log.info("ErrorURL= " + ak);
349
 
350
 
351
        pipe.setAmt(amount);        
352
        String ap=pipe.getAmt();
353
        log.info("Amt= " + ap);
354
 
355
        pipe.setCurrency(currencyCode);
356
        String a=pipe.getCurrency();
357
        log.info("Currency= " + a);
358
 
359
        pipe.setLanguage("USA");
360
        String p=pipe.getLanguage();
361
        log.info("Language= "+ p);
362
 
363
        pipe.setTrackId((new Long(merchantPaymentId)).toString());
364
    }
365
 
366
    private static String formatUdf(String udfString){
367
        udfString = udfString.replaceAll(regex, replacement);
368
        if(udfString.length() > MAX_UDF_LENGTH){
369
            udfString = udfString.substring(0, MAX_UDF_LENGTH);
370
        }
371
        return udfString;
372
    }
373
}