Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
719 rajveer 1
package in.shop2020.serving.controllers;
2
 
741 rajveer 3
import in.shop2020.config.ConfigException;
853 rajveer 4
import in.shop2020.payments.Attribute;
741 rajveer 5
import in.shop2020.payments.Payment;
6
import in.shop2020.payments.PaymentException;
894 rajveer 7
import in.shop2020.payments.PaymentService.Client;
719 rajveer 8
import in.shop2020.payments.PaymentStatus;
1905 chandransh 9
import in.shop2020.serving.services.CommonPaymentService;
2334 chandransh 10
import in.shop2020.serving.services.HdfcPaymentService;
11
import in.shop2020.serving.services.IPaymentService;
719 rajveer 12
import in.shop2020.thrift.clients.PaymentServiceClient;
13
import in.shop2020.thrift.clients.TransactionServiceClient;
14
import in.shop2020.thrift.clients.UserContextServiceClient;
15
import in.shop2020.thrift.clients.config.ConfigClient;
16
 
17
import java.io.IOException;
2334 chandransh 18
import java.text.SimpleDateFormat;
19
import java.util.ArrayList;
20
import java.util.Date;
21
import java.util.List;
22
import java.util.Map;
719 rajveer 23
 
24
import javax.servlet.http.HttpServletRequest;
25
 
26
import org.apache.struts2.interceptor.ServletRequestAware;
741 rajveer 27
import org.apache.thrift.TException;
1044 chandransh 28
import org.apache.log4j.Logger;
719 rajveer 29
 
2334 chandransh 30
/**
31
 * This controller processes payment data received on the back channel from
32
 * HDFC. Since this request doesn't have any cookies associated with it, we
33
 * can't extend the BaseController which is intercepted by UserInterceptor. Thus
34
 * to get the parameters from the request, it implements the ServletRequestAware
35
 * interface.
36
 * 
37
 * @author Rajveer, Chandranshu
38
 * @
39
 */
40
public class HdfcPayResponseController implements ServletRequestAware{
41
 
42
	/**
43
	 * Enum of all statuses that can be returned by the HDFC gateway
44
	 * 
45
	 * @author Chandranshu
46
	 * 
47
	 */
719 rajveer 48
	private enum PaymentReturnStatus{
2334 chandransh 49
		APPROVED("APPROVED"),
50
		NOT_APPROVED("NOT APPROVED"),
719 rajveer 51
		CAPTURED("CAPTURED"),
52
		NOT_CAPTURED ("NOT CAPTURED"),
53
		CANCELLED ("CANCELLED"),
54
		DENIED_BY_RISK("DENIED BY RISK"),
55
		HOST_TIMEOUT("HOST TIMEOUT");
56
		private String value;
57
		PaymentReturnStatus(String value) {
58
			this.value = value;
59
		}
60
		public String value(){
61
			return this.value;
62
		}
63
	}
64
 
65
	HttpServletRequest request;
66
 
1044 chandransh 67
	//private static Logger log = LoggerFactory.getLogger(HdfcPayResponseController.class);
68
	private static Logger log = Logger.getLogger(Class.class);
719 rajveer 69
 
894 rajveer 70
	public static String successUrl;
71
	public static String errorUrl;
72
 
719 rajveer 73
	public static String AMOUNT = "amt";
74
	public static String TRACKID = "trackid";
75
	public static String RESULT = "result";
76
	public static String AUTH = "auth";
77
	public static String TRANID = "tranid";
78
	public static String PAYMENTID = "paymentid";
79
	public static String REF = "ref";
80
	public static String POSTDATE = "postdate";
81
	public static String ERROR = "Error";
82
	public static String ERRORTEXT = "ErrorText";
1905 chandransh 83
	public static String UDF5 = "udf5";	
894 rajveer 84
 
85
	static{
719 rajveer 86
		try {
894 rajveer 87
			successUrl = ConfigClient.getClient().get("payment_success_url");
88
			errorUrl = ConfigClient.getClient().get("payment_error_url");
89
		} catch (ConfigException e) {
90
			log.error("Unable to get success and error usr info from config server.");
719 rajveer 91
		}
92
	}
93
 
1905 chandransh 94
	String redirectUrl;
894 rajveer 95
 
96
	public HdfcPayResponseController() {
97
 
98
	}
2334 chandransh 99
 
100
	/**
101
	 * Sets the redirectUrl instance variable which is used in the view to
102
	 * redirect the customer to the success or failure page.
103
	 * 
104
	 * @return index in all cases.
105
	 * @throws IOException
106
	 * @throws SecurityException
107
	 */
719 rajveer 108
	public String create() throws IOException, SecurityException{
894 rajveer 109
		log.info("Inside hdfc pay response Create");
719 rajveer 110
 
894 rajveer 111
		PaymentServiceClient paymentServiceClient = null;
112
		TransactionServiceClient transactionServiceClient = null;
113
		UserContextServiceClient userServiceClient = null;
114
		try{
115
			paymentServiceClient = new PaymentServiceClient();
116
			transactionServiceClient = new TransactionServiceClient();
117
			userServiceClient = new UserContextServiceClient();
118
		}catch(Exception e){
119
			//Nothing to worry. lets move forward
2334 chandransh 120
			log.error("Unable to initialize one of the clients", e);
894 rajveer 121
		}
122
 
1905 chandransh 123
		Long txnId = null;
124
 
125
		String paymentId = request.getParameter(PAYMENTID);
126
		String result = request.getParameter(RESULT);
127
		String trackId = request.getParameter(TRACKID);
128
		long merchantPaymentId = Long.parseLong(trackId);
129
		String amount = request.getParameter(AMOUNT);
130
		String errorText = request.getParameter(ERRORTEXT);
131
 
719 rajveer 132
		//FIXME dump them somewhere
853 rajveer 133
		String udf5=request.getParameter(UDF5);
894 rajveer 134
		//FIXME hdfc is sending comma separated amount, which is very disappointing. May be we get more surprises moving forward.
856 rajveer 135
		amount= amount.replace(",", "");
894 rajveer 136
 
2334 chandransh 137
		//Setting redirect URL to the error URL value by default.
138
		this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
139
 
894 rajveer 140
		Client paymentClient = paymentServiceClient.getClient();
2334 chandransh 141
		Payment payment = null;
741 rajveer 142
		try {
2334 chandransh 143
			payment = paymentClient.getPayment(merchantPaymentId);
1905 chandransh 144
			txnId = payment.getMerchantTxnId();
145
 
146
			if(!validatePaymentParams(paymentId, amount, udf5, payment))
741 rajveer 147
				return "index";
148
		} catch (PaymentException e1) {
2334 chandransh 149
			log.error("Payment exception. It is serious, check merchant payment id + " + merchantPaymentId, e1);
741 rajveer 150
		} catch (TException e1) {
2334 chandransh 151
			log.error("Thrift exception. Check payment id "+ merchantPaymentId, e1);
741 rajveer 152
		}
719 rajveer 153
 
2334 chandransh 154
		if (result != null && result.trim().equals(PaymentReturnStatus.APPROVED.value())) {
155
			log.info("Payment " + merchantPaymentId + " authorized successfully. Updating the database.");
156
			String description = "Payment authorized";
157
			updatePaymentDetails(merchantPaymentId, description, PaymentStatus.AUTHORIZED, request, paymentClient);
894 rajveer 158
 
2334 chandransh 159
			log.info("Capturing payment with id: " + merchantPaymentId);
160
			Map<String, String> captureResult = HdfcPaymentService.capturePayment(payment, request.getParameter(TRANID));
161
			String captureStatus = captureResult.get(IPaymentService.STATUS);
162
			String gatewayStatus = captureResult.get(IPaymentService.GATEWAY_STATUS);
163
 
164
			List<Attribute> attributes = new ArrayList<Attribute>();
165
			if(!captureStatus.trim().equals("0") || !PaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)){
166
				//Failure
167
				log.info("Capture attempt failed for payment with id: " + merchantPaymentId);
168
				description = captureResult.get(IPaymentService.ERROR);
169
				String errorCode = captureResult.get(IPaymentService.ERR_CODE);				
170
 
171
				try {
172
					paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, paymentId,
173
							null, null, description, null, null, null, errorCode, PaymentStatus.FAILED, null, attributes);
174
				} catch (PaymentException e) {
175
					log.error("Error while updating failed capture payment attempt: ", e);
176
				} catch (TException e) {
177
					log.error("Error while updating failed capture payment attempt: ", e);
178
				}
179
				//DataLogger.logData(EventType.PAYMENT_FAILURE.name(), session.getId(), Long.toString(userinfo.getUserId()), userinfo.getEmail(), Long.toString(merchantPaymentId), paymentId, gatewayTxnStatus, description, errorCode);
180
				this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
181
			}else{
182
				//Success
183
				log.info("Capture attempt successful for payment with id: " + merchantPaymentId);
184
				description = "Payment Captured";
185
				attributes.add(new Attribute(IPaymentService.CAPTURE_TXN_ID, captureResult.get(IPaymentService.CAPTURE_TXN_ID)));
186
				attributes.add(new Attribute(IPaymentService.CAPTURE_REF_ID, captureResult.get(IPaymentService.CAPTURE_REF_ID)));
187
				attributes.add(new Attribute(IPaymentService.CAPTURE_AUTH_ID, captureResult.get(IPaymentService.CAPTURE_AUTH_ID)));
188
 
189
				SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
190
				attributes.add(new Attribute(IPaymentService.CAPTURE_TIME, captureTimeDateFormatter.format(new Date())));
191
 
192
				try {
193
					paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, paymentId,
194
							null, gatewayStatus, null, null, null, null, null, PaymentStatus.SUCCESS, null, attributes);
195
				} catch (PaymentException e) {
196
					log.error("Error while updating successful capture payment attempt: ", e);
197
				} catch (TException e) {
198
					log.error("Error while updating successful capture payment attempt: ", e);
199
				}
200
 
201
				CommonPaymentService.processSuccessfulTxn(txnId, userServiceClient, transactionServiceClient);
1905 chandransh 202
 
2334 chandransh 203
				this.redirectUrl = successUrl + "?paymentId=" + merchantPaymentId;
204
				//DataLogger.logData(EventType.PAYMENT_SUCCESS.name(), session.getId(), Long.toString(userinfo.getUserId()), userinfo.getEmail(), Long.toString(merchantPaymentId), paymentId, gatewayTxnStatus, description, captureStatus);
205
			}			
1905 chandransh 206
		} else {
207
			updatePaymentDetails(merchantPaymentId, errorText, PaymentStatus.FAILED, request, paymentClient);
208
 
209
			CommonPaymentService.processFailedTxn(txnId, transactionServiceClient);
210
 
211
			this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
1554 varun.gupt 212
		}
1905 chandransh 213
 
214
		return "index";
215
	}
216
 
217
	private boolean validatePaymentParams(String paymentId,	String amount, String udf5, Payment payment) {
218
		long merchantPaymentId = payment.getPaymentId();
219
		String dbUdf5="";
220
		double dbAmount = payment.getAmount();
221
		for(Attribute attribute: payment.getAttributes()){
222
			if(attribute.getName().trim().equalsIgnoreCase(UDF5)){
223
				dbUdf5 = attribute.getValue();
719 rajveer 224
			}
225
		}
1905 chandransh 226
		// verify 3 things:  udf5, amount and paymentid
227
		//FIXME should we first dump the data and then verify these things. ?? 
2134 chandransh 228
		double returnedAmount = Double.parseDouble(amount);
229
		log.info(paymentId+ ":"+ payment.getGatewayPaymentId() + "\n" + returnedAmount + ":" + dbAmount + "\n" + dbUdf5 + ":" + udf5 );
230
		if(!(paymentId.equalsIgnoreCase(payment.getGatewayPaymentId()) && (Math.abs(dbAmount - returnedAmount) <= 0.50) && udf5.equalsIgnoreCase(dbUdf5))){
1905 chandransh 231
			log.error("Checks and balance failed on returned data");
232
			this.redirectUrl =  errorUrl + "?paymentId="+merchantPaymentId;
233
			return false;
234
		}
235
		return true;
236
	}
237
 
238
	private void updatePaymentDetails(long merchantPaymentId, String message, PaymentStatus status, HttpServletRequest req, Client paymentClient) {
239
		String paymentId = request.getParameter(PAYMENTID);
240
		String result = request.getParameter(RESULT);
241
		String postdate = request.getParameter(POSTDATE);
242
		String tranId = request.getParameter(TRANID);
243
		String auth = request.getParameter(AUTH);
244
		String ref = request.getParameter(REF);
719 rajveer 245
 
1905 chandransh 246
		String sessionId = request.getSession().getId();
247
		String errorNo = request.getParameter(ERROR);
248
		try {
249
			paymentClient.updatePaymentDetails(merchantPaymentId, paymentId, sessionId, result, message, tranId, auth, ref, errorNo, status, postdate, null);
250
		} catch (PaymentException e1) {
2334 chandransh 251
			log.error("Unable to update payment details in our database.", e1);
1905 chandransh 252
		} catch (TException e1) {
2334 chandransh 253
			log.error("Unable to update payment details in our database. Thrift exception.", e1);
1905 chandransh 254
		}
719 rajveer 255
	}
256
 
257
	public String getRedirectUrl(){
258
		return this.redirectUrl;
259
	}
260
 
261
	@Override
262
	public void setServletRequest(HttpServletRequest request) {
263
		this.request = request;
264
		for(Object param: request.getParameterMap().keySet()){
2334 chandransh 265
			log.info("PARAMS: " + param + " = "+ request.getParameter((String)param));
719 rajveer 266
		}
267
	}
1554 varun.gupt 268
}