Subversion Repositories SmartDukaan

Rev

Rev 2334 | Rev 2899 | 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.services;
2
 
3
import in.shop2020.config.ConfigException;
2159 chandransh 4
import in.shop2020.payments.Attribute;
2708 chandransh 5
import in.shop2020.payments.Payment;
2159 chandransh 6
import in.shop2020.payments.PaymentStatus;
2708 chandransh 7
import in.shop2020.payments.PaymentService.Client;
8
import in.shop2020.serving.services.IPaymentService.Errors;
2159 chandransh 9
import in.shop2020.thrift.clients.PaymentServiceClient;
1905 chandransh 10
import in.shop2020.thrift.clients.config.ConfigClient;
11
 
1959 chandransh 12
import java.io.BufferedReader;
1905 chandransh 13
import java.io.DataOutputStream;
14
import java.io.IOException;
1959 chandransh 15
import java.io.InputStreamReader;
1905 chandransh 16
import java.io.StringReader;
17
import java.net.MalformedURLException;
18
import java.net.URL;
19
import java.net.URLConnection;
20
import java.net.URLEncoder;
2159 chandransh 21
import java.util.ArrayList;
1905 chandransh 22
import java.util.HashMap;
2159 chandransh 23
import java.util.List;
1905 chandransh 24
import java.util.Map;
25
import java.util.Map.Entry;
26
 
27
import javax.xml.xpath.XPath;
28
import javax.xml.xpath.XPathConstants;
29
import javax.xml.xpath.XPathExpressionException;
30
import javax.xml.xpath.XPathFactory;
31
 
32
import org.apache.log4j.Logger;
33
import org.w3c.dom.Element;
34
import org.w3c.dom.NodeList;
35
import org.xml.sax.InputSource;
36
 
37
public class EbsPaymentService implements IPaymentService{
38
 
39
	private static Logger log = Logger.getLogger(Class.class);
40
 
41
	public static final String TXN_ID = "transactionId";
42
	public static final String PAYMENT_ID = "paymentId";
43
	public static final String AMOUNT = "amount";
44
	public static final String DATE_TIME = "dateTime";
45
	public static final String MODE = "mode";
46
	public static final String REF_NO = "referenceNo";
47
	public static final String TXN_TYPE = "transactionType";
48
 
49
    private static String accountId;
50
    private static String secretKey;
51
 
52
	static{
53
		try {
54
			accountId = ConfigClient.getClient().get("ebs_account_id");
55
			secretKey = ConfigClient.getClient().get("ebs_secret_key");
56
		} catch (ConfigException e) {
57
			log.error("Unable to get EBS payment configuration.");
58
		}
59
	}
60
 
2118 chandransh 61
	private static int gatewayId=2;
1905 chandransh 62
	private long paymentId;
63
 
1959 chandransh 64
	@Override
2159 chandransh 65
	public long createPayment(long currentCartId, long userId, long txnId, String paymentOption){
2199 chandransh 66
		log.info("Creating payment for the txn#: " + txnId + " for the user: " + userId + " for processing through EBS");
1905 chandransh 67
		CommonPaymentService cps = new CommonPaymentService();
68
		if(!cps.createPayment(currentCartId, userId, txnId, gatewayId)){
69
			log.error("Error while creating the basic payment");
70
			return PAYMENT_NOT_CREATED;
71
		}
2159 chandransh 72
		paymentId = cps.getPaymentId();
1905 chandransh 73
 
2199 chandransh 74
		if(paymentOption != null){
75
			List<Attribute> attributes = new ArrayList<Attribute>();
76
			attributes.add(new Attribute(IPaymentService.PAYMENT_METHOD, paymentOption));
77
 
78
			try {
79
				PaymentServiceClient paymentServiceClient = new PaymentServiceClient();
80
				paymentServiceClient.getClient().updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null, PaymentStatus.INIT, null, attributes);
81
			} catch (Exception e) {
82
				log.error("Error while saving payment option attribute", e);
83
				// TODO: We've already created the payment. We could allow the
84
				// payment to go through. The customer will be a little
85
				// annoyed to have to select from a host of options again but
86
				// will be better than completely disallowing him.
87
				return PAYMENT_NOT_CREATED;
88
			}
2159 chandransh 89
		}
90
 
1905 chandransh 91
		return paymentId;
92
	}
1959 chandransh 93
 
94
	/**
95
	 * Capture the amount which was authorized for this payment Id. Makes
96
	 * requests over the network and so internet connectivity is must for it to
97
	 * succeed.
98
	 * 
99
	 * @param amount
100
	 *            The amount to be captured. Must be the same value which was
101
	 *            authorized for this payment.
2708 chandransh 102
	 * @param gatewayPaymentId
1959 chandransh 103
	 *            The payment ID generated by the gateway.
104
	 * @return A Map. The Map will definitely have status and will have error
105
	 *         information in case of error and txn information in case of
106
	 *         success. In case there is an error in processing, the returned
107
	 *         result map will be empty.
108
	 */
2708 chandransh 109
	public static Map<String, String> capturePayment(Payment payment, String gatewayPaymentId){
110
		String amount = "" + payment.getAmount();
111
		log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);
1959 chandransh 112
	    Map<String, String> resultMap = new HashMap<String, String>();
113
 
2118 chandransh 114
	    //Prepare resultMap to elicit failure behaviour in case anything goes wrong.
115
	    resultMap.put(STATUS, "");
116
 
2708 chandransh 117
		try {
118
			PaymentServiceClient paymentServiceClient = new PaymentServiceClient();
119
			Client paymentClient = paymentServiceClient.getClient();
120
			resultMap = paymentClient.captureEbsPayment(payment.getPaymentId());
121
		} catch (Exception e) {
122
			log.error("Unable to capture payment", e);
2118 chandransh 123
			resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
2708 chandransh 124
			resultMap.put(ERROR, "Unable to capture transaction.");
1905 chandransh 125
		}
2708 chandransh 126
 
127
		return resultMap;
128
 
129
//		/*
130
//		 * HDFC Insanity
131
//		 * 
132
//		 * If we don't set this property, all payments through HDFC will fail if
133
//		 * the first payment is made through EBS.
134
//		 * 
135
//		 * The JAR file provided by HDFC requires that the instances of
136
//		 * HttpsURLConnection returned by a call to URL.openConnection be an
137
//		 * instance of com.sun.net.ssl.HttpsURLConnection. Java versions before
138
//		 * 1.4 used to return an instance of this class which goes against the
139
//		 * current policy of using instances of undocumented internal classes of
140
//		 * JDK since they can change at any time. This behaviour was changed in
141
//		 * JAVA 1.4 to return instances of javax.net.ssl.HttpsURLConnection.
142
//		 * However, it appears, that to allow clients with JDK 1.4 and earlier,
143
//		 * HDFC favours the use of the deprecated class.
144
//		 */
145
//	    System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
146
//	    
147
//	    try {
148
//		    // URL of CGI-Bin script.
149
//			url = new URL("https://secure.ebs.in/api/1_0");
150
//		    // URL connection channel.
151
//		    urlConn = url.openConnection();
152
//		    //urlConn.setRequestMethod("POST");
153
//	    } catch (MalformedURLException e1) {
154
//			log.error(Errors.CONN_FAILURE.message, e1);
155
//			resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
156
//			resultMap.put(ERROR, Errors.CONN_FAILURE.message);
157
//			return resultMap;
158
//		} catch (IOException e) {
159
//			log.error("Unable to initialize connection to EBS API server", e);
160
//			resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
161
//			resultMap.put(ERROR, Errors.CONN_FAILURE.message);
162
//			return resultMap;
163
//		}
164
//
165
//	    // Let the run-time system (RTS) know that we want input.
166
//	    urlConn.setDoInput (true);
167
//	    // Let the RTS know that we want to do output.
168
//	    urlConn.setDoOutput (true);
169
//	    // No caching, we want the real thing.
170
//	    urlConn.setUseCaches (false);
171
//	    // Specify the content type.
172
//	    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
173
//	    // Send POST output.
174
//	    try {
175
//			printout = new DataOutputStream (urlConn.getOutputStream ());
176
//		    String content =
177
//			    "Action=" + URLEncoder.encode("capture", "UTF-8") +
178
//			    "&AccountID=" + URLEncoder.encode(accountId, "UTF-8") +
179
//			    "&SecretKey=" + URLEncoder.encode(secretKey, "UTF-8") +
180
//			    "&Amount=" + URLEncoder.encode(""+amount, "UTF-8") +
181
//			    "&PaymentID=" + URLEncoder.encode(paymentId, "UTF-8") +
182
//			    "&submitted=Submit";
183
//		    printout.writeBytes (content);
184
//		    printout.flush ();
185
//		    printout.close ();
186
//
187
//		    // Get response data.
188
//		    reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
189
//		    resultMap = parseCaptureOutput(reader);
190
//		    reader.close ();
191
//	    } catch (IOException e) {
192
//			log.error(Errors.CAPTURE_FAILURE.message, e);
193
//			resultMap.clear();
194
//			resultMap.put(STATUS, "");
195
//			resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
196
//			resultMap.put(ERROR, Errors.CAPTURE_FAILURE.message);
197
//		}
198
//	    return resultMap;
1905 chandransh 199
	}
200
 
1959 chandransh 201
	/**
202
	 * Parses the given input stream and returns a map containing the
203
	 * transaction details
204
	 * 
205
	 * @param reader The reader containing the response of the capture request.
206
	 * @return A Map. The Map will definitely have status and will have error
207
	 *         information in case of error and txn information in case of
208
	 *         success.
209
	 */
210
	private static Map<String, String> parseCaptureOutput(BufferedReader reader){
1905 chandransh 211
		Map<String, String> resultMap = new HashMap<String, String>();
212
		resultMap.put(STATUS, "");
213
 
214
		String str = null;
215
		try {
1959 chandransh 216
			str = reader.readLine();
1905 chandransh 217
			log.info("Capture response: " + str);
218
		} catch (IOException e) {
219
			log.error("Error reading the capture response:", e);
220
			return resultMap;
221
		}
222
 
223
		InputSource inputSource = new InputSource(new StringReader(str));
224
		XPath xpath = XPathFactory.newInstance().newXPath();
225
		String expression = "/output";
226
		NodeList nodes = null;
227
		try {
228
			nodes = (NodeList) xpath.evaluate(expression, inputSource,	XPathConstants.NODESET);
229
		} catch(XPathExpressionException xpee) {
230
			log.error("Input couldn't be parsed. See capture response for more info.");
231
			return resultMap;
232
		}
233
 
234
		Element elem = (Element) nodes.item(0);
235
		String status = elem.getAttribute(STATUS);
236
		resultMap.put(STATUS, status);
237
		if("".equals(status) || !"Processing".equals(status)){
238
			//We've received an error. Retrieve the error values
239
			resultMap.put(ERR_CODE, elem.getAttribute(ERR_CODE));
240
			resultMap.put(ERROR, elem.getAttribute(ERROR));
241
		}else{
2334 chandransh 242
			resultMap.put(CAPTURE_TXN_ID, elem.getAttribute(TXN_ID));
1905 chandransh 243
			resultMap.put(PAYMENT_ID, elem.getAttribute(PAYMENT_ID));
244
			resultMap.put(AMOUNT, elem.getAttribute(AMOUNT));
2334 chandransh 245
			resultMap.put(CAPTURE_TIME, elem.getAttribute(DATE_TIME));
1905 chandransh 246
			resultMap.put(MODE, elem.getAttribute(MODE));
247
			resultMap.put(REF_NO, elem.getAttribute(REF_NO));
248
			resultMap.put(TXN_TYPE, elem.getAttribute(TXN_TYPE));
249
		}
250
 
251
		log.info("Parsed capture response:");
252
		for(Entry<String, String> entry : resultMap.entrySet()){
253
			log.info("Key: " + entry.getKey() + ", Value: " + entry.getValue());
254
		}
255
 
256
		return resultMap;
257
	}
258
 
259
	public static void main(String[] args){
2708 chandransh 260
		//capturePayment(30450.00, "2412653");
1905 chandransh 261
 
262
//		<output  transactionId="4793507"  paymentId="2411078"  amount="25005"  dateTime="2011-05-16 09:03:15"  mode="TEST"  referenceNo="4"  transactionType="Captured"  status="Processing"  />";
263
 
264
//		<output  errorCode="2"  error="Invalid Account ID/Secret Key"  />
265
//		<output  errorCode="12"  error="This payment is failed"  />
266
//		<output  errorCode="13"  error="This payment is captured already"  />		
267
	}
268
}