KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > accounting > thirdparty > worldpay > WorldPayEvents


1 /*
2  * $Id: WorldPayEvents.java 6642 2006-02-01 02:29:51Z sichen $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.accounting.thirdparty.worldpay;
26
27 import java.io.IOException JavaDoc;
28 import java.util.List JavaDoc;
29
30 import javax.servlet.ServletContext JavaDoc;
31 import javax.servlet.http.HttpServletRequest JavaDoc;
32 import javax.servlet.http.HttpServletResponse JavaDoc;
33
34 import org.ofbiz.base.util.Debug;
35 import org.ofbiz.base.util.UtilFormatOut;
36 import org.ofbiz.base.util.UtilHttp;
37 import org.ofbiz.base.util.UtilMisc;
38 import org.ofbiz.base.util.UtilProperties;
39 import org.ofbiz.entity.GenericDelegator;
40 import org.ofbiz.entity.GenericEntityException;
41 import org.ofbiz.entity.GenericValue;
42 import org.ofbiz.entity.util.EntityUtil;
43 import org.ofbiz.product.catalog.CatalogWorker;
44 import org.ofbiz.product.store.ProductStoreWorker;
45 import org.ofbiz.service.LocalDispatcher;
46
47 import com.worldpay.core.ArgumentException;
48 import com.worldpay.protocols.http.HTTPURL;
49 import com.worldpay.protocols.http.URLParameters;
50 import com.worldpay.select.PurchaseToken;
51 import com.worldpay.select.Select;
52 import com.worldpay.select.SelectCurrency;
53 import com.worldpay.select.SelectDefs;
54 import com.worldpay.select.SelectException;
55 import com.worldpay.util.Currency;
56 import com.worldpay.util.CurrencyAmount;
57
58 /**
59  * WorldPay Select Pro Events/Services
60  *
61  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
62  * @version $Rev: 6642 $
63  * @since 2.0
64  */

65 public class WorldPayEvents {
66     
67     public static final String JavaDoc module = WorldPayEvents.class.getName();
68     
69     public static String JavaDoc worldPayRequest(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
70         ServletContext JavaDoc application = ((ServletContext JavaDoc) request.getAttribute("servletContext"));
71         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
72         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
73         GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
74                                  
75         // we need the websiteId for the correct properties file
76
String JavaDoc webSiteId = CatalogWorker.getWebSiteId(request);
77         
78         // get the orderId from the request, stored by previous event(s)
79
String JavaDoc orderId = (String JavaDoc) request.getAttribute("orderId");
80         
81         if (orderId == null) {
82             Debug.logError("Problems getting orderId, was not found in request", module);
83             request.setAttribute("_ERROR_MESSAGE_", "<li>OrderID not found, please contact customer service.");
84             return "error";
85         }
86         
87         // get the order header for total and other information
88
GenericValue orderHeader = null;
89         try {
90             orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
91         } catch (GenericEntityException e) {
92             Debug.logError(e, "Cannot not get OrderHeader from datasource", module);
93             request.setAttribute("_ERROR_MESSAGE_", "<li>Problems getting order information, please contact customer service.");
94             return "error";
95         }
96         
97         // get the contact address to pass over
98
GenericValue contactAddress = null;
99         try {
100             List JavaDoc addresses = delegator.findByAnd("OrderContactMech", UtilMisc.toMap("orderId", orderId, "contactMechPurposeTypeId", "BILLING_LOCATION"));
101             if (addresses == null || addresses.size() == 0)
102                 addresses = delegator.findByAnd("OrderContactMech", UtilMisc.toMap("orderId", orderId, "contactMechPurposeTypeId", "SHIPPING_LOCATION"));
103             GenericValue contactMech = EntityUtil.getFirst(addresses);
104             contactAddress = delegator.findByPrimaryKey("PostalAddress", UtilMisc.toMap("contactMechId", contactMech.getString("contactMechId")));
105         } catch (GenericEntityException e) {
106             Debug.logWarning(e, "Problems getting order contact information", module);
107         }
108         
109         // get the country geoID
110
GenericValue countryGeo = null;
111         if (contactAddress != null) {
112             try {
113                 countryGeo = contactAddress.getRelatedOne("CountryGeo");
114             } catch (GenericEntityException e) {
115                 Debug.logWarning(e, "Problems getting country geo entity", module);
116             }
117         }
118         
119         // string of customer's name
120
String JavaDoc name = null;
121         if (contactAddress != null) {
122             if (contactAddress.get("attnName") != null && contactAddress.getString("attnName").length() > 0)
123                 name = contactAddress.getString("attnName");
124             else if (contactAddress.get("toName") != null && contactAddress.getString("toName").length() > 0)
125                 name = contactAddress.getString("toName");
126         }
127         
128         // build an address string
129
StringBuffer JavaDoc address = null;
130         if (contactAddress != null) {
131             address = new StringBuffer JavaDoc();
132             if (contactAddress.get("address1") != null) {
133                 address.append(contactAddress.getString("address1").trim());
134             }
135             if (contactAddress.get("address2") != null) {
136                 if (address.length() > 0)
137                     address.append("&#10;");
138                 address.append(contactAddress.getString("address2").trim());
139             }
140             if (contactAddress.get("city") != null) {
141                 if (address.length() > 0)
142                     address.append("&#10;");
143                 address.append(contactAddress.getString("city").trim());
144             }
145             if (contactAddress.get("stateProvinceGeoId") != null) {
146                 if (contactAddress.get("city") != null)
147                     address.append(", ");
148                 address.append(contactAddress.getString("stateProvinceGeoId").trim());
149             }
150         }
151         
152         // get the telephone number to pass over
153
String JavaDoc phoneNumber = null;
154         GenericValue phoneContact = null;
155         
156         // get the email address to pass over
157
String JavaDoc emailAddress = null;
158         GenericValue emailContact = null;
159         try {
160             List JavaDoc emails = delegator.findByAnd("OrderContactMech", UtilMisc.toMap("orderId", orderId, "contactMechPurposeTypeId", "ORDER_EMAIL"));
161             GenericValue firstEmail = EntityUtil.getFirst(emails);
162             emailContact = delegator.findByPrimaryKey("ContactMech", UtilMisc.toMap("contactMechId", firstEmail.getString("contactMechId")));
163             emailAddress = emailContact.getString("infoString");
164         } catch (GenericEntityException e) {
165             Debug.logWarning(e, "Problems getting order email address", module);
166         }
167         
168         // get the product store
169
GenericValue productStore = null;
170         try {
171             productStore = orderHeader.getRelatedOne("ProductStore");
172         } catch (GenericEntityException e) {
173             Debug.logError(e, "Unable to get ProductStore from OrderHeader", module);
174             
175         }
176         if (productStore == null) {
177             Debug.logError("ProductStore is null", module);
178             request.setAttribute("_ERROR_MESSAGE_", "<li>Problems getting merchant configuration, please contact customer service.");
179             return "error";
180         }
181         
182         // get the payment properties file
183
GenericValue paymentConfig = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStore.getString("productStoreId"), "EXT_WORLDPAY", null, true);
184         String JavaDoc configString = null;
185         if (paymentConfig != null) {
186             configString = paymentConfig.getString("paymentPropertiesPath");
187         }
188                 
189         if (configString == null) {
190             configString = "payment.properties";
191         }
192             
193         String JavaDoc instId = UtilProperties.getPropertyValue(configString, "payment.worldpay.instId", "NONE");
194         String JavaDoc authMode = UtilProperties.getPropertyValue(configString, "payment.worldpay.authMode", "A");
195         String JavaDoc testMode = UtilProperties.getPropertyValue(configString, "payment.worldpay.testMode", "100");
196         String JavaDoc fixContact = UtilProperties.getPropertyValue(configString, "payment.worldpay.fixContact", "N");
197         String JavaDoc hideContact = UtilProperties.getPropertyValue(configString, "payment.worldpay.hideContact", "N");
198         String JavaDoc confirmTemplate = UtilProperties.getPropertyValue(configString, "payment.worldpay.confirmTemplate", "");
199         String JavaDoc timeout = UtilProperties.getPropertyValue(configString, "payment.worldpay.timeout", "0");
200         String JavaDoc company = UtilFormatOut.checkEmpty(productStore.getString("companyName"), "");
201         String JavaDoc defCur = UtilFormatOut.checkEmpty(productStore.getString("defaultCurrencyUomId"), "USD");
202                            
203         // order description
204
String JavaDoc description = "Order #" + orderId;
205         if (company != null && company.length() > 0)
206         description = description + " from " + company;
207         
208         // check the instId - very important
209
if (instId == null || instId.equals("NONE")) {
210             Debug.logError("Worldpay InstId not found, cannot continue", module);
211             request.setAttribute("_ERROR_MESSAGE_", "<li>Problems getting merchant configuration, please contact customer service.");
212             return "error";
213         }
214         
215         int instIdInt = 0;
216         try {
217             instIdInt = Integer.parseInt(instId);
218         } catch (NumberFormatException JavaDoc nfe) {
219             Debug.logError(nfe, "Problem converting instId string to integer", module);
220             request.setAttribute("_ERROR_MESSAGE_", "<li>Problems getting merchant configuration, please contact customer service.");
221             return "error";
222         }
223         
224         // check the testMode
225
int testModeInt = -1;
226         if (testMode != null) {
227             try {
228                 testModeInt = Integer.parseInt(testMode);
229             } catch (NumberFormatException JavaDoc nfe) {
230                 Debug.logWarning(nfe, "Problems getting the testMode value, setting to 0", module);
231                 testModeInt = 0;
232             }
233         }
234         
235         // create the purchase link
236
String JavaDoc purchaseURL = null;
237         HTTPURL link = null;
238         URLParameters linkParms = null;
239         try {
240             purchaseURL = Select.getPurchaseURL();
241             link = new HTTPURL(purchaseURL);
242             linkParms = link.getParameters();
243         } catch (SelectException e) {
244             Debug.logError(e, "Problems creating the purchase url", module);
245             request.setAttribute("_ERROR_MESSAGE_", "<li>Problem creating link to WorldPay, please contact customer service.");
246             return "error";
247         } catch (ArgumentException e) {
248             Debug.logError(e, "Problems creating HTTPURL link", module);
249             request.setAttribute("_ERROR_MESSAGE_", "<li>Problem creating link to WorldPay, please contact customer service.");
250             return "error";
251         }
252         
253         // create the currency amount
254
double orderTotal = orderHeader.getDouble("grandTotal").doubleValue();
255         CurrencyAmount currencyAmount = null;
256         try {
257             Currency currency = SelectCurrency.getInstanceByISOCode(defCur);
258             currencyAmount = new CurrencyAmount(orderTotal, currency);
259         } catch (ArgumentException ae) {
260             Debug.logError(ae, "Problems building CurrencyAmount", module);
261             request.setAttribute("_ERROR_MESSAGE_", "<li>Merchant Configuration Error, please contact customer service.");
262             return "error";
263         }
264                 
265         // create a purchase token
266
PurchaseToken token = null;
267         try {
268             token = new PurchaseToken(instIdInt, currencyAmount, orderId);
269         } catch (SelectException e) {
270             Debug.logError(e, "Cannot create purchase token", module);
271         } catch (ArgumentException e) {
272             Debug.logError(e, "Cannot create purchase token", module);
273         }
274         if (token == null) {
275             request.setAttribute("_ERROR_MESSAGE_", "<li>Problems creating a purchase token, please contact customer service.");
276             return "error";
277         }
278         
279         // set the auth/test modes
280
try {
281             token.setAuthorisationMode(authMode);
282         } catch (SelectException e) {
283             Debug.logWarning(e, "Problems setting the authorization mode", module);
284         }
285         token.setTestMode(testModeInt);
286                         
287         // set the token to the purchase link
288
try {
289             linkParms.setValue(SelectDefs.SEL_purchase, token.produce());
290         } catch (SelectException e) {
291             Debug.logError(e, "Problems producing token", module);
292             request.setAttribute("_ERROR_MESSAGE_", "<li>Problems producing purchase token, please contact customer service.");
293             return "error";
294         }
295         
296         // set the customer data in the link
297
linkParms.setValue(SelectDefs.SEL_desc, description);
298         linkParms.setValue(SelectDefs.SEL_name, name != null ? name : "");
299         linkParms.setValue(SelectDefs.SEL_address, address != null ? address.toString() : "");
300         linkParms.setValue(SelectDefs.SEL_postcode, contactAddress != null ? contactAddress.getString("postalCode") : "");
301         linkParms.setValue(SelectDefs.SEL_country, countryGeo.getString("geoCode"));
302         linkParms.setValue(SelectDefs.SEL_tel, phoneNumber != null ? phoneNumber : "");
303         linkParms.setValue(SelectDefs.SEL_email, emailAddress != null ? emailAddress : "");
304         
305         // set some optional data
306
if (fixContact != null && fixContact.toUpperCase().startsWith("Y")) {
307             linkParms.setValue(SelectDefs.SEL_fixContact, "Y");
308         }
309         if (hideContact != null && hideContact.toUpperCase().startsWith("Y")) {
310             linkParms.setValue("hideContact", "Y"); // why is this not in SelectDefs??
311
}
312         
313         // now set some send-back parameters
314
linkParms.setValue("M_controlPath", (String JavaDoc)request.getAttribute("_CONTROL_PATH_"));
315         linkParms.setValue("M_userLoginId", userLogin.getString("userLoginId"));
316         linkParms.setValue("M_dispatchName", dispatcher.getName());
317         linkParms.setValue("M_delegatorName", delegator.getDelegatorName());
318         linkParms.setValue("M_webSiteId", webSiteId);
319         linkParms.setValue("M_localLocale", UtilHttp.getLocale(request).toString());
320         linkParms.setValue("M_confirmTemplate", confirmTemplate != null ? confirmTemplate : "");
321                     
322         // redirect to worldpay
323
try {
324             response.sendRedirect(link.produce());
325         } catch (IOException JavaDoc e) {
326             Debug.logError(e, "Problems redirecting to Worldpay", module);
327             request.setAttribute("_ERROR_MESSAGE_", "<li>Problems connecting with WorldPay, please contact customer service.");
328             return "error";
329         }
330         
331         return "success";
332     }
333
334 }
335
Popular Tags