Subversion Repositories SmartDukaan

Rev

Rev 4643 | Rev 6402 | 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{
6401 rajveer 66
    	int []  gatewayIds = {5,10,11,12};
67
    	for(int gatewayId: gatewayIds){
68
    		String resourceDirPath = "/tmp/emi-resource/" + gatewayId + "/";
69
	        try {
70
				InputStream inputStream = Class.class.getResourceAsStream(ConfigClient.getClient().get("emi_payment_resource_file_path") + resourceFileName);
71
				File resourceDir = new File(resourceDirPath);
72
				if(!resourceDir.exists()){
73
					resourceDir.mkdir();
74
				}
75
 
76
				OutputStream outStream = new FileOutputStream(resourceDirPath  + resourceFileName);
77
				byte buf[]=new byte[1024];
78
				int len;
79
				while((len=inputStream.read(buf))>0)
80
					outStream.write(buf,0,len);
81
				outStream.close();
82
				inputStream.close();
83
 
84
				responseURL = ConfigClient.getClient().get("emi_payment_response_url");
85
	            errorURL = ConfigClient.getClient().get("emi_payment_error_url");
86
	        } catch (ConfigException e) {
87
	            log.error("Unable to get data from config server.");
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();
4641 rajveer 94
			}
6401 rajveer 95
    	}
3583 chandransh 96
    }
97
 
98
    public static Map<String, String> capturePayment(Payment payment){
99
        String amount = "" + payment.getAmount();
100
        String gatewayPaymentId = payment.getGatewayPaymentId();
101
        log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
102
 
6401 rajveer 103
        String aliasName = null;
104
		try {
105
			aliasName = ConfigClient.getClient().get("emi_payment_alias_name" + payment.getGatewayId());
106
		} catch (ConfigException e1) {
107
			e1.printStackTrace();
108
		}
109
		String resourceDirPath = "/tmp/emi-resource/" + payment.getGatewayId() + "/";
110
 
3583 chandransh 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);
3583 chandransh 116
 
117
        e24TranPipe pipe = new e24TranPipe();
4641 rajveer 118
        pipe.setResourcePath(resourceDirPath);
3583 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 {
3583 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());
3583 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 {
6401 rajveer 177
            initializePayment(pipe, merchantPaymentId, amount, payment.getGatewayId());
3583 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();
207
                return payURL + "?PaymentID=" + paymentID;
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
        }
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");
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;
227
        TransactionClient transactionServiceClient = null;
228
        try {
229
            transactionServiceClient = new TransactionClient();
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
 
6401 rajveer 314
    private static void initializePayment(e24PaymentPipe pipe, long merchantPaymentId, double amounta, long gatewayId) throws ShoppingCartException, TException{
315
    	String aliasName = null;
316
		try {
317
			aliasName = ConfigClient.getClient().get("emi_payment_alias_name" + gatewayId);
318
		} catch (ConfigException e1) {
319
			e1.printStackTrace();
320
		}
321
		String resourceDirPath = "/tmp/emi-resource/" + gatewayId + "/";
3583 chandransh 322
        String amount = (new Double(amounta)).toString();
323
 
324
        //Following is the code which initilize e24PaymentPipe with proper value
4641 rajveer 325
        pipe.setResourcePath(resourceDirPath); //mandatory 
3583 chandransh 326
        String as = pipe.getResourcePath();
327
        log.info("Resource= " +as);
328
 
329
        pipe.setAlias(aliasName);           //mandatory 
330
        String ab=pipe.getAlias();
331
        log.info("Alias= " +ab);
332
 
333
        pipe.setAction(ActionType.AUTH.value());            //mandatory 
334
        String ac=pipe.getAction();
335
        log.info("Action= " +ac);
336
 
337
        pipe.setResponseURL( responseURL ); //mandatory
338
        String at=pipe.getResponseURL();
339
        log.info("ResponseURL= "+at);
340
 
341
        //pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId );     //mandatory
342
        pipe.setErrorURL( errorURL);
343
        String ak=pipe.getErrorURL();
344
        log.info("ErrorURL= " + ak);
345
 
346
 
347
        pipe.setAmt(amount);        
348
        String ap=pipe.getAmt();
349
        log.info("Amt= " + ap);
350
 
351
        pipe.setCurrency(currencyCode);
352
        String a=pipe.getCurrency();
353
        log.info("Currency= " + a);
354
 
355
        pipe.setLanguage("USA");
356
        String p=pipe.getLanguage();
357
        log.info("Language= "+ p);
358
 
359
        pipe.setTrackId((new Long(merchantPaymentId)).toString());
360
    }
361
 
362
    private static String formatUdf(String udfString){
363
        udfString = udfString.replaceAll(regex, replacement);
364
        if(udfString.length() > MAX_UDF_LENGTH){
365
            udfString = udfString.substring(0, MAX_UDF_LENGTH);
366
        }
367
        return udfString;
368
    }
369
}