Subversion Repositories SmartDukaan

Rev

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