Subversion Repositories SmartDukaan

Rev

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