Subversion Repositories SmartDukaan

Rev

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