KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > wstore > PaymentServlet


1 /******************************************************************************
2  * The contents of this file are subject to the Compiere License Version 1.1
3  * ("License"); You may not use this file except in compliance with the License
4  * You may obtain a copy of the License at http://www.compiere.org/license.html
5  * Software distributed under the License is distributed on an "AS IS" basis,
6  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
7  * the specific language governing rights and limitations under the License.
8  * The Original Code is Compiere ERP & CRM Business Solution
9  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
10  * Portions created by Jorg Janke are Copyright (C) 1999-2002 Jorg Janke, parts
11  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
12  * Contributor(s): ______________________________________.
13  *****************************************************************************/

14 package org.compiere.wstore;
15
16 import javax.servlet.*;
17 import javax.servlet.http.*;
18 import java.io.*;
19 import java.util.*;
20 import java.math.*;
21
22 import org.apache.log4j.Logger;
23
24 import org.compiere.www.*;
25 import org.compiere.model.*;
26 import org.compiere.util.*;
27
28 /**
29  * Web Store Payment Entry & Confirmation
30  *
31  * @author Jorg Janke
32  * @version $Id: PaymentServlet.java,v 1.13 2003/09/05 04:55:42 jjanke Exp $
33  */

34 public class PaymentServlet extends HttpServlet
35 {
36     /** Logging */
37     private Logger log = Logger.getLogger(getClass());
38
39     public static final String JavaDoc ATTR_PAYMENT = "payment";
40
41     /**
42      * Initialize global variables
43      * @param config servlet configuration
44      * @throws ServletException
45      */

46     public void init(ServletConfig config) throws ServletException
47     {
48         super.init(config);
49         if (!WEnv.initWeb(config))
50             throw new ServletException("PaymentServlet.init");
51     } // init
52

53     /**
54      * Get Servlet information
55      * @return Info
56      */

57     public String JavaDoc getServletInfo()
58     {
59         return "Compiere Payment Servlet";
60     } // getServletInfo
61

62     /**
63      * Clean up resources
64      */

65     public void destroy()
66     {
67         log.info("destroy");
68     } // destroy
69

70     /*************************************************************************/
71
72     /**
73      * Process the initial HTTP Get request.
74      * Reads the Parameter Amt and optional C_Invoice_ID
75      *
76      * @param request request
77      * @param response response
78      * @throws ServletException
79      * @throws IOException
80      */

81     public void doGet(HttpServletRequest request, HttpServletResponse response)
82         throws ServletException, IOException
83     {
84         log.info("doGet from " + request.getRemoteHost() + " - " + request.getRemoteAddr());
85         Properties ctx = JSPEnv.getCtx(request);
86         HttpSession session = request.getSession(true);
87         session.removeAttribute(JSPEnv.HDR_MESSAGE);
88     // WEnv.dump(session);
89
// WEnv.dump(request);
90

91         // Non existing user or Existing Web Payment
92
WebUser wu = (WebUser)session.getAttribute(WebUser.NAME);
93         MPayment p = (MPayment)session.getAttribute (ATTR_PAYMENT);
94         if (wu == null)
95         {
96             log.info ("doGet - No User");
97             String JavaDoc url = "index.jsp";
98             log.info ("doPost - Forward to " + url);
99             RequestDispatcher dispatcher = getServletContext ().getRequestDispatcher (url);
100             dispatcher.forward (request, response);
101         }
102
103         // Remove any open Order
104
session.removeAttribute(WebOrder.NAME);
105         // Payment Amount
106
String JavaDoc amtParam = request.getParameter("Amt");
107         if (amtParam == null || amtParam.length() == 0)
108         {
109             log.info ("doGet - No Payment Amount (" + amtParam + ")");
110             doPost (request, response);
111             return;
112         }
113         char[] chars = amtParam.toCharArray();
114         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
115         boolean decimal = false;
116         for (int i = chars.length-1; i >=0; i--)
117         {
118             char c = chars[i];
119             if (c == ',' || c == '.')
120             {
121                 if (!decimal)
122                 {
123                     sb.insert (0, '.');
124                     decimal = true;
125                 }
126             }
127             else if (Character.isDigit(c))
128                 sb.insert(0,c);
129         }
130         BigDecimal amt = null;
131         try
132         {
133                 if (sb.length() > 0)
134                 {
135                     amt = new BigDecimal (sb.toString ());
136                     amt = amt.abs (); // make it positive
137
}
138         }
139         catch (Exception JavaDoc ex)
140         {
141             log.warn("doGet - Parsing Amount=" + amtParam + " (" + sb + ") - " + ex.toString());
142         }
143         // Need to be positive amount
144
if (amt == null || amt.compareTo(Env.ZERO) < 0)
145         {
146             log.info("doGet - No valid Payment Amount (" + amtParam + ") - " + amt);
147             doPost (request, response);
148             return;
149         }
150
151         String JavaDoc invoiceParam = request.getParameter("C_Invoice_ID");
152         int C_Invoice_ID = 0;
153         try
154         {
155             if (invoiceParam != null)
156                 C_Invoice_ID = Integer.parseInt (invoiceParam);
157         }
158         catch (NumberFormatException JavaDoc ex)
159         {
160             log.warn("doGet - Parsing C_Invoice_ID=" + invoiceParam + " - " + ex.toString());
161         }
162         log.info("doGet - Amt=" + amt + ", C_Invoice_ID=" + C_Invoice_ID);
163
164         // Create New Payment for Amt & optional Invoice
165
// see OrderServlet.createPayment
166
p = new MPayment(ctx, 0);
167         p.setIsSelfService(true);
168         p.setAmount(0, amt); // for CC selection ges default from Acct Currency
169
p.setIsOnline(true);
170
171         // Sales CC Trx
172
p.setC_DocType_ID(true);
173         p.setTrxType(MPayment.TRXTYPE_Sales);
174         p.setTenderType(MPayment.TENDERTYPE_CreditCard);
175         // Payment Info
176
p.setC_Invoice_ID(C_Invoice_ID);
177         // BP Info
178
p.setBP_BankAccount(wu.getBankAccount());
179         //
180
// p.save();
181
session.setAttribute (ATTR_PAYMENT, p);
182
183         String JavaDoc url = "paymentInfo.jsp";
184         log.info ("doGet - Forward to " + url);
185         RequestDispatcher dispatcher = getServletContext ().getRequestDispatcher (url);
186         dispatcher.forward (request, response);
187     } // doGet
188

189     /**
190      * Process the HTTP Post request.
191      * The actual payment processing
192      *
193      * @param request request
194      * @param response response
195      * @throws ServletException
196      * @throws IOException
197      */

198     public void doPost(HttpServletRequest request, HttpServletResponse response)
199         throws ServletException, IOException
200     {
201         log.info("doPost from " + request.getRemoteHost() + " - " + request.getRemoteAddr());
202         Properties ctx = JSPEnv.getCtx(request);
203         HttpSession session = request.getSession(true);
204         WEnv.dump(session);
205         WEnv.dump(request);
206
207         // Web User/Payment
208
WebUser wu = (WebUser)session.getAttribute(WebUser.NAME);
209         MPayment p = (MPayment)session.getAttribute (ATTR_PAYMENT);
210         WebOrder wo = (WebOrder)session.getAttribute (WebOrder.NAME);
211
212         String JavaDoc url = null;
213         if (wu == null || p == null)
214             url = "index.jsp";
215         else if (processPayment(request, ctx, p, wu, wo))
216             url = "confirm.jsp";
217         else
218             url = "paymentInfo.jsp";
219
220         log.info ("doPost - Forward to " + url);
221         RequestDispatcher dispatcher = getServletContext ().getRequestDispatcher (url);
222         dispatcher.forward (request, response);
223     } // doPost
224

225
226     /*************************************************************************/
227
228     /**
229      * Process Payment.
230      * @param request request
231      * @param ctx context
232      * @param p payment
233      * @param wu web user
234      * @param wo web order
235      * @return true if processed
236      */

237     private boolean processPayment(HttpServletRequest request, Properties ctx, MPayment p, WebUser wu, WebOrder wo)
238     {
239         boolean ok = processParameter(request, ctx, p, wu);
240         if (ok)
241         {
242             // if negative amount - make it positive
243
if (p.getPayAmt().compareTo(Env.ZERO) < 0)
244                 p.setPayAmt(p.getPayAmt().abs());
245             ok = p.processOnline();
246             if (ok)
247             {
248                 // Process Web Order and Set Invoice ID
249
if (wo != null)
250                 {
251                     if (!wo.isProcessed())
252                         wo.process();
253                     if (wo.isProcessed())
254                         p.setC_Invoice_ID(wo.getInvoice_ID());
255                     else
256                         log.warn("processPayment - Order not processed " + wo);
257                 }
258                 else
259                     log.warn("processPayment - no Order");
260                 p.post ();
261                 sendEMail (request, ctx, p, wu);
262             }
263             else
264             {
265                 log.debug("processPayment - " + p.getErrorMessage());
266                 String JavaDoc errMsg = p.getErrorMessage();
267                 p.save ();
268                 p.setErrorMessage(errMsg);
269                 request.getSession().setAttribute(JSPEnv.HDR_MESSAGE, errMsg);
270                 //
271
sendDeclineEMail(request, ctx, p, wu);
272             }
273         }
274         return ok;
275     } // processPayment
276

277     /**
278      * Process Parameter and check them
279      * @param request request
280      * @param ctx context
281      * @param p payment
282      * @param wu web user
283      * @return true if processed
284      */

285     private boolean processParameter (HttpServletRequest request, Properties ctx, MPayment p, WebUser wu)
286     {
287         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
288         p.setTenderType(MPayment.TENDERTYPE_CreditCard);
289         p.setTrxType(MPayment.TRXTYPE_Sales);
290         p.setA_EMail(wu.getEmail());
291         // CC & Number
292
String JavaDoc ccType = request.getParameter("CreditCard");
293         p.setCreditCardType(ccType);
294         String JavaDoc ccNumber = request.getParameter("CreditCardNumber");
295         p.setCreditCardNumber (ccNumber);
296         String JavaDoc AD_Message = MPayment.validateCreditCardNumber(ccNumber, ccType);
297         if (AD_Message.length() > 0)
298             sb.append(Msg.getMsg(ctx, AD_Message)).append(" - ");
299
300         // Optional Verification Code
301
String JavaDoc ccVV = request.getParameter("CreditCardVV");
302         p.setCreditCardVV(ccVV);
303         if (ccVV != null && ccVV.length() > 0)
304         {
305             AD_Message = MPayment.validateCreditCardVV (ccVV, ccType);
306             if (AD_Message.length () > 0)
307                 sb.append (Msg.getMsg (ctx, AD_Message)).append (" - ");
308         }
309         // Exp
310
int mm = WUtil.getParameterAsInt(request, "CreditCardExpMM");
311         p.setCreditCardExpMM (mm);
312         int yy = WUtil.getParameterAsInt(request, "CreditCardExpYY");
313         p.setCreditCardExpYY (yy);
314         AD_Message = MPayment.validateCreditCardExp(mm, yy);
315         if (AD_Message.length() > 0)
316             sb.append(Msg.getMsg(ctx, AD_Message)).append(" - ");
317
318         // Account Info
319
String JavaDoc aName = request.getParameter("A_Name");
320         if (aName == null || aName.length() == 0)
321             sb.append("Name - ");
322         else
323             p.setA_Name(aName);
324         String JavaDoc aStreet = request.getParameter("A_Street");
325         p.setA_Street(aStreet);
326         String JavaDoc aCity = request.getParameter("A_City");
327         if (aCity == null || aCity.length() == 0)
328             sb.append("City - ");
329         else
330             p.setA_City(aCity);
331         String JavaDoc aState = request.getParameter("A_State");
332         p.setA_State(aState);
333         String JavaDoc aZip = request.getParameter("A_Zip");
334         if (aZip == null || aZip.length() == 0)
335             sb.append("Zip - ");
336         else
337             p.setA_Zip(aZip);
338         String JavaDoc aCountry = request.getParameter("A_Country");
339         p.setA_Country(aCountry);
340
341         // Error Message
342
boolean ok = sb.length() == 0;
343         p.setErrorMessage(sb.toString()); // always set
344

345         // Save BP Bank Account
346
if (ok)
347         {
348             String JavaDoc SP = "SavePayment";
349             String JavaDoc SavePayment = request.getParameter (SP);
350             if (SP.equals(SavePayment))
351                 p.saveToBP_BankAccount(wu.getBankAccount());
352         }
353         //
354
return sb.length() == 0;
355     } // processParameter
356

357
358     /**
359      * Send Payment EMail.
360      * @param request request
361      * @param ctx context
362      * @param p payment
363      * @param wu web user
364      */

365     private void sendEMail (HttpServletRequest request, Properties ctx, MPayment p, WebUser wu)
366     {
367         String JavaDoc subject = "Compiere Web - " + p.getPayAmt() + " Payment - " + p.getDocumentNo();
368         String JavaDoc message = "Dear " + wu.getName()
369             + "\nThank you for your payment of " + p.getPayAmt() + " (Reference=" + p.getR_PnRef() + ")"
370             + "\nYou can view your orders, payments and assets at http://"
371             + request.getServerName() + request.getContextPath() + "/"
372             + "\nSincerely,"
373             + "\n The " + ctx.getProperty("description") + " Team";
374
375         String JavaDoc SMTPHost = ctx.getProperty("SMTPHost", "localhost");
376         String JavaDoc RequestEMail = ctx.getProperty("RequestEMail");
377         String JavaDoc RequestUser = ctx.getProperty("RequestUser");
378         String JavaDoc RequestUserPw = ctx.getProperty("RequestUserPw");
379         //
380
EMail em = new EMail(SMTPHost, RequestEMail, wu.getEmail(), subject, message);
381         em.setEMailUser(RequestUser, RequestUserPw);
382         //
383
String JavaDoc webOrderEMail = ctx.getProperty("webOrderEMail");
384         em.addBcc(webOrderEMail);
385         //
386
em.send();
387     } // sendEMail
388

389     /**
390      * Send Payment EMail.
391      * @param request request
392      * @param ctx context
393      * @param p payment
394      * @param wu web user
395      */

396     private void sendDeclineEMail (HttpServletRequest request, Properties ctx, MPayment p, WebUser wu)
397     {
398         String JavaDoc subject = "Compiere Web - Declined Payment " + p.getDocumentNo();
399         String JavaDoc message = "Payment of " + p.getPayAmt() + " (Reference=" + p.getR_PnRef() + ")"
400             + "\nwas declined " + p.getErrorMessage()
401             + "\nUser=" + wu.getName() + " - " + wu.getEmail();
402
403         String JavaDoc SMTPHost = ctx.getProperty("SMTPHost", "localhost");
404         String JavaDoc RequestEMail = ctx.getProperty("RequestEMail");
405         String JavaDoc RequestUser = ctx.getProperty("RequestUser");
406         String JavaDoc RequestUserPw = ctx.getProperty("RequestUserPw");
407         //
408
EMail em = new EMail(SMTPHost, RequestEMail, RequestEMail, subject, message);
409         em.setEMailUser(RequestUser, RequestUserPw);
410         //
411
String JavaDoc webOrderEMail = ctx.getProperty("webOrderEMail");
412         em.addBcc(webOrderEMail);
413         //
414
em.send();
415     } // sendDeclineEMail
416

417 } // PaymentServlet
418
Popular Tags