Subversion Repositories SmartDukaan

Rev

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