Subversion Repositories SmartDukaan

Rev

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