Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
1905 chandransh 1
package in.shop2020.serving.controllers;
2
 
2118 chandransh 3
import java.io.BufferedReader;
1905 chandransh 4
import java.io.ByteArrayInputStream;
5
import java.io.IOException;
2118 chandransh 6
import java.io.InputStreamReader;
1905 chandransh 7
import java.util.ArrayList;
8
import java.util.List;
9
import java.util.Map;
10
import java.util.StringTokenizer;
11
import java.util.TreeMap;
12
 
13
import in.shop2020.config.ConfigException;
2263 vikas 14
import in.shop2020.datalogger.EventType;
1905 chandransh 15
import in.shop2020.payments.Attribute;
16
import in.shop2020.payments.Payment;
17
import in.shop2020.payments.PaymentException;
18
import in.shop2020.payments.PaymentStatus;
19
import in.shop2020.serving.services.CommonPaymentService;
20
import in.shop2020.serving.services.EbsPaymentService;
1999 vikas 21
import in.shop2020.serving.utils.DataLogger;
1905 chandransh 22
import in.shop2020.serving.utils.ebs.Base64;
23
import in.shop2020.serving.utils.ebs.RC4;
24
import in.shop2020.thrift.clients.PaymentServiceClient;
25
import in.shop2020.thrift.clients.TransactionServiceClient;
26
import in.shop2020.thrift.clients.UserContextServiceClient;
27
import in.shop2020.thrift.clients.config.ConfigClient;
28
 
29
import javax.servlet.http.HttpServletRequest;
30
 
31
import org.apache.log4j.Logger;
32
import org.apache.thrift.TException;
33
 
2118 chandransh 34
@SuppressWarnings("serial")
35
public class EbsPayResponseController extends BaseController{
1905 chandransh 36
 
37
	private static Logger log = Logger.getLogger(Class.class);
38
 
39
	private static final String FLAG_KEY = "IsFlagged";
40
	private static final String TXN_KEY = "TransactionID";
41
	private static final String AUTH_TXN_ID = "AuthTxnId";
42
	private static final String CAPTURE_TXN_ID = "CaptureTxnId";
43
	private static final String CAPTURE_TIME = "CaptureTime";
44
 
2264 chandransh 45
 
1905 chandransh 46
	private static String successUrl;
47
	private static String errorUrl;
48
 
49
	/**
50
	 * The secret key used to decode RC4 encoded data.
51
	 */
52
	private static String accountKey;
53
 
54
	private String redirectUrl;
55
	private String id;
56
 
57
	static{
58
		try {
59
			successUrl = ConfigClient.getClient().get("ebs_success_url");
60
			errorUrl = ConfigClient.getClient().get("ebs_error_url");
61
			accountKey = ConfigClient.getClient().get("ebs_secret_key");
62
		} catch (ConfigException e) {
63
			log.error("Unable to get success and error usr info from config server.");
64
		}
65
	}
66
 
67
	private Map<String, String> paymentParams = new TreeMap<String, String>();
68
 
69
	public String index() {
70
		StringBuffer data1 = new StringBuffer(request.getParameter("DR"));
71
		log.info("Received data string: " + data1.toString());
72
		byte[] result = decodeRecvdData(data1);
73
 
74
		String recvString = parseRecvdData(result);
75
		updatePaymentParams(recvString);
76
 
77
		PaymentServiceClient paymentServiceClient = null;
78
		TransactionServiceClient transactionServiceClient = null;
79
		UserContextServiceClient userServiceClient = null;
80
		try {
81
			paymentServiceClient = new PaymentServiceClient();
82
			transactionServiceClient = new TransactionServiceClient();
83
			userServiceClient = new UserContextServiceClient();
84
		} catch (Exception e) {
85
			log.error("Unable to initialize one of the clients");
86
			e.printStackTrace();
87
		}
88
 
89
 
90
		long merchantPaymentId = Long.parseLong(paymentParams.get("MerchantRefNo"));
91
		String gatewayPaymentId = paymentParams.get("PaymentID");
92
		double amount = Double.parseDouble(paymentParams.get("Amount"));
93
		String isFlagged = paymentParams.get(FLAG_KEY);
94
		String gatewayTxnStatus = paymentParams.get("ResponseCode");
95
		String description = paymentParams.get("ResponseMessage");
96
		String authTxnId = paymentParams.get(TXN_KEY);
97
 
98
 
99
		List<Attribute> attributes = new ArrayList<Attribute>();
100
		attributes.add(new Attribute(FLAG_KEY, isFlagged));
101
		attributes.add(new Attribute(AUTH_TXN_ID, authTxnId));
102
 
103
		Payment payment = null;
104
		Long txnId = null;
105
		try {
106
			payment = paymentServiceClient.getClient().getPayment(merchantPaymentId);
107
			txnId = payment.getMerchantTxnId();
108
		} catch (PaymentException e1) {
109
			log.error("Payment exception. It is serious, check merchant payment id + " + merchantPaymentId);
110
			e1.printStackTrace();
111
		} catch (TException e1) {
112
			log.error("Thrift exception. Check payment id "+ merchantPaymentId);
113
			e1.printStackTrace();
114
		}
115
 
2118 chandransh 116
		if(payment.getStatus() != PaymentStatus.INIT){
117
			// We have already processed a response for this payment. Processing
118
			// it again may fail his orders. So, let's ask him to check his
119
			// account.
120
			return "maybe";
121
		}
122
 
1905 chandransh 123
		if(!validatePaymentParams(amount, payment)){
2118 chandransh 124
			this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
1905 chandransh 125
			return "index";
126
		}
127
 
128
		if(gatewayTxnStatus.equals("0")){
129
			//Update payment status as authorized
130
			try {
131
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
132
						"", gatewayTxnStatus, description, "", "", "", "", PaymentStatus.AUTHORIZED, "", attributes);
133
			} catch (PaymentException e) {
134
				e.printStackTrace();
135
			} catch (TException e) {
136
				e.printStackTrace();
137
			}
138
 
139
			Map<String, String> captureResult = EbsPaymentService.capturePayment(amount, gatewayPaymentId);
140
			String captureStatus = captureResult.get(EbsPaymentService.STATUS);
141
 
142
			if("".equals(captureStatus)){
143
				//Failure
144
				description = captureResult.get(EbsPaymentService.ERROR);
145
				String errorCode = captureResult.get(EbsPaymentService.ERR_CODE);
146
				try {
147
					paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
148
							"", gatewayTxnStatus, description, "", "", "", errorCode, PaymentStatus.FAILED, "", attributes);
149
				} catch (PaymentException e) {
150
					log.error("Error while updating failed capture payment attempt: ", e);
151
				} catch (TException e) {
152
					log.error("Error while updating failed capture payment attempt: ", e);
153
				}
2263 vikas 154
				DataLogger.logData(EventType.PAYMENT_FAILURE.name(), session.getId(), Long.toString(userinfo.getUserId()), userinfo.getEmail(), Long.toString(merchantPaymentId), gatewayPaymentId,
2157 vikas 155
                        gatewayTxnStatus, description, errorCode);
1905 chandransh 156
				this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
157
			}else{
158
				//Success
159
				try {
160
					attributes.add(new Attribute(CAPTURE_TXN_ID, captureResult.get(EbsPaymentService.TXN_ID)));
161
					attributes.add(new Attribute(CAPTURE_TIME, captureResult.get(EbsPaymentService.DATE_TIME)));
162
 
163
					paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
164
							"", captureStatus, description, "", "", "", "", PaymentStatus.SUCCESS, "", attributes);
165
				} catch (PaymentException e) {
166
					log.error("Error while updating successful capture payment attempt: ", e);
167
				} catch (TException e) {
168
					log.error("Error while updating successful capture payment attempt: ", e);
169
				}
170
 
171
				CommonPaymentService.processSuccessfulTxn(txnId, userServiceClient, transactionServiceClient);
172
 
2263 vikas 173
				DataLogger.logData(EventType.PAYMENT_SUCCESS.name(), session.getId(), Long.toString(userinfo.getUserId()), userinfo.getEmail(), Long.toString(merchantPaymentId), gatewayPaymentId,
2157 vikas 174
                        gatewayTxnStatus, description, captureStatus);
1905 chandransh 175
				this.redirectUrl = successUrl + "?paymentId=" + merchantPaymentId;				
176
			}
177
		}else{
178
			try {
179
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
180
						"", gatewayTxnStatus, description, "", "", "", "", PaymentStatus.FAILED, "", attributes);
181
			} catch (PaymentException e) {
182
				e.printStackTrace();
183
			} catch (TException e) {
184
				e.printStackTrace();
185
			}
186
 
187
			CommonPaymentService.processFailedTxn(txnId, transactionServiceClient);
2263 vikas 188
			DataLogger.logData(EventType.PAYMENT_FAILURE.name(), session.getId(), Long.toString(userinfo.getUserId()), userinfo.getEmail(), Long.toString(merchantPaymentId), gatewayPaymentId,
2157 vikas 189
                    gatewayTxnStatus, description);
1905 chandransh 190
 
191
			this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
192
		}
193
 
194
		log.info("User will be redirected to: " + this.redirectUrl);
195
		return "index";
196
	}
197
 
198
	public String getId() {
199
		return id;
200
	}
201
 
2134 chandransh 202
	private boolean validatePaymentParams(double returnedAmount, Payment payment){
203
		if(!(payment != null && Math.abs(payment.getAmount() - returnedAmount) <= 0.50)){
1905 chandransh 204
			// We did not request this payment or the authorised amount is different.
205
			log.error("Checks and balance failed on returned data");
206
			return false;
207
		}
208
		return true;
209
	}
210
 
211
	private byte[] decodeRecvdData(StringBuffer data1) {
212
		for (int i = 0; i < data1.length(); i++) {
213
			if (data1.charAt(i) == ' ')
214
				data1.setCharAt(i, '+');
215
		}
216
 
217
		Base64 base64 = new Base64();
218
		byte[] data = base64.decode(data1.toString());
219
		RC4 rc4 = new RC4(accountKey);
220
		byte[] result = rc4.rc4(data);
221
		return result;
222
	}
223
 
224
	private String parseRecvdData(byte[] result) {
225
		ByteArrayInputStream byteIn = new ByteArrayInputStream(result, 0, result.length);
2118 chandransh 226
		BufferedReader reader = new BufferedReader(new InputStreamReader(byteIn));
1905 chandransh 227
		String recvString1 = "";
228
		String recvString = "";
229
		try {
2118 chandransh 230
			recvString1 = reader.readLine();
1905 chandransh 231
			int lineCount = 0;
232
			while (recvString1 != null) {
233
				lineCount++;
234
				if (lineCount > 705)
235
					break;
236
				recvString += recvString1 + "\n";
2118 chandransh 237
				recvString1 = reader.readLine();
1905 chandransh 238
			}
239
		} catch (IOException e) {
240
			e.printStackTrace();
241
		}
242
		recvString = recvString.replace("=&", "=--&");
243
		return recvString;
244
	}
245
 
246
	private void updatePaymentParams(String str){
247
		StringTokenizer st = new StringTokenizer(str, "=&");
248
		String key, value; 
249
		while(st.hasMoreTokens()) {
250
			key = st.nextToken();
251
			value = st.nextToken();
252
			log.info("Key: " + key + ", Value: " + value);
253
			paymentParams.put(key, value);
254
		}
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
	}
265
 
266
	public Map<String, String> getPaymentParams() {
267
		return paymentParams;
268
	}
269
}