Subversion Repositories SmartDukaan

Rev

Rev 6091 | 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;
6058 anupam.sin 5
import in.shop2020.model.v1.order.RechargeOrder;
6050 anupam.sin 6
import in.shop2020.model.v1.order.RechargeOrderStatus;
6091 anupam.sin 7
import in.shop2020.model.v1.order.TransactionServiceException;
1905 chandransh 8
import in.shop2020.payments.Attribute;
9
import in.shop2020.payments.Payment;
10
import in.shop2020.payments.PaymentException;
11
import in.shop2020.payments.PaymentStatus;
12
import in.shop2020.serving.services.CommonPaymentService;
13
import in.shop2020.serving.utils.ebs.Base64;
14
import in.shop2020.serving.utils.ebs.RC4;
3126 rajveer 15
import in.shop2020.thrift.clients.PaymentClient;
16
import in.shop2020.thrift.clients.TransactionClient;
17
import in.shop2020.thrift.clients.UserClient;
1905 chandransh 18
import in.shop2020.thrift.clients.config.ConfigClient;
2511 vikas 19
import in.shop2020.utils.DataLogger;
1905 chandransh 20
 
2419 vikas 21
import java.io.BufferedReader;
22
import java.io.ByteArrayInputStream;
23
import java.io.IOException;
24
import java.io.InputStreamReader;
25
import java.util.ArrayList;
26
import java.util.List;
27
import java.util.Map;
28
import java.util.StringTokenizer;
29
import java.util.TreeMap;
30
 
1905 chandransh 31
import javax.servlet.http.HttpServletRequest;
32
 
33
import org.apache.log4j.Logger;
34
import org.apache.thrift.TException;
35
 
2118 chandransh 36
@SuppressWarnings("serial")
37
public class EbsPayResponseController extends BaseController{
2673 vikas 38
 
1905 chandransh 39
	private static Logger log = Logger.getLogger(Class.class);
2673 vikas 40
 
1905 chandransh 41
	private static final String FLAG_KEY = "IsFlagged";
42
	private static final String TXN_KEY = "TransactionID";
43
	private static final String AUTH_TXN_ID = "AuthTxnId";
2673 vikas 44
 
1905 chandransh 45
	private static String successUrl;
46
	private static String errorUrl;
6050 anupam.sin 47
	private static String rechargeResultUri;
2673 vikas 48
 
1905 chandransh 49
	/**
50
	 * The secret key used to decode RC4 encoded data.
51
	 */
52
	private static String accountKey;
2673 vikas 53
 
1905 chandransh 54
	private String redirectUrl;
2673 vikas 55
 
1905 chandransh 56
	static{
57
		try {
58
			successUrl = ConfigClient.getClient().get("ebs_success_url");
59
			errorUrl = ConfigClient.getClient().get("ebs_error_url");
6050 anupam.sin 60
			setRechargeResultUri(ConfigClient.getClient().get("recharge_success_url"));
1905 chandransh 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
	}
2673 vikas 66
 
2681 vikas 67
	private Map<String, String> paymentParams = new TreeMap<String, String>();
2673 vikas 68
 
1905 chandransh 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);
2673 vikas 76
 
3126 rajveer 77
		PaymentClient paymentServiceClient = null;
78
		TransactionClient transactionServiceClient = null;
79
		UserClient userServiceClient = null;
1905 chandransh 80
		try {
3126 rajveer 81
			paymentServiceClient = new PaymentClient();
82
			transactionServiceClient = new TransactionClient();
83
			userServiceClient = new UserClient();
1905 chandransh 84
		} catch (Exception e) {
2942 chandransh 85
			log.error("Unable to initialize one of the clients", e);
1905 chandransh 86
		}
2673 vikas 87
 
88
 
1905 chandransh 89
		long merchantPaymentId = Long.parseLong(paymentParams.get("MerchantRefNo"));
90
		String gatewayPaymentId = paymentParams.get("PaymentID");
91
		double amount = Double.parseDouble(paymentParams.get("Amount"));
92
		String isFlagged = paymentParams.get(FLAG_KEY);
93
		String gatewayTxnStatus = paymentParams.get("ResponseCode");
94
		String description = paymentParams.get("ResponseMessage");
95
		String authTxnId = paymentParams.get(TXN_KEY);
2673 vikas 96
 
97
 
1905 chandransh 98
		List<Attribute> attributes = new ArrayList<Attribute>();
99
		attributes.add(new Attribute(FLAG_KEY, isFlagged));
100
		attributes.add(new Attribute(AUTH_TXN_ID, authTxnId));
2673 vikas 101
 
1905 chandransh 102
		Payment payment = null;
103
		Long txnId = null;
104
		try {
105
			payment = paymentServiceClient.getClient().getPayment(merchantPaymentId);
106
			txnId = payment.getMerchantTxnId();
107
		} catch (PaymentException e1) {
2334 chandransh 108
			log.error("Payment exception. It is serious, check merchant payment id + " + merchantPaymentId, e1);
1905 chandransh 109
		} catch (TException e1) {
2334 chandransh 110
			log.error("Thrift exception. Check payment id "+ merchantPaymentId, e1);
1905 chandransh 111
		}
2673 vikas 112
 
2118 chandransh 113
		if(payment.getStatus() != PaymentStatus.INIT){
114
			// We have already processed a response for this payment. Processing
115
			// it again may fail his orders. So, let's ask him to check his
116
			// account.
117
			return "maybe";
118
		}
2673 vikas 119
 
1905 chandransh 120
		if(!validatePaymentParams(amount, payment)){
2118 chandransh 121
			this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
1905 chandransh 122
			return "index";
123
		}
2673 vikas 124
 
1905 chandransh 125
		if(gatewayTxnStatus.equals("0")){
4246 rajveer 126
			//Update payment status as authorized if payment is authorized.
1905 chandransh 127
			try {
128
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
129
						"", gatewayTxnStatus, description, "", "", "", "", PaymentStatus.AUTHORIZED, "", attributes);
130
			} catch (PaymentException e) {
2942 chandransh 131
				log.error("Unable to mark the payment as authorized", e);
1905 chandransh 132
			} catch (TException e) {
2942 chandransh 133
			    log.error("Unable to mark the payment as authorized", e);
1905 chandransh 134
			}
6050 anupam.sin 135
 
136
			if(payment.isIsDigital()) {
6091 anupam.sin 137
			    RechargeOrder rechargeOrder = null;
138
                try {
139
                    rechargeOrder = transactionServiceClient.getClient().getRechargeOrdersForTransaction(txnId);
140
                } catch (Exception e1) {
141
                    log.error("Problem with txn client while getting recharge object", e1);
6050 anupam.sin 142
                }
6091 anupam.sin 143
			    if(!isFlagged.equals("YES")) {
144
			        //Recharge only when payment is digital and is captured and is not flagged 
145
			        try {
146
			            PaymentClient pcl = new PaymentClient();
8618 rajveer 147
			            boolean isCaptured = pcl.getClient().capturePayment(txnId, true);
6091 anupam.sin 148
 
8618 rajveer 149
			            //Retry in case we are not able to capture first time
150
			            if(!isCaptured){
151
			            	Thread.sleep(2000);
152
			            	isCaptured = pcl.getClient().capturePayment(txnId, true);
153
			            }
154
			            if(!isCaptured){
155
			            	Thread.sleep(2000);
156
			            	isCaptured = pcl.getClient().capturePayment(txnId, true);
157
			            }
158
 
6091 anupam.sin 159
			            if(isCaptured) {
160
			                transactionServiceClient.getClient().updateRechargeOrderStatus(rechargeOrder.getId(), RechargeOrderStatus.PAYMENT_SUCCESSFUL);
161
			            } else {
162
	                        transactionServiceClient.getClient().updateRechargeOrderStatus(rechargeOrder.getId(), RechargeOrderStatus.PAYMENT_FAILED);
163
			            }
164
			        } catch (Exception e) {
165
			            log.error("Problem with txn client while trying to recharge", e);
166
			        }
167
			    } else {
168
			        try {
169
			            transactionServiceClient.getClient().updateRechargeOrderStatus(rechargeOrder.getId(), RechargeOrderStatus.PAYMENT_FAILED);
170
                    } catch (Exception e) {
171
                        log.error("Problem with txn client while trying to mark payment failed in recharge order", e);
172
                    }
173
			    }
174
			    this.redirectUrl = rechargeResultUri + "?paymentId=" + merchantPaymentId;
6050 anupam.sin 175
			} else {
6091 anupam.sin 176
			    //For physical orders
6050 anupam.sin 177
			    if(isFlagged.equals("YES")){
178
			        CommonPaymentService.processSuccessfulTxn(txnId, userServiceClient, transactionServiceClient, true);
179
			        this.redirectUrl = successUrl + "?paymentId=" + merchantPaymentId;
180
			    }else{
181
			        CommonPaymentService.processSuccessfulTxn(txnId, userServiceClient, transactionServiceClient, false);
182
			        this.redirectUrl = successUrl + "?paymentId=" + merchantPaymentId;	
183
			    }
4246 rajveer 184
			}
3010 chandransh 185
 
4246 rajveer 186
 
3010 chandransh 187
//			Map<String, String> captureResult = EbsPaymentService.capturePayment(payment, gatewayPaymentId);
188
//			String captureStatus = captureResult.get(IPaymentService.STATUS);
189
//
190
//			if("".equals(captureStatus)){
191
//				//Failure
192
//				description = captureResult.get(EbsPaymentService.ERROR);
193
//				String errorCode = captureResult.get(EbsPaymentService.ERR_CODE);
194
//				try {
195
//					paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
196
//							"", gatewayTxnStatus, description, "", "", "", errorCode, PaymentStatus.FAILED, "", attributes);
197
//				} catch (PaymentException e) {
198
//					log.error("Error while updating failed capture payment attempt: ", e);
199
//				} catch (TException e) {
200
//					log.error("Error while updating failed capture payment attempt: ", e);
201
//				}
3224 vikas 202
//				DataLogger.logData(EventType.PAYMENT_FAILURE, getSessionId(), userinfo.getUserId(), userinfo.getEmail(), Long.toString(merchantPaymentId), gatewayPaymentId,
3010 chandransh 203
//                        gatewayTxnStatus, description, errorCode);
204
//				this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
205
//			}else{
206
//				//Success
207
//				try {
208
//					attributes.add(new Attribute(IPaymentService.CAPTURE_TXN_ID, captureResult.get(IPaymentService.CAPTURE_TXN_ID)));
209
//					attributes.add(new Attribute(IPaymentService.CAPTURE_TIME, captureResult.get(IPaymentService.CAPTURE_TIME)));
210
//
211
//					paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
212
//							"", captureStatus, description, "", "", "", "", PaymentStatus.SUCCESS, "", attributes);
213
//				} catch (PaymentException e) {
214
//					log.error("Error while updating successful capture payment attempt: ", e);
215
//				} catch (TException e) {
216
//					log.error("Error while updating successful capture payment attempt: ", e);
217
//				}
218
//
219
//				CommonPaymentService.processSuccessfulTxn(txnId, userServiceClient, transactionServiceClient);
220
//
221
//				this.redirectUrl = successUrl + "?paymentId=" + merchantPaymentId;
222
//			}
1905 chandransh 223
		}else{
224
			try {
225
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
226
						"", gatewayTxnStatus, description, "", "", "", "", PaymentStatus.FAILED, "", attributes);
227
			} catch (PaymentException e) {
2942 chandransh 228
			    log.error("Unable to mark the payment as failed", e);
1905 chandransh 229
			} catch (TException e) {
2942 chandransh 230
			    log.error("Unable to mark the payment as failed", e);
1905 chandransh 231
			}
6050 anupam.sin 232
			if(!payment.isIsDigital()) {
1905 chandransh 233
			CommonPaymentService.processFailedTxn(txnId, transactionServiceClient);
3185 vikas 234
			DataLogger.logData(EventType.PAYMENT_FAILURE, getSessionId(), userinfo.getUserId(), userinfo.getEmail(), Long.toString(merchantPaymentId), gatewayPaymentId,
2157 vikas 235
                    gatewayTxnStatus, description);
1905 chandransh 236
 
237
			this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
6050 anupam.sin 238
			} else {
239
			    this.redirectUrl = rechargeResultUri + "?paymentId=" + merchantPaymentId;
240
			}
1905 chandransh 241
		}
2673 vikas 242
 
1905 chandransh 243
		log.info("User will be redirected to: " + this.redirectUrl);
244
		return "index";
245
	}
2673 vikas 246
 
2134 chandransh 247
	private boolean validatePaymentParams(double returnedAmount, Payment payment){
248
		if(!(payment != null && Math.abs(payment.getAmount() - returnedAmount) <= 0.50)){
1905 chandransh 249
			// We did not request this payment or the authorised amount is different.
250
			log.error("Checks and balance failed on returned data");
251
			return false;
252
		}
253
		return true;
254
	}
255
 
256
	private byte[] decodeRecvdData(StringBuffer data1) {
257
		for (int i = 0; i < data1.length(); i++) {
258
			if (data1.charAt(i) == ' ')
259
				data1.setCharAt(i, '+');
260
		}
2673 vikas 261
 
1905 chandransh 262
		Base64 base64 = new Base64();
263
		byte[] data = base64.decode(data1.toString());
264
		RC4 rc4 = new RC4(accountKey);
265
		byte[] result = rc4.rc4(data);
266
		return result;
267
	}
268
 
269
	private String parseRecvdData(byte[] result) {
270
		ByteArrayInputStream byteIn = new ByteArrayInputStream(result, 0, result.length);
2118 chandransh 271
		BufferedReader reader = new BufferedReader(new InputStreamReader(byteIn));
1905 chandransh 272
		String recvString1 = "";
273
		String recvString = "";
274
		try {
2118 chandransh 275
			recvString1 = reader.readLine();
1905 chandransh 276
			int lineCount = 0;
277
			while (recvString1 != null) {
278
				lineCount++;
279
				if (lineCount > 705)
280
					break;
281
				recvString += recvString1 + "\n";
2118 chandransh 282
				recvString1 = reader.readLine();
1905 chandransh 283
			}
284
		} catch (IOException e) {
2942 chandransh 285
			log.error("Unable to read from Ebs response", e);
1905 chandransh 286
		}
287
		recvString = recvString.replace("=&", "=--&");
288
		return recvString;
289
	}
290
 
291
	private void updatePaymentParams(String str){
292
		StringTokenizer st = new StringTokenizer(str, "=&");
2673 vikas 293
		String key, value;
1905 chandransh 294
		while(st.hasMoreTokens()) {
295
			key = st.nextToken();
296
			value = st.nextToken();
297
			log.info("Key: " + key + ", Value: " + value);
298
			paymentParams.put(key, value);
299
		}
300
	}
2673 vikas 301
 
1905 chandransh 302
	public String getRedirectUrl(){
303
		return this.redirectUrl;
304
	}
2673 vikas 305
 
1905 chandransh 306
	@Override
307
	public void setServletRequest(HttpServletRequest request) {
308
		this.request = request;
309
	}
310
 
311
	public Map<String, String> getPaymentParams() {
312
		return paymentParams;
313
	}
6050 anupam.sin 314
 
315
    public static void setRechargeResultUri(String rechargeResultUri) {
316
        EbsPayResponseController.rechargeResultUri = rechargeResultUri;
317
    }
318
 
319
    public static String getRechargeResultUri() {
320
        return rechargeResultUri;
321
    }
1905 chandransh 322
}