Subversion Repositories SmartDukaan

Rev

Rev 4246 | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 4246 Rev 20112
Line 1... Line 1...
1
package in.shop2020.serving.controllers;
1
package in.shop2020.serving.controllers;
2
 
2
 
3
import in.shop2020.config.ConfigException;
3
import in.shop2020.config.ConfigException;
-
 
4
import in.shop2020.model.v1.order.RechargeOrder;
-
 
5
import in.shop2020.model.v1.order.RechargeOrderStatus;
4
import in.shop2020.payments.Attribute;
6
import in.shop2020.payments.Attribute;
5
import in.shop2020.payments.Payment;
7
import in.shop2020.payments.Payment;
6
import in.shop2020.payments.PaymentException;
8
import in.shop2020.payments.PaymentException;
7
import in.shop2020.payments.PaymentService.Client;
9
import in.shop2020.payments.PaymentService.Client;
8
import in.shop2020.payments.PaymentStatus;
10
import in.shop2020.payments.PaymentStatus;
Line 11... Line 13...
11
import in.shop2020.thrift.clients.TransactionClient;
13
import in.shop2020.thrift.clients.TransactionClient;
12
import in.shop2020.thrift.clients.UserClient;
14
import in.shop2020.thrift.clients.UserClient;
13
import in.shop2020.thrift.clients.config.ConfigClient;
15
import in.shop2020.thrift.clients.config.ConfigClient;
14
 
16
 
15
import java.io.IOException;
17
import java.io.IOException;
-
 
18
import java.security.MessageDigest;
-
 
19
import java.security.NoSuchAlgorithmException;
-
 
20
import java.text.SimpleDateFormat;
-
 
21
import java.util.ArrayList;
-
 
22
import java.util.Date;
-
 
23
import java.util.List;
-
 
24
import java.util.Map;
-
 
25
import java.util.TreeMap;
16
 
26
 
17
import javax.servlet.http.HttpServletRequest;
27
import javax.servlet.http.HttpServletRequest;
18
 
28
 
19
import org.apache.struts2.interceptor.ServletRequestAware;
29
import org.apache.struts2.interceptor.ServletRequestAware;
20
import org.apache.thrift.TException;
30
import org.apache.thrift.TException;
Line 30... Line 40...
30
 * @author Rajveer, Chandranshu
40
 * @author Rajveer, Chandranshu
31
 * @
41
 * @
32
 */
42
 */
33
public class HdfcPayResponseController implements ServletRequestAware{
43
public class HdfcPayResponseController implements ServletRequestAware{
34
 
44
 
-
 
45
	private static String rechargeResultUri;
-
 
46
 
-
 
47
	/**
-
 
48
	 * The secret key used to decode RC4 encoded data.
-
 
49
	 */
-
 
50
	private static String accountKey;
-
 
51
 
-
 
52
	private static String salt;
-
 
53
	
-
 
54
	private String eurl;
-
 
55
	private String surl;
-
 
56
 
35
	/**
57
	/**
36
	 * Enum of all statuses that can be returned by the HDFC gateway
58
	 * Enum of all statuses that can be returned by the HDFC gateway
37
	 * 
59
	 * 
38
	 * @author Chandranshu
60
	 * @author Chandranshu
39
	 * 
61
	 * 
Line 61... Line 83...
61
	private static Logger log = Logger.getLogger(Class.class);
83
	private static Logger log = Logger.getLogger(Class.class);
62
 
84
 
63
	public static String successUrl;
85
	public static String successUrl;
64
	public static String errorUrl;
86
	public static String errorUrl;
65
	
87
	
66
	public static String AMOUNT = "amt";
88
	public static String AMOUNT = "Amount";
67
	public static String TRACKID = "trackid";
-
 
68
	public static String RESULT = "result";
-
 
69
	public static String AUTH = "auth";
-
 
70
	public static String TRANID = "tranid";
-
 
71
	public static String PAYMENTID = "paymentid";
89
	public static String PAYMENTID = "PaymentID";
72
	public static String REF = "ref";
-
 
73
	public static String POSTDATE = "postdate";
-
 
74
	public static String ERROR = "Error";
90
	public static String ERROR = "Error";
-
 
91
	public static String MERCHANTREFNO="MerchantRefNo";
-
 
92
	public static String RESPONSECODE="ResponseCode";
-
 
93
	public static String SECUREHASH="SecureHash";
-
 
94
	public static String RESPONSEMESSAGE  = "ResponseMessage";
75
	public static String ERRORTEXT = "ErrorText";
95
	public static String ISFLAGGED = "IsFlagged";
-
 
96
	public static String TRANSACTIONID ="TransactionID";
-
 
97
	public static String PAYMENTMETHOD = "PaymentMethod";
76
	public static String UDF5 = "udf5";	
98
	public static String REQUESTID= "RequestID";
-
 
99
	public static String DATECREATED = "DateCreated";
-
 
100
	public static String SUCCESS= "0";//responsecode for successfull transaction by hdfc gateway
77
 
101
 
78
	static{
102
	static{
79
		try {
103
		try {
-
 
104
			ConfigClient cc = ConfigClient.getClient();
80
			successUrl = ConfigClient.getClient().get("payment_success_url");
105
			successUrl = cc.get("payment_success_url");
81
			errorUrl = ConfigClient.getClient().get("payment_error_url");
106
			errorUrl = cc.get("payment_error_url");
-
 
107
			rechargeResultUri = cc.get("recharge_result_uri");
82
		} catch (ConfigException e) {
108
		} catch (ConfigException e) {
83
			log.error("Unable to get success and error usr info from config server.");
109
			log.error("Unable to get success and error usr info from config server.");
84
		}
110
		}
85
	}
111
	}
86
	
-
 
87
	String redirectUrl;
112
	String redirectUrl;
88
	
113
	
89
	public HdfcPayResponseController() {
114
	public HdfcPayResponseController() {
90
		
115
		
91
	}
116
	}
-
 
117
	
-
 
118
	private Map<String, String> paymentParams = new TreeMap<String, String>();
92
 
119
 
93
	/**
120
	/**
94
	 * Sets the redirectUrl instance variable which is used in the view to
121
	 * Sets the redirectUrl instance variable which is used in the view to
95
	 * redirect the customer to the success or failure page.
122
	 * redirect the customer to the success or failure page.
96
	 * 
123
	 * 
Line 98... Line 125...
98
	 * @throws IOException
125
	 * @throws IOException
99
	 * @throws SecurityException
126
	 * @throws SecurityException
100
	 */
127
	 */
101
	public String create() throws IOException, SecurityException{
128
	public String create() throws IOException, SecurityException{
102
		log.info("Inside hdfc pay response Create");
129
		log.info("Inside hdfc pay response Create");
-
 
130
		eurl = errorUrl;
-
 
131
		surl = successUrl;
-
 
132
		updatePaymentParams(request.getParameterMap());
103
		
133
 
104
		PaymentClient paymentServiceClient = null;
134
		PaymentClient paymentServiceClient = null;
105
		TransactionClient transactionServiceClient = null;
135
		TransactionClient transactionServiceClient = null;
106
		UserClient userServiceClient = null;
136
		UserClient userServiceClient = null;
107
		try{
137
		try {
-
 
138
			userServiceClient = new UserClient();
108
			paymentServiceClient = new PaymentClient();
139
			paymentServiceClient = new PaymentClient();
109
			transactionServiceClient = new TransactionClient();
140
			transactionServiceClient = new TransactionClient();
110
			userServiceClient = new UserClient();
-
 
111
		}catch(Exception e){
141
		} catch (Exception e) {
112
			//Nothing to worry. lets move forward
-
 
113
			log.error("Unable to initialize one of the clients", e);
142
			log.error("Unable to initialize one of the clients", e);
114
		}
143
		}
115
		
144
		
116
		Long txnId = null;
145
		long merchantPaymentId = Long.parseLong(paymentParams.get(MERCHANTREFNO));
117
		
-
 
118
		String paymentId = request.getParameter(PAYMENTID);
146
		String gatewayPaymentId = paymentParams.get(PAYMENTID);
119
		String result = request.getParameter(RESULT);
147
		double amount = Double.parseDouble(paymentParams.get(AMOUNT));
120
		String trackId = request.getParameter(TRACKID);
148
		String gatewayTxnStatus = paymentParams.get(RESPONSECODE);
121
		long merchantPaymentId = Long.parseLong(trackId);
149
		String hash = paymentParams.get(SECUREHASH);
122
		String amount = request.getParameter(AMOUNT);
150
		String transactionId = paymentParams.get(TRANSACTIONID);
123
		String errorText = request.getParameter(ERRORTEXT);
151
		String requestId = paymentParams.get(REQUESTID);
124
		
-
 
125
		//FIXME dump them somewhere
-
 
126
		String udf5=request.getParameter(UDF5);
152
		String error = paymentParams.get(ERROR);
127
		//FIXME hdfc is sending comma separated amount, which is very disappointing. May be we get more surprises moving forward.
-
 
128
		amount= amount.replace(",", "");
153
		List<Attribute> attributes = new ArrayList<Attribute>();
129
		
154
		
130
		//Setting redirect URL to the error URL value by default.
-
 
131
		this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
-
 
132
		
155
 
133
		Client paymentClient = paymentServiceClient.getClient();
-
 
134
		Payment payment = null;
156
		Payment payment = null;
-
 
157
		Long txnId = null;
135
		try {
158
		try {
136
			payment = paymentClient.getPayment(merchantPaymentId);
159
			payment = paymentServiceClient.getClient().getPayment(merchantPaymentId);
137
			txnId = payment.getMerchantTxnId();
160
			txnId = payment.getMerchantTxnId();
138
			
-
 
139
			if(!validatePaymentParams(paymentId, amount, udf5, payment))
-
 
140
				return "index";
-
 
141
		} catch (PaymentException e1) {
161
		} catch (PaymentException e1) {
142
			log.error("Payment exception. It is serious, check merchant payment id + " + merchantPaymentId, e1);
162
			log.error("Payment exception. It is serious, check merchant payment id + " + merchantPaymentId, e1);
143
		} catch (TException e1) {
163
		} catch (TException e1) {
144
			log.error("Thrift exception. Check payment id "+ merchantPaymentId, e1);
164
			log.error("Thrift exception. Check payment id "+ merchantPaymentId, e1);
145
		}
165
		}
146
		
166
		
147
		if (result != null && result.trim().equals(PaymentReturnStatus.APPROVED.value())) {
167
		if(payment.getStatus() != PaymentStatus.INIT){
148
			log.info("Payment " + merchantPaymentId + " authorized successfully. Updating the database.");
168
			// We have already processed a response for this payment. Processing
149
			String description = "Payment authorized";
169
			// it again may fail his orders. So, let's ask him to check his
-
 
170
			// account.
150
			updatePaymentDetails(merchantPaymentId, description, PaymentStatus.AUTHORIZED, request, paymentClient);
171
			return "ebs-pay-response-maybe";
-
 
172
		}
151
 
173
 
-
 
174
		if(payment.isIsDigital()){
-
 
175
			eurl = rechargeResultUri;
-
 
176
			surl = rechargeResultUri;
-
 
177
		}
-
 
178
		
-
 
179
		if(!validatePaymentParams(amount, payment, hash)){
152
            CommonPaymentService.processSuccessfulTxn(txnId, userServiceClient, transactionServiceClient, false);
180
			this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
-
 
181
			return "index";
-
 
182
		}
153
 
183
 
-
 
184
		if(gatewayTxnStatus.equalsIgnoreCase(SUCCESS)){
-
 
185
			try {
-
 
186
				attributes.add(new Attribute(DATECREATED, paymentParams.get(DATECREATED)));
-
 
187
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
-
 
188
						"", gatewayTxnStatus, "Transaction captured at PG", 
-
 
189
						transactionId, "", requestId, "", PaymentStatus.SUCCESS,
-
 
190
								new SimpleDateFormat().format(new Date()), attributes);
-
 
191
			} catch (PaymentException e) {
-
 
192
				this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
-
 
193
				return "index";
-
 
194
			} catch (TException e) {
-
 
195
				this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
-
 
196
				return "index";
-
 
197
			}
-
 
198
            if(payment.isIsDigital()){
-
 
199
            	RechargeOrder rechargeOrder = null;
-
 
200
                try {
-
 
201
                    rechargeOrder = transactionServiceClient.getClient().getRechargeOrdersForTransaction(txnId);
-
 
202
                } catch (Exception e1) {
-
 
203
                    log.error("Problem with txn client while getting recharge object", e1);
-
 
204
    				this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
-
 
205
    				return "index";
-
 
206
                }
-
 
207
                
-
 
208
		        try {
-
 
209
		            PaymentClient pcl = new PaymentClient();
-
 
210
		            boolean isCaptured = pcl.getClient().capturePayment(txnId, true);
-
 
211
		            
-
 
212
		            //Retry in case we are not able to capture first time
-
 
213
		            if(!isCaptured){
-
 
214
		            	Thread.sleep(2000);
-
 
215
		            	isCaptured = pcl.getClient().capturePayment(txnId, true);
-
 
216
		            }
-
 
217
		            if(!isCaptured){
-
 
218
		            	Thread.sleep(2000);
-
 
219
		            	isCaptured = pcl.getClient().capturePayment(txnId, true);
-
 
220
		            }
-
 
221
		            
-
 
222
		            if(isCaptured) {
-
 
223
		                transactionServiceClient.getClient().updateRechargeOrderStatus(rechargeOrder.getId(), RechargeOrderStatus.PAYMENT_SUCCESSFUL);
-
 
224
		            } else {
-
 
225
                        transactionServiceClient.getClient().updateRechargeOrderStatus(rechargeOrder.getId(), RechargeOrderStatus.PAYMENT_FAILED);
-
 
226
		            }
-
 
227
		        } catch (Exception e) {
-
 
228
		            log.error("Problem with txn client while trying to recharge", e);
-
 
229
		        }
-
 
230
            } else {
-
 
231
		        CommonPaymentService.processSuccessfulTxn(txnId, userServiceClient, transactionServiceClient, false);
-
 
232
            }
154
            this.redirectUrl = successUrl + "?paymentId=" + merchantPaymentId;
233
            this.redirectUrl = surl + "?paymentId=" + merchantPaymentId;
-
 
234
			
155
		} else {
235
		} else{
-
 
236
			try {
-
 
237
				attributes.add(new Attribute(ERROR, error));
156
			updatePaymentDetails(merchantPaymentId, errorText, PaymentStatus.FAILED, request, paymentClient);
238
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
-
 
239
						"", gatewayTxnStatus, "Payment Failed at PG ", "", "", "", "", PaymentStatus.FAILED, new SimpleDateFormat().format(new Date()), attributes);
-
 
240
			} catch (PaymentException e) {
-
 
241
			    log.error("Unable to mark the payment as failed", e);
-
 
242
			} catch (TException e) {
-
 
243
			    log.error("Unable to mark the payment as failed", e);
-
 
244
			}
157
 
245
 
-
 
246
			if(!payment.isIsDigital()) {
158
			CommonPaymentService.processFailedTxn(txnId, transactionServiceClient);
247
				CommonPaymentService.processFailedTxn(txnId, transactionServiceClient);
-
 
248
			}
159
 
249
 
160
			this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
250
			this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
161
		}
251
		}
162
		
252
 
-
 
253
		log.info("User will be redirected to: " + surl + "?paymentId=" + merchantPaymentId);
163
		return "index";
254
		return "index";
-
 
255
 
-
 
256
		
-
 
257
	}
-
 
258
	
-
 
259
	
-
 
260
	private boolean validatePaymentParams(double returnedAmount, Payment payment, String hash){
-
 
261
		boolean hashCheckResult= hash.equals(getSecureHash());
-
 
262
		hashCheckResult = true;//remove this and implement hash check
-
 
263
		if(!(payment != null && Math.abs(payment.getAmount() - returnedAmount) <= 0.50
-
 
264
				&& hashCheckResult)){
-
 
265
			// We did not request this payment or the authorised amount is different.
-
 
266
			log.error("Checks and balance failed on returned data");
-
 
267
			return false;
-
 
268
		}
-
 
269
		return true;
-
 
270
	}
-
 
271
 
-
 
272
 
-
 
273
	public String getSecureHash(){
-
 
274
		/*try{
-
 
275
			
-
 
276
			//to do implement hash check
-
 
277
		}catch(Exception nsae){
-
 
278
			log.error("No such algorithm exception");
-
 
279
			return null;
-
 
280
		}*/
-
 
281
		return "";
164
	}
282
	}
165
 
283
 
-
 
284
	private void updatePaymentParams(Map map){
-
 
285
		for(Object key : map.keySet()){
-
 
286
		    String keyStr = (String)key;
-
 
287
		    String[] vals = (String[])map.get(keyStr);
-
 
288
		    String value = vals[0];
-
 
289
		    System.out.println("Key " + (String)key + "     :    " + value);
-
 
290
		    paymentParams.put(keyStr, value);
-
 
291
		}
-
 
292
	}
166
	private boolean validatePaymentParams(String paymentId,	String amount, String udf5, Payment payment) {
293
/*	private boolean validatePaymentParams(String paymentId,	String amount, String udf5, Payment payment) {
167
		long merchantPaymentId = payment.getPaymentId();
294
		long merchantPaymentId = payment.getPaymentId();
168
		String dbUdf5="";
295
		String dbUdf5="";
169
		double dbAmount = payment.getAmount();
296
		double dbAmount = payment.getAmount();
170
		for(Attribute attribute: payment.getAttributes()){
297
		for(Attribute attribute: payment.getAttributes()){
171
			if(attribute.getName().trim().equalsIgnoreCase(UDF5)){
298
			if(attribute.getName().trim().equalsIgnoreCase(UDF5)){
Line 180... Line 307...
180
			log.error("Checks and balance failed on returned data");
307
			log.error("Checks and balance failed on returned data");
181
			this.redirectUrl =  errorUrl + "?paymentId="+merchantPaymentId;
308
			this.redirectUrl =  errorUrl + "?paymentId="+merchantPaymentId;
182
			return false;
309
			return false;
183
		}
310
		}
184
		return true;
311
		return true;
185
	}
312
	}*/
186
 
313
 
187
	private void updatePaymentDetails(long merchantPaymentId, String message, PaymentStatus status, HttpServletRequest req, Client paymentClient) {
314
/*	private void updatePaymentDetails(long merchantPaymentId, String message, PaymentStatus status, HttpServletRequest req, Client paymentClient) {
188
		String paymentId = request.getParameter(PAYMENTID);
315
		String paymentId = request.getParameter(PAYMENTID);
189
		String result = request.getParameter(RESULT);
-
 
190
		String postdate = request.getParameter(POSTDATE);
-
 
191
		String tranId = request.getParameter(TRANID);
-
 
192
		String auth = request.getParameter(AUTH);
-
 
193
		String ref = request.getParameter(REF);
-
 
194
		
316
		
195
		String sessionId = request.getSession().getId();
317
		String sessionId = request.getSession().getId();
196
		String errorNo = request.getParameter(ERROR);
318
		String errorNo = request.getParameter(ERROR);
197
		try {
319
		try {
198
			paymentClient.updatePaymentDetails(merchantPaymentId, paymentId, sessionId, result, message, tranId, auth, ref, errorNo, status, postdate, null);
320
			paymentClient.updatePaymentDetails(merchantPaymentId, paymentId, sessionId, result, message, tranId, auth, ref, errorNo, status, postdate, null);
199
		} catch (PaymentException e1) {
321
		} catch (PaymentException e1) {
200
			log.error("Unable to update payment details in our database.", e1);
322
			log.error("Unable to update payment details in our database.", e1);
201
		} catch (TException e1) {
323
		} catch (TException e1) {
202
			log.error("Unable to update payment details in our database. Thrift exception.", e1);
324
			log.error("Unable to update payment details in our database. Thrift exception.", e1);
203
		}
325
		}
204
	}
326
	}*/
205
	
327
	
206
	public String getRedirectUrl(){
328
	public String getRedirectUrl(){
207
		return this.redirectUrl;
329
		return this.redirectUrl;
208
	}
330
	}
209
 
331