Subversion Repositories SmartDukaan

Rev

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