001: /*
002: * $Id: SelectRespServlet.java,v 1.1 2003/08/18 19:37:43 jonesde Exp $
003: *
004: * Copyright (c) 2003 The Open For Business Project - www.ofbiz.org
005: *
006: * Permission is hereby granted, free of charge, to any person obtaining a
007: * copy of this software and associated documentation files (the "Software"),
008: * to deal in the Software without restriction, including without limitation
009: * the rights to use, copy, modify, merge, publish, distribute, sublicense,
010: * and/or sell copies of the Software, and to permit persons to whom the
011: * Software is furnished to do so, subject to the following conditions:
012: *
013: * The above copyright notice and this permission notice shall be included
014: * in all copies or substantial portions of the Software.
015: *
016: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
017: * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
018: * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
019: * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
020: * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
021: * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
022: * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023: *
024: */
025: package org.ofbiz.accounting.thirdparty.worldpay;
026:
027: import java.io.IOException;
028: import java.util.Enumeration;
029: import java.util.Iterator;
030: import java.util.List;
031: import java.util.Locale;
032: import java.util.Map;
033:
034: import javax.servlet.ServletContext;
035: import javax.servlet.ServletException;
036: import javax.servlet.ServletOutputStream;
037: import javax.servlet.ServletRequest;
038: import javax.servlet.http.HttpSession;
039:
040: import org.ofbiz.base.util.Debug;
041: import org.ofbiz.base.util.GeneralException;
042: import org.ofbiz.base.util.StringUtil;
043: import org.ofbiz.base.util.UtilMisc;
044: import org.ofbiz.content.webapp.view.JPublishWrapper;
045: import org.ofbiz.entity.GenericDelegator;
046: import org.ofbiz.entity.GenericEntityException;
047: import org.ofbiz.entity.GenericValue;
048: import org.ofbiz.entity.transaction.GenericTransactionException;
049: import org.ofbiz.entity.transaction.TransactionUtil;
050: import org.ofbiz.order.order.OrderChangeHelper;
051: import org.ofbiz.service.DispatchContext;
052: import org.ofbiz.service.GenericServiceException;
053: import org.ofbiz.service.LocalDispatcher;
054: import org.ofbiz.service.ServiceDispatcher;
055:
056: import com.worldpay.select.SelectDefs;
057: import com.worldpay.select.merchant.SelectServlet;
058: import com.worldpay.select.merchant.SelectServletRequest;
059: import com.worldpay.select.merchant.SelectServletResponse;
060:
061: /**
062: * WorldPay Select Pro Response Servlet
063: *
064: * @author <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a>
065: * @version $Revision: 1.1 $
066: * @since 2.0
067: */
068: public class SelectRespServlet extends SelectServlet implements
069: SelectDefs {
070:
071: public static final String module = SelectRespServlet.class
072: .getName();
073:
074: protected void doRequest(SelectServletRequest request,
075: SelectServletResponse response) throws ServletException,
076: IOException {
077: Debug.logInfo("Response received from worldpay..", module);
078:
079: String localLocaleStr = request.getParameter("M_localLocale");
080: String webSiteId = request.getParameter("M_webSiteId");
081: String delegatorName = request.getParameter("M_delegatorName");
082: String dispatchName = request.getParameter("M_dispatchName");
083: String userLoginId = request.getParameter("M_userLoginId");
084: String confirmTemplate = request
085: .getParameter("M_confirmTemplate");
086:
087: // get the ServletContext
088: ServletContext context = (ServletContext) request
089: .getAttribute("servletContext");
090: JPublishWrapper jp = (JPublishWrapper) context
091: .getAttribute("jpublishWrapper");
092:
093: // get the delegator
094: GenericDelegator delegator = GenericDelegator
095: .getGenericDelegator(delegatorName);
096:
097: // get the dispatcher
098: ServiceDispatcher serviceDisp = ServiceDispatcher.getInstance(
099: dispatchName, delegator);
100: DispatchContext dctx = serviceDisp
101: .getLocalContext(dispatchName);
102: LocalDispatcher dispatcher = dctx.getDispatcher();
103:
104: // get the userLogin
105: GenericValue userLogin = null;
106: try {
107: userLogin = delegator.findByPrimaryKey("UserLogin",
108: UtilMisc.toMap("userLoginId", userLoginId));
109: } catch (GenericEntityException e) {
110: Debug.logError(e, "Cannot get admin UserLogin entity",
111: module);
112: callError(request);
113: }
114:
115: // get the client locale
116: List localeSplit = StringUtil.split(localLocaleStr, "_");
117: Locale localLocale = new Locale((String) localeSplit.get(0),
118: (String) localeSplit.get(1));
119:
120: // get the properties file
121: String configString = null;
122: try {
123: GenericValue webSitePayment = delegator.findByPrimaryKey(
124: "WebSitePaymentSetting", UtilMisc.toMap(
125: "webSiteId", webSiteId,
126: "paymentMethodTypeId", "EXT_WORLDPAY"));
127: if (webSitePayment != null)
128: configString = webSitePayment
129: .getString("paymentConfiguration");
130: } catch (GenericEntityException e) {
131: Debug.logWarning(e, "Cannot find webSitePayment Settings",
132: module);
133: }
134: if (configString == null)
135: configString = "payment.properties";
136: Debug.logInfo("Got the payment configuration", module);
137:
138: String orderId = request.getParameter(SelectDefs.SEL_cartId);
139: String authAmount = request
140: .getParameter(SelectDefs.SEL_authAmount);
141: String transStatus = request
142: .getParameter(SelectDefs.SEL_transStatus);
143:
144: // get the order header
145: GenericValue orderHeader = null;
146: try {
147: orderHeader = delegator.findByPrimaryKey("OrderHeader",
148: UtilMisc.toMap("orderId", orderId));
149: } catch (GenericEntityException e) {
150: Debug
151: .logError(
152: e,
153: "Cannot get the order header for the returned orderId",
154: module);
155: callError(request);
156: }
157:
158: // the order total MUST match the auth amount or we do not process
159: Double wpTotal = new Double(authAmount);
160: Double orderTotal = orderHeader != null ? orderHeader
161: .getDouble("grandTotal") : null;
162: if (orderTotal != null && wpTotal != null) {
163: if (orderTotal.doubleValue() != wpTotal.doubleValue()) {
164: Debug.logError("AuthAmount (" + wpTotal
165: + ") does not match OrderTotal (" + orderTotal
166: + ")", module);
167: callError(request);
168: }
169: }
170:
171: // store some stuff for calling existing events
172: HttpSession session = request.getSession(true);
173: session.setAttribute("userLogin", userLogin);
174:
175: request.setAttribute("delegator", delegator);
176: request.setAttribute("dispatcher", dispatcher);
177: request.setAttribute("order_id", orderId);
178: request.setAttribute("notifyEmail", request
179: .getParameter("M_notifyEmail"));
180: request.setAttribute("confirmEmail", request
181: .getParameter("M_confirmEmail"));
182: request.setAttribute("_CONTROL_PATH_", request
183: .getParameter("M_controlPath"));
184:
185: // attempt to start a transaction
186: boolean beganTransaction = false;
187: try {
188: beganTransaction = TransactionUtil.begin();
189: } catch (GenericTransactionException gte) {
190: Debug.logError(gte, "Unable to begin transaction", module);
191: }
192:
193: boolean okay = false;
194: if (transStatus.equalsIgnoreCase("Y")) {
195: // order was approved
196: Debug.logInfo("Order #" + orderId + " approved", module);
197: okay = OrderChangeHelper.approveOrder(dispatcher,
198: userLogin, orderId);
199: } else {
200: // order was cancelled
201: Debug.logInfo("Order #" + orderId + " cancelled", module);
202: okay = OrderChangeHelper.cancelOrder(dispatcher, userLogin,
203: orderId);
204: }
205:
206: if (okay) {
207: // set the payment preference
208: okay = setPaymentPreferences(delegator, orderId, request);
209: }
210:
211: if (okay) {
212: try {
213: TransactionUtil.commit(beganTransaction);
214: } catch (GenericTransactionException gte) {
215: Debug.logError(gte, "Unable to commit transaction",
216: module);
217: }
218: } else {
219: try {
220: TransactionUtil.rollback(beganTransaction);
221: } catch (GenericTransactionException gte) {
222: Debug.logError(gte, "Unable to rollback transaction",
223: module);
224: }
225: }
226:
227: // attempt to release the offline hold on the order (workflow)
228: OrderChangeHelper.releaseInitialOrderHold(dispatcher, orderId);
229:
230: // call the email confirm service
231: Map emailContext = UtilMisc.toMap("orderId", orderId);
232: try {
233: Map emailResult = dispatcher.runSync(
234: "sendOrderConfirmation", emailContext);
235: } catch (GenericServiceException e) {
236: Debug.logError(e, "Problems sending email confirmation",
237: module);
238: }
239:
240: // set up the output stream for the response
241: response.setContentType("text/html");
242: ServletOutputStream out = response.getOutputStream();
243: String content = "Error getting confirm content";
244: if (confirmTemplate != null) {
245: // render the thank-you / confirm page
246: try {
247: content = jp.render(confirmTemplate, request, response);
248: } catch (GeneralException e) {
249: Debug.logError(e, "Trouble rendering confirm page",
250: module);
251: }
252: }
253: out.println(content);
254: out.flush();
255: }
256:
257: private boolean setPaymentPreferences(GenericDelegator delegator,
258: String orderId, ServletRequest request) {
259: List paymentPrefs = null;
260: boolean okay = true;
261: try {
262: Map paymentFields = UtilMisc.toMap("orderId", orderId,
263: "statusId", "PAYMENT_NOT_RECEIVED");
264: paymentPrefs = delegator.findByAnd(
265: "OrderPaymentPreference", paymentFields);
266: } catch (GenericEntityException e) {
267: Debug.logError(e,
268: "Cannot get payment preferences for order #"
269: + orderId, module);
270: }
271: if (paymentPrefs != null && paymentPrefs.size() > 0) {
272: Iterator i = paymentPrefs.iterator();
273: while (okay && i.hasNext()) {
274: GenericValue pref = (GenericValue) i.next();
275: okay = setPaymentPreference(pref, request);
276: }
277: }
278: return okay;
279: }
280:
281: private boolean setPaymentPreference(
282: GenericValue paymentPreference, ServletRequest request) {
283: String transId = request.getParameter(SelectDefs.SEL_transId);
284: String transTime = request
285: .getParameter(SelectDefs.SEL_transTime);
286: String transStatus = request
287: .getParameter(SelectDefs.SEL_transStatus);
288: String avsCode = request.getParameter("AVS"); // why is this not in SelectDefs??
289: String authCode = request.getParameter(SelectDefs.SEL_authCode);
290: String authAmount = request
291: .getParameter(SelectDefs.SEL_authAmount);
292: String rawAuthMessage = request
293: .getParameter(SelectDefs.SEL_rawAuthMessage);
294:
295: if (transStatus.equalsIgnoreCase("Y")) {
296: paymentPreference.set("authCode", authCode);
297: paymentPreference.set("statusId", "PAYMENT_RECEIVED");
298: } else {
299: paymentPreference.set("statusId", "PAYMENT_CANCELLED");
300: }
301: Long transTimeLong = new Long(transTime);
302: java.sql.Timestamp authDate = new java.sql.Timestamp(
303: transTimeLong.longValue());
304:
305: paymentPreference.set("avsCode", avsCode);
306: paymentPreference.set("authRefNum", transId);
307: paymentPreference.set("authDate", authDate);
308: paymentPreference.set("authFlag", transStatus);
309: paymentPreference.set("authMessage", rawAuthMessage);
310: paymentPreference.set("maxAmount", new Double(authAmount));
311:
312: // create a payment record too -- this method does not store the object so we must here
313: GenericValue payment = OrderChangeHelper
314: .createPaymentFromPreference(paymentPreference, null,
315: null, "Payment received via WorldPay");
316:
317: try {
318: paymentPreference.store();
319: paymentPreference.getDelegator().create(payment);
320: } catch (GenericEntityException e) {
321: Debug.logError(e,
322: "Cannot set payment preference/payment info",
323: module);
324: return false;
325: }
326: return true;
327: }
328:
329: private void callError(ServletRequest request)
330: throws ServletException {
331: Enumeration e = request.getParameterNames();
332: Debug.logError("###### SelectRespServlet Error:", module);
333: while (e.hasMoreElements()) {
334: String name = (String) e.nextElement();
335: String value = request.getParameter(name);
336: Debug.logError("### Parameter: " + name + " => " + value,
337: module);
338: }
339: Debug.logError("###### The order was not processed!", module);
340: throw new ServletException("Order Error");
341: }
342: }
|