Subversion Repositories SmartDukaan

Rev

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