Subversion Repositories SmartDukaan

Rev

Rev 1999 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1905 chandransh 1
package in.shop2020.serving.controllers;
2
 
3
import java.io.ByteArrayInputStream;
4
import java.io.DataInputStream;
5
import java.io.IOException;
6
import java.util.ArrayList;
7
import java.util.List;
8
import java.util.Map;
9
import java.util.StringTokenizer;
10
import java.util.TreeMap;
11
 
12
import in.shop2020.config.ConfigException;
13
import in.shop2020.payments.Attribute;
14
import in.shop2020.payments.Payment;
15
import in.shop2020.payments.PaymentException;
16
import in.shop2020.payments.PaymentStatus;
17
import in.shop2020.serving.services.CommonPaymentService;
18
import in.shop2020.serving.services.EbsPaymentService;
19
import in.shop2020.serving.utils.ebs.Base64;
20
import in.shop2020.serving.utils.ebs.RC4;
21
import in.shop2020.thrift.clients.PaymentServiceClient;
22
import in.shop2020.thrift.clients.TransactionServiceClient;
23
import in.shop2020.thrift.clients.UserContextServiceClient;
24
import in.shop2020.thrift.clients.config.ConfigClient;
25
 
26
import javax.servlet.http.HttpServletRequest;
27
 
28
import org.apache.log4j.Logger;
29
import org.apache.struts2.interceptor.ServletRequestAware;
30
import org.apache.thrift.TException;
31
 
32
public class EbsPayResponseController implements ServletRequestAware{
33
 
34
	private HttpServletRequest request;
35
 
36
	private static Logger log = Logger.getLogger(Class.class);
37
 
38
	private static final String FLAG_KEY = "IsFlagged";
39
	private static final String TXN_KEY = "TransactionID";
40
	private static final String AUTH_TXN_ID = "AuthTxnId";
41
	private static final String CAPTURE_TXN_ID = "CaptureTxnId";
42
	private static final String CAPTURE_TIME = "CaptureTime";
43
 
44
	private static String processingUrl;
45
	private static String successUrl;
46
	private static String errorUrl;
47
 
48
	/**
49
	 * The secret key used to decode RC4 encoded data.
50
	 */
51
	private static String accountKey;
52
 
53
	private String redirectUrl;
54
	private String id;
55
 
56
	static{
57
		try {
58
			processingUrl = ConfigClient.getClient().get("ebs_processing_url"); 
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
 
116
		if(!validatePaymentParams(amount, payment)){
117
			return "index";
118
		}
119
 
120
		if(gatewayTxnStatus.equals("0")){
121
			//Update payment status as authorized
122
			try {
123
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
124
						"", gatewayTxnStatus, description, "", "", "", "", PaymentStatus.AUTHORIZED, "", attributes);
125
			} catch (PaymentException e) {
126
				e.printStackTrace();
127
			} catch (TException e) {
128
				e.printStackTrace();
129
			}
130
 
131
			Map<String, String> captureResult = EbsPaymentService.capturePayment(amount, gatewayPaymentId);
132
			String captureStatus = captureResult.get(EbsPaymentService.STATUS);
133
 
134
			if("".equals(captureStatus)){
135
				//Failure
136
				description = captureResult.get(EbsPaymentService.ERROR);
137
				String errorCode = captureResult.get(EbsPaymentService.ERR_CODE);
138
				try {
139
					paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
140
							"", gatewayTxnStatus, description, "", "", "", errorCode, PaymentStatus.FAILED, "", attributes);
141
				} catch (PaymentException e) {
142
					log.error("Error while updating failed capture payment attempt: ", e);
143
				} catch (TException e) {
144
					log.error("Error while updating failed capture payment attempt: ", e);
145
				}
146
				this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
147
			}else{
148
				//Success
149
				try {
150
					attributes.add(new Attribute(CAPTURE_TXN_ID, captureResult.get(EbsPaymentService.TXN_ID)));
151
					attributes.add(new Attribute(CAPTURE_TIME, captureResult.get(EbsPaymentService.DATE_TIME)));
152
 
153
					paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
154
							"", captureStatus, description, "", "", "", "", PaymentStatus.SUCCESS, "", attributes);
155
				} catch (PaymentException e) {
156
					log.error("Error while updating successful capture payment attempt: ", e);
157
				} catch (TException e) {
158
					log.error("Error while updating successful capture payment attempt: ", e);
159
				}
160
 
161
				CommonPaymentService.processSuccessfulTxn(txnId, userServiceClient, transactionServiceClient);
162
 
163
				CommonPaymentService.sendTxnEmail(txnId, transactionServiceClient);
164
 
165
				this.redirectUrl = successUrl + "?paymentId=" + merchantPaymentId;				
166
			}
167
		}else{
168
			try {
169
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
170
						"", gatewayTxnStatus, description, "", "", "", "", PaymentStatus.FAILED, "", attributes);
171
			} catch (PaymentException e) {
172
				e.printStackTrace();
173
			} catch (TException e) {
174
				e.printStackTrace();
175
			}
176
 
177
			CommonPaymentService.processFailedTxn(txnId, transactionServiceClient);
178
 
179
			this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
180
		}
181
 
182
		log.info("User will be redirected to: " + this.redirectUrl);
183
		return "index";
184
	}
185
 
186
	public String show(){
187
		StringBuffer paymentData = new StringBuffer(request.getParameter("DR"));
188
		for (int i = 0; i < paymentData.length(); i++) {
189
			if (paymentData.charAt(i) == ' ')
190
				paymentData.setCharAt(i, '+');
191
		}
192
 
193
		log.info("Received data string: " + paymentData.toString());
194
		this.redirectUrl = processingUrl + paymentData.toString();
195
		return "show";
196
	}
197
 
198
	public String getId() {
199
		return id;
200
	}
201
 
202
	private boolean validatePaymentParams(double amount, Payment payment){
203
		long merchantPaymentId = payment.getPaymentId();
204
		if(payment==null || payment.getAmount()!= amount){
205
			// We did not request this payment or the authorised amount is different.
206
			log.error("Checks and balance failed on returned data");
207
			this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
208
			return false;
209
		}
210
		return true;
211
	}
212
 
213
	private byte[] decodeRecvdData(StringBuffer data1) {
214
		for (int i = 0; i < data1.length(); i++) {
215
			if (data1.charAt(i) == ' ')
216
				data1.setCharAt(i, '+');
217
		}
218
 
219
		Base64 base64 = new Base64();
220
		byte[] data = base64.decode(data1.toString());
221
		RC4 rc4 = new RC4(accountKey);
222
		byte[] result = rc4.rc4(data);
223
		return result;
224
	}
225
 
226
	private String parseRecvdData(byte[] result) {
227
		ByteArrayInputStream byteIn = new ByteArrayInputStream(result, 0, result.length);
228
		DataInputStream dataIn = new DataInputStream(byteIn);
229
		String recvString1 = "";
230
		String recvString = "";
231
		try {
232
			recvString1 = dataIn.readLine();
233
			int lineCount = 0;
234
			while (recvString1 != null) {
235
				lineCount++;
236
				if (lineCount > 705)
237
					break;
238
				recvString += recvString1 + "\n";
239
				recvString1 = dataIn.readLine();
240
			}
241
		} catch (IOException e) {
242
			e.printStackTrace();
243
		}
244
		recvString = recvString.replace("=&", "=--&");
245
		return recvString;
246
	}
247
 
248
	private void updatePaymentParams(String str){
249
		StringTokenizer st = new StringTokenizer(str, "=&");
250
		String key, value; 
251
		while(st.hasMoreTokens()) {
252
			key = st.nextToken();
253
			value = st.nextToken();
254
			log.info("Key: " + key + ", Value: " + value);
255
			paymentParams.put(key, value);
256
		}
257
	}
258
 
259
	public String getRedirectUrl(){
260
		return this.redirectUrl;
261
	}
262
 
263
	@Override
264
	public void setServletRequest(HttpServletRequest request) {
265
		this.request = request;
266
	}
267
 
268
	public Map<String, String> getPaymentParams() {
269
		return paymentParams;
270
	}
271
}