Subversion Repositories SmartDukaan

Rev

Rev 12788 | Rev 13380 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
6060 rajveer 1
package in.shop2020.serving.controllers;
2
 
3
import in.shop2020.config.ConfigException;
13372 amit.gupta 4
import in.shop2020.model.v1.order.RechargeOrder;
5
import in.shop2020.model.v1.order.RechargeOrderStatus;
6060 rajveer 6
import in.shop2020.payments.Attribute;
7
import in.shop2020.payments.Payment;
8
import in.shop2020.payments.PaymentException;
9
import in.shop2020.payments.PaymentStatus;
10
import in.shop2020.serving.services.CommonPaymentService;
11
import in.shop2020.thrift.clients.PaymentClient;
12
import in.shop2020.thrift.clients.TransactionClient;
13
import in.shop2020.thrift.clients.config.ConfigClient;
14
 
15
import java.security.MessageDigest;
16
import java.security.NoSuchAlgorithmException;
13372 amit.gupta 17
import java.text.SimpleDateFormat;
6060 rajveer 18
import java.util.ArrayList;
13372 amit.gupta 19
import java.util.Date;
6060 rajveer 20
import java.util.List;
21
import java.util.Map;
22
import java.util.TreeMap;
23
 
24
import javax.servlet.http.HttpServletRequest;
25
 
26
import org.apache.log4j.Logger;
27
import org.apache.thrift.TException;
28
 
29
@SuppressWarnings("serial")
30
public class PayuPayResponseController extends BaseController{
31
 
32
	private static Logger log = Logger.getLogger(Class.class);
33
 
34
	private static final String UNMAPPED_STATUS = "UnMappedStatus";
35
 
36
	private static String successUrl;
37
	private static String errorUrl;
13372 amit.gupta 38
	private static String rechargeResultUri;
6060 rajveer 39
 
40
	/**
41
	 * The secret key used to decode RC4 encoded data.
42
	 */
6062 rajveer 43
	private static String accountKey;
6060 rajveer 44
 
6062 rajveer 45
	private static String salt;
6060 rajveer 46
 
47
	private String redirectUrl;
13372 amit.gupta 48
 
49
	private String eurl;
50
	private String surl;
6060 rajveer 51
 
52
	static{
53
		try {
13372 amit.gupta 54
			ConfigClient cc = ConfigClient.getClient();
55
			successUrl = cc.get("payu_success_url");
56
			errorUrl = cc.get("payu_error_url");
57
			accountKey = cc.get("payu_account_id");
58
			salt = cc.get("payu_secret_key");
59
			rechargeResultUri = ConfigClient.getClient().get("recharge_result_uri");
6060 rajveer 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
 
13372 amit.gupta 67
	public String index() {
68
		eurl = errorUrl;
69
		surl = successUrl;
6060 rajveer 70
		updatePaymentParams(request.getParameterMap());
71
 
72
		PaymentClient paymentServiceClient = null;
73
		TransactionClient transactionServiceClient = null;
74
		try {
75
			paymentServiceClient = new PaymentClient();
76
			transactionServiceClient = new TransactionClient();
77
		} catch (Exception e) {
78
			log.error("Unable to initialize one of the clients", e);
79
		}
80
 
81
 
82
		long merchantPaymentId = Long.parseLong(paymentParams.get("txnid"));
83
		String gatewayPaymentId = paymentParams.get("mihpayid");
84
		double amount = Double.parseDouble(paymentParams.get("amount"));
85
		String gatewayTxnStatus = paymentParams.get("status");
86
		String hash = paymentParams.get("hash");
87
		String bankRefId = paymentParams.get("bank_ref_num");
88
		String unmappedStatus  = paymentParams.get("unmappedstatus");
89
 
90
 
91
		List<Attribute> attributes = new ArrayList<Attribute>();
92
		attributes.add(new Attribute(UNMAPPED_STATUS, unmappedStatus));
93
 
94
		Payment payment = null;
95
		Long txnId = null;
96
		try {
97
			payment = paymentServiceClient.getClient().getPayment(merchantPaymentId);
98
			txnId = payment.getMerchantTxnId();
99
		} catch (PaymentException e1) {
100
			log.error("Payment exception. It is serious, check merchant payment id + " + merchantPaymentId, e1);
101
		} catch (TException e1) {
102
			log.error("Thrift exception. Check payment id "+ merchantPaymentId, e1);
103
		}
13372 amit.gupta 104
 
105
		if(payment.getStatus() != PaymentStatus.INIT){
106
			// We have already processed a response for this payment. Processing
107
			// it again may fail his orders. So, let's ask him to check his
108
			// account.
109
			return "ebs-pay-response-maybe";
110
		}
6060 rajveer 111
 
13372 amit.gupta 112
		if(payment.isIsDigital()){
113
			eurl = rechargeResultUri;
114
			surl = rechargeResultUri;
115
		}
116
 
6060 rajveer 117
		if(!validatePaymentParams(amount, payment, hash)){
13372 amit.gupta 118
			this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
6060 rajveer 119
			return "index";
120
		}
121
 
122
		if(gatewayTxnStatus.equalsIgnoreCase("SUCCESS")){
123
			try {
124
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
13372 amit.gupta 125
						"", gatewayTxnStatus, unmappedStatus.equals("captured") ? "Transaction captured at PG":"Transaction Authorized at PG", 
126
						"", "", bankRefId, "", unmappedStatus.equals("captured") ? PaymentStatus.SUCCESS : PaymentStatus.AUTHORIZED, new SimpleDateFormat().format(new Date()), attributes);
6060 rajveer 127
			} catch (PaymentException e) {
13372 amit.gupta 128
				this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
129
				return "index";
6060 rajveer 130
			} catch (TException e) {
13372 amit.gupta 131
				this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
132
				return "index";
6060 rajveer 133
			}
13372 amit.gupta 134
            if(payment.isIsDigital()){
135
            	RechargeOrder rechargeOrder = null;
136
                try {
137
                    rechargeOrder = transactionServiceClient.getClient().getRechargeOrdersForTransaction(txnId);
138
                } catch (Exception e1) {
139
                    log.error("Problem with txn client while getting recharge object", e1);
140
    				this.redirectUrl = eurl + "?paymentId=" + merchantPaymentId;
141
    				return "index";
142
                }
143
 
144
		        try {
145
		            PaymentClient pcl = new PaymentClient();
146
		            boolean isCaptured = pcl.getClient().capturePayment(txnId, true);
147
 
148
		            //Retry in case we are not able to capture first time
149
		            if(!isCaptured){
150
		            	Thread.sleep(2000);
151
		            	isCaptured = pcl.getClient().capturePayment(txnId, true);
152
		            }
153
		            if(!isCaptured){
154
		            	Thread.sleep(2000);
155
		            	isCaptured = pcl.getClient().capturePayment(txnId, true);
156
		            }
157
 
158
		            if(isCaptured) {
159
		                transactionServiceClient.getClient().updateRechargeOrderStatus(rechargeOrder.getId(), RechargeOrderStatus.PAYMENT_SUCCESSFUL);
160
		            } else {
161
                        transactionServiceClient.getClient().updateRechargeOrderStatus(rechargeOrder.getId(), RechargeOrderStatus.PAYMENT_FAILED);
162
		            }
163
		        } catch (Exception e) {
164
		            log.error("Problem with txn client while trying to recharge", e);
165
		        }
166
            }
6060 rajveer 167
 
168
		}else{
169
			try {
170
				paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, gatewayPaymentId,
13372 amit.gupta 171
						"", gatewayTxnStatus, "Payment Failed at PG", "", "", "", "", PaymentStatus.FAILED, new SimpleDateFormat().format(new Date()), attributes);
6060 rajveer 172
			} catch (PaymentException e) {
173
			    log.error("Unable to mark the payment as failed", e);
174
			} catch (TException e) {
175
			    log.error("Unable to mark the payment as failed", e);
176
			}
177
 
178
			CommonPaymentService.processFailedTxn(txnId, transactionServiceClient);
179
 
180
			this.redirectUrl = errorUrl + "?paymentId=" + merchantPaymentId;
181
		}
182
 
13372 amit.gupta 183
		log.info("User will be redirected to: " + "?paymentId=" + merchantPaymentId);
184
		this.redirectUrl = surl + "?paymentId=" + merchantPaymentId;
6060 rajveer 185
		return "index";
186
	}
187
 
188
	private boolean validatePaymentParams(double returnedAmount, Payment payment, String hash){
189
		if(!(payment != null && Math.abs(payment.getAmount() - returnedAmount) <= 0.50 && hash.equals(getSecureHash()))){
190
			// We did not request this payment or the authorised amount is different.
191
			log.error("Checks and balance failed on returned data");
192
			return false;
193
		}
194
		return true;
195
	}
196
 
197
 
198
	public String getSecureHash(){
199
		try{
6065 rajveer 200
			String pass = salt + "|" + paymentParams.get("status") + "|||||||||||" + paymentParams.get("email") + "|" +  paymentParams.get("firstname") + "|" + paymentParams.get("productinfo") + "|" + paymentParams.get("amount") + "|" + paymentParams.get("txnid") + "|" + accountKey;
6060 rajveer 201
			System.out.println(pass);
202
			MessageDigest md = MessageDigest.getInstance("SHA-512");
203
			md.update(pass.getBytes(), 0, pass.getBytes().length);
204
			byte[] mdbytes = md.digest();
205
			//	convert the byte to hex format method
206
			StringBuffer sb = new StringBuffer();
207
			for (int i = 0; i < mdbytes.length; i++) {
208
				sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
209
			}
210
			return sb.toString();
211
		}catch(NoSuchAlgorithmException nsae){
212
			log.error("No such algorithm exception");
213
			return null;
214
		}
215
	}
216
 
217
	private void updatePaymentParams(Map map){
218
		for(Object key : map.keySet()){
219
		    String keyStr = (String)key;
220
		    String[] vals = (String[])map.get(keyStr);
221
		    String value = vals[0];
222
		    System.out.println("Key " + (String)key + "     :    " + value);
223
		    paymentParams.put(keyStr, value);
224
		}
225
	}
226
 
227
	public String getRedirectUrl(){
228
		return this.redirectUrl;
229
	}
230
 
231
	@Override
232
	public void setServletRequest(HttpServletRequest request) {
233
		this.request = request;
234
	}
235
 
236
	public Map<String, String> getPaymentParams() {
237
		return paymentParams;
238
	}
239
}