Subversion Repositories SmartDukaan

Rev

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