1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.shopping.action;
24  
25  import com.liferay.portal.kernel.log.Log;
26  import com.liferay.portal.kernel.log.LogFactoryUtil;
27  import com.liferay.portal.kernel.util.HttpUtil;
28  import com.liferay.portal.kernel.util.ParamUtil;
29  import com.liferay.portal.util.PortalUtil;
30  import com.liferay.portlet.shopping.NoSuchOrderException;
31  import com.liferay.portlet.shopping.model.ShoppingOrder;
32  import com.liferay.portlet.shopping.service.ShoppingOrderLocalServiceUtil;
33  import com.liferay.portlet.shopping.util.ShoppingPreferences;
34  import com.liferay.portlet.shopping.util.ShoppingUtil;
35  
36  import java.io.BufferedReader;
37  import java.io.InputStreamReader;
38  import java.io.PrintWriter;
39  
40  import java.net.URL;
41  import java.net.URLConnection;
42  
43  import java.util.Enumeration;
44  
45  import javax.servlet.http.HttpServletRequest;
46  import javax.servlet.http.HttpServletResponse;
47  
48  import org.apache.struts.action.Action;
49  import org.apache.struts.action.ActionForm;
50  import org.apache.struts.action.ActionForward;
51  import org.apache.struts.action.ActionMapping;
52  
53  /**
54   * <a href="PayPalNotificationAction.java.html"><b><i>View Source</i></b></a>
55   *
56   * @author Brian Wing Shun Chan
57   *
58   */
59  public class PayPalNotificationAction extends Action {
60  
61      public ActionForward execute(
62              ActionMapping mapping, ActionForm form, HttpServletRequest request,
63              HttpServletResponse response)
64          throws Exception {
65  
66          String invoice = null;
67  
68          try {
69              if (_log.isDebugEnabled()) {
70                  _log.debug("Receiving notification from PayPal");
71              }
72  
73              String query = "cmd=_notify-validate";
74  
75              Enumeration<String> enu = request.getParameterNames();
76  
77              while (enu.hasMoreElements()) {
78                  String name = enu.nextElement();
79  
80                  String value = request.getParameter(name);
81  
82                  query = query + "&" + name + "=" + HttpUtil.encodeURL(value);
83              }
84  
85              if (_log.isDebugEnabled()) {
86                  _log.debug("Sending response to PayPal " + query);
87              }
88  
89              URL url = new URL("https://www.paypal.com/cgi-bin/webscr");
90  
91              URLConnection urlc = url.openConnection();
92  
93              urlc.setDoOutput(true);
94              urlc.setRequestProperty(
95                  "Content-Type","application/x-www-form-urlencoded");
96  
97              PrintWriter pw = new PrintWriter(urlc.getOutputStream());
98  
99              pw.println(query);
100 
101             pw.close();
102 
103             BufferedReader br = new BufferedReader(
104                 new InputStreamReader(urlc.getInputStream()));
105 
106             String payPalStatus = br.readLine();
107 
108             br.close();
109 
110             String itemName = ParamUtil.getString(request, "item_name");
111             String itemNumber = ParamUtil.getString(request, "item_number");
112             invoice = ParamUtil.getString(request, "invoice");
113             String txnId = ParamUtil.getString(request, "txn_id");
114             String paymentStatus = ParamUtil.getString(
115                 request, "payment_status");
116             double paymentGross = ParamUtil.getDouble(request, "mc_gross");
117             String receiverEmail = ParamUtil.getString(
118                 request, "receiver_email");
119             String payerEmail = ParamUtil.getString(request, "payer_email");
120 
121             if (_log.isDebugEnabled()) {
122                 _log.debug("Receiving response from PayPal");
123                 _log.debug("Item name " + itemName);
124                 _log.debug("Item number " + itemNumber);
125                 _log.debug("Invoice " + invoice);
126                 _log.debug("Transaction ID " + txnId);
127                 _log.debug("Payment status " + paymentStatus);
128                 _log.debug("Payment gross " + paymentGross);
129                 _log.debug("Receiver email " + receiverEmail);
130                 _log.debug("Payer email " + payerEmail);
131             }
132 
133             if (payPalStatus.equals("VERIFIED") && validate(request)) {
134                 ShoppingOrderLocalServiceUtil.completeOrder(
135                     invoice, txnId, paymentStatus, paymentGross, receiverEmail,
136                     payerEmail, true);
137             }
138             else if (payPalStatus.equals("INVALID")) {
139             }
140 
141             return null;
142         }
143         catch (Exception e) {
144             PortalUtil.sendError(e, request, response);
145 
146             return null;
147         }
148     }
149 
150     protected boolean validate(HttpServletRequest request) throws Exception {
151 
152         // Invoice
153 
154         String ppInvoice = ParamUtil.getString(request, "invoice");
155 
156         ShoppingOrder order = ShoppingOrderLocalServiceUtil.getOrder(
157             ppInvoice);
158 
159         ShoppingPreferences shoppingPrefs = ShoppingPreferences.getInstance(
160             order.getCompanyId(), order.getGroupId());
161 
162         // Receiver email address
163 
164         String ppReceiverEmail = ParamUtil.getString(
165             request, "receiver_email");
166 
167         String payPalEmailAddress = shoppingPrefs.getPayPalEmailAddress();
168 
169         if (!payPalEmailAddress.equals(ppReceiverEmail)) {
170             return false;
171         }
172 
173         // Payment gross
174 
175         double ppGross = ParamUtil.getDouble(request, "mc_gross");
176 
177         double orderTotal = ShoppingUtil.calculateTotal(order);
178 
179         if (orderTotal != ppGross) {
180             return false;
181         }
182 
183         // Payment currency
184 
185         String ppCurrency = ParamUtil.getString(request, "mc_currency");
186 
187         String currencyId = shoppingPrefs.getCurrencyId();
188 
189         if (!currencyId.equals(ppCurrency)) {
190             return false;
191         }
192 
193         // Transaction ID
194 
195         String ppTxnId = ParamUtil.getString(request, "txn_id");
196 
197         try {
198             ShoppingOrderLocalServiceUtil.getPayPalTxnIdOrder(ppTxnId);
199 
200             return false;
201         }
202         catch (NoSuchOrderException nsoe) {
203         }
204 
205         return true;
206     }
207 
208     private static Log _log =
209          LogFactoryUtil.getLog(PayPalNotificationAction.class);
210 
211 }