Subversion Repositories SmartDukaan

Rev

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