PageRenderTime 38ms CodeModel.GetById 22ms app.highlight 12ms RepoModel.GetById 0ms app.codeStats 1ms

/src/com/paypal/donation/services/PaymentService.java

https://gitlab.com/CORP-RESELLER/DonationWidget
Java | 327 lines | 265 code | 28 blank | 34 comment | 36 complexity | ec605014c74c4dc62a0805afcc24562e MD5 | raw file
  1package com.paypal.donation.services;
  2
  3import java.io.BufferedReader;
  4import java.io.InputStreamReader;
  5import java.io.PrintWriter;
  6import java.net.URL;
  7import java.net.URLConnection;
  8import java.net.URLEncoder;
  9import java.util.Date;
 10import java.util.Enumeration;
 11import java.util.HashMap;
 12import java.util.Map;
 13
 14import javax.servlet.http.HttpServletRequest;
 15import javax.servlet.http.HttpServletResponse;
 16
 17import org.apache.commons.logging.Log;
 18import org.apache.commons.logging.LogFactory;
 19
 20import com.paypal.donation.exceptions.CustomAPIException;
 21import com.paypal.donation.models.Currency;
 22import com.paypal.donation.models.Event;
 23import com.paypal.donation.models.EventHome;
 24import com.paypal.donation.models.RenderLocation;
 25import com.paypal.donation.models.RenderLocationHome;
 26import com.paypal.donation.models.Transaction;
 27import com.paypal.donation.models.TransactionHome;
 28import com.paypal.donation.models.User;
 29import com.paypal.donation.models.Widgetui;
 30import com.paypal.donation.utils.Constants;
 31import com.paypal.donation.utils.Utility;
 32import com.paypal.sdk.core.nvp.NVPDecoder;
 33import com.paypal.services.DoExpressCheckout;
 34import com.paypal.services.GetExpressCheckout;
 35import com.paypal.services.GetTransactionDetails;
 36import com.paypal.services.SetExpressCheckout;
 37
 38public class PaymentService {
 39	
 40	private static final Log LOG = LogFactory.getLog(PaymentService.class);
 41	private static final Log APILOG = LogFactory.getLog("apiErrors");
 42	
 43	private static PaymentService singletonObj = new PaymentService();
 44
 45	public static PaymentService getInstance() {
 46		return singletonObj;
 47	}
 48
 49	public void doPay(HttpServletRequest request, HttpServletResponse response)
 50			throws Exception {
 51
 52		LOG.debug("Starting PaymentService.doPay()");
 53		Map<String, String> data = new HashMap<String, String>();
 54		
 55		final String amount = request.getParameter("amountsList");
 56		final String widgetExternalId = request.getParameter("widgetId");
 57		//final String action = request.getParameter("method");
 58		Widgetui widgetui = null;
 59		User user = null;
 60		Currency currency = null;
 61		String serverUrl = Utility.getServerUrl();
 62		
 63		try {
 64			widgetui = WidgetService.getInstance().findWidgetuiByExternalId(widgetExternalId);
 65			currency = ApplicationProperties.findCurrencyById(widgetui.getGoalcurrency());
 66			user = UserService.getInstance().findUserByPayerId(widgetui.getPayerid());
 67			
 68			data.put(Constants.CURRENCYCODE, currency.getUnits());
 69			data.put(Constants.IPN_URL, serverUrl + "/ac?method=ipnMsg");
 70			data.put(Constants.RECEIVEREMAIL, user.getEmailId());
 71			
 72			// Update the render_location table with payment history
 73			RenderLocation renderLoc = new RenderLocation();
 74			renderLoc.setCountry(request.getLocale().getDisplayCountry());
 75			renderLoc.setHost(request.getRemoteHost());
 76			renderLoc.setIpaddress(request.getRemoteAddr());
 77			renderLoc.setLocale(request.getLocale().toString());
 78			renderLoc.setLanguage(request.getLocale().getDisplayLanguage());
 79			renderLoc.setAmount(new Double(amount));
 80			renderLoc.setDonateflag('Y');
 81			renderLoc.setPayerid(widgetui.getPayerid());
 82			renderLoc.setCreatedDt(new Date());
 83			renderLoc.setWidgetexternalid(widgetExternalId);
 84			RenderLocationHome.getInstance().persist(renderLoc);
 85			
 86			data.put(Constants.NOTE, ApplicationProperties.getProperty("PAYMENT_MEMO")+" "+widgetui.getTitle());
 87			NVPDecoder respDecoder = new NVPDecoder();
 88			data.put(Constants.AMT, amount);
 89			StringBuilder strBuf = new StringBuilder();
 90			strBuf.append(serverUrl).append("/ac?method=paymentSuccess&widgetId=");
 91			strBuf.append(widgetExternalId);
 92			strBuf.append("&payerId=");
 93			strBuf.append(widgetui.getPayerid());
 94			strBuf.append('&');
 95			strBuf.append(Constants.APP_RETURNURL);
 96			strBuf.append('=');
 97			if(widgetui.getWeburl() != null && widgetui.getWeburl().trim().length() > 0) {
 98				strBuf.append(widgetui.getWeburl());
 99			} else {
100				strBuf.append(ApplicationProperties.getProperty(Constants.DEFAULT_AFTER_DONATION_RETURN_PAGE));
101			}
102			data.put(Constants.RETURNURL, strBuf.toString());
103			data.put(Constants.CANCELURL, data.get(Constants.RETURNURL));
104			respDecoder.decode(SetExpressCheckout.getInstance().setExpressCheckoutCall(data));
105			
106			if ("Success".equals(respDecoder.get(Constants.ACK))) {
107				response.sendRedirect(ApplicationProperties.getProperty(Constants.MEC_URL)
108						+ respDecoder.get(Constants.TOKEN).toString());
109			} else {
110				// Display a user friendly Error on the page using any of
111				// the following error information returned by PayPal
112				final String errorCode = respDecoder.get("L_ERRORCODE0").toString();
113				final String errorLongMsg = respDecoder.get("L_LONGMESSAGE0").toString();
114				LOG.error(errorCode + "|" + errorLongMsg);
115				response.sendRedirect(Utility.getServerUrl()+"/error");
116			}
117		} catch (Exception exc) {
118			LOG.error("Error - PaymentService.doPay()");
119			LOG.error(Utility.getStackTrace(exc));
120			throw new CustomAPIException();
121		} finally {
122			data = null;
123			widgetui = null;
124			user = null;
125			currency = null;
126		}
127		LOG.debug("Ending PaymentService.doPay()");
128	}
129
130	public void getPaymentDetails(HttpServletRequest request,
131			HttpServletResponse response) throws Exception {
132
133		LOG.debug("Starting PaymentService.doGetPaymentDetails()");
134		NVPDecoder decoder = new NVPDecoder();
135		NVPDecoder transactionDecoder = new NVPDecoder();
136		Transaction transactionData = new Transaction();
137		final String payerId = request.getParameter("payerId");
138		final String widgetId = request.getParameter("widgetId");
139		final String token = request.getParameter("token");
140		Map<String, String> ecData = null;
141		try {
142			User user = UserService.getInstance().findUserByPayerId(payerId);
143			decoder.decode(GetExpressCheckout.getInstance().getExpressCheckoutCall(token, user.getEmailId()));
144			
145			if ("Success".equals(decoder.get(Constants.ACK))) {
146				transactionData.setEmailid(decoder.get(Constants.EMAIL));
147				// PayerId of the Receiver.
148				transactionData.setPayerid(payerId);
149				ecData = new HashMap<String, String>();
150				ecData.put(Constants.TOKEN, token);
151				ecData.put(Constants.PAYERID, decoder.get(Constants.PAYERID));
152				ecData.put(Constants.AMT, decoder.get(Constants.AMT));
153				ecData.put(Constants.RECEIVEREMAIL, user.getEmailId());
154				ecData.put(Constants.CURRENCYCODE, decoder.get(Constants.CURRENCYCODE));
155				ecData.put(Constants.IPN_URL, Utility.getServerUrl() + "/ac?method=ipnMsg");
156				
157				decoder.decode(DoExpressCheckout.getInstance().doExpressCheckoutCall(ecData));
158				
159				if ("Success".equals(decoder.get(Constants.ACK))) {
160					transactionDecoder.decode(GetTransactionDetails.getInstance().getTransactionDetails(decoder
161							.get(Constants.TRANSACTIONID), user.getEmailId()));
162					
163					final Date now = new Date();
164					transactionData.setAmount(new Double(transactionDecoder.get(Constants.AMT)));
165					transactionData.setCreatedDt(now);
166					transactionData.setUpdatedDt(now);
167					transactionData.setPaypaltransid(transactionDecoder.get(Constants.TRANSACTIONID));
168					transactionData.setStatus(transactionDecoder.get(Constants.PAYMENTSTATUS));
169					transactionData.setTransresponse(Utility.getDecodedString(transactionDecoder));
170					transactionData.setWidgetexternalid(widgetId);
171					transactionData.setTransactiontype("EC");
172					TransactionHome.getInstance().persist(transactionData);
173				} else {
174					APILOG.error("Error in PaymentService.doGetPaymentDetails()");
175					APILOG.error(Utility.getDecodedString(decoder));
176				}
177			} else {
178				APILOG.error("Error in PaymentService.doGetPaymentDetails()");
179				APILOG.error(Utility.getDecodedString(decoder));
180			}
181			if (request.getParameter(Constants.APP_RETURNURL) != null) {
182				response.sendRedirect(request.getParameter(Constants.APP_RETURNURL));
183			} else {
184				response.sendRedirect(ApplicationProperties.getProperty(Constants.DEFAULT_AFTER_DONATION_RETURN_PAGE));
185			}
186			LOG.debug("Ending PaymentService.doGetPaymentDetails()");
187		} catch (Exception exc) {
188			APILOG.error("Error in PaymentService.doGetPaymentDetails()");
189			APILOG.error(Utility.getDecodedString(decoder));
190			APILOG.error(Utility.getStackTrace(exc));
191			throw new CustomAPIException();
192		} finally {
193			decoder = null;
194			transactionData = null;
195			ecData = null;
196		}
197	}
198
199	public static void getIPN(HttpServletRequest request,
200			HttpServletResponse response) throws Exception {
201		
202	NVPDecoder decoder = new NVPDecoder();
203	try {
204		Enumeration<String> en = request.getParameterNames();
205		StringBuilder ipnMsg = new StringBuilder();
206		ipnMsg.append("cmd=_notify-validate");
207		while (en.hasMoreElements()) {
208			String paramName = (String) en.nextElement();
209			String paramValue = request.getParameter(paramName);
210			if("method".equals(paramName)){
211				continue;
212			}
213			ipnMsg.append('&').append(paramName).append('=').append(URLEncoder.encode(paramValue, "UTF-8"));
214		}
215		LOG.debug("Resending IPN message to paypal - " +ipnMsg.toString());
216		// post back to PayPal system to validate
217		// NOTE: change http: to https: in the following URL to verify using
218		// SSL (for increased security).
219		// using HTTPS requires either Java 1.4 or greater, or Java Secure
220		// Socket Extension (JSSE)
221		// and configured for older versions.
222		URL u = new URL(ApplicationProperties.getProperty(Constants.IPN_VALIDATE_URL));
223		URLConnection uc = u.openConnection();
224		uc.setDoOutput(true);
225		uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
226		PrintWriter pw = new PrintWriter(uc.getOutputStream());
227		pw.println(ipnMsg.toString());
228		pw.close();
229		BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
230		String res = in.readLine();
231		in.close();
232		LOG.debug("IPN response from paypal - " + res);
233		decoder.decode(ipnMsg.toString());
234		
235		// check notification validation
236		if (res.equals("VERIFIED")) {
237			Transaction transaction = null;
238			final Date now = new Date();				
239			final Event eventData = new Event();
240			boolean expressCheckoutTransaction = false; 
241			String status = decoder.get(ApplicationProperties.getProperty(Constants.IPN_AP_STATUS));
242			if (status == null){
243				status = decoder.get(ApplicationProperties.getProperty(Constants.IPN_EC_STATUS));
244				expressCheckoutTransaction = true;
245			}
246			eventData.setResponse(Utility.getDecodedString(decoder));
247			eventData.setCreatedDt(now);
248			eventData.setUpdatedDt(now);
249			eventData.setEventType("IPN");
250			eventData.setStatus(status);
251			EventHome.getInstance().persist(eventData);
252			String transactionId = null;
253			String senderEmail = null;
254			String amount = null;
255			String transactionType = null;
256			
257			if (expressCheckoutTransaction) {
258				//Express Checkout
259				if ("Refunded".equals(status)){
260					transactionId = decoder.get(ApplicationProperties.getProperty(Constants.IPN_EC_REFUND_TXNID));
261				} else {
262					transactionId = decoder.get(ApplicationProperties.getProperty(Constants.IPN_EC_TXNID));
263				}
264				senderEmail = decoder.get(ApplicationProperties.getProperty(Constants.IPN_EC_SENDEREMAIL));
265				transactionType = "EC";
266				amount = decoder.get(ApplicationProperties.getProperty(Constants.IPN_EC_TXNAMT));					
267				if(amount == null)
268					amount = "0" ;					
269			} /*else {
270				//Adaptive Payments - Amount is concatenated with Units. Ex:USD 5.00
271				transactionId = decoder.get(ApplicationProperties.getProperty(Constants.IPN_AP_TXNID));					
272				senderEmail = decoder.get(ApplicationProperties.getProperty(Constants.IPN_AP_SENDEREMAIL));
273				transactionType = "AP";
274				if ("Refunded".equals(status) || "Partially_Refunded".equals(status)) {
275					amount = decoder.get(ApplicationProperties
276							.getProperty(Constants.IPN_AP_TXN_REFUND_AMT));
277				} else {
278					amount = decoder.get(ApplicationProperties
279							.getProperty(Constants.IPN_AP_TXNAMT));
280				}
281				if (amount != null) {
282					String[] amountArray = amount.split(" ");
283					if(amountArray.length > 1) {
284						amount = amountArray[1];
285					} 
286				} else {
287					amount = "0";
288				}					
289			}*/
290			if (transactionId != null || "".equals(transactionId)) {
291				transaction = TransactionHome.getInstance().findByTransactionId(transactionId);
292				if(transaction == null){
293					LOG.error("Transaction not found -"+ Utility.getDecodedString(decoder));
294				} else if ("Refunded".equals(status) || "Partially_Refunded".equals(status) || (!Constants.COMPLETED.equalsIgnoreCase(transaction
295								.getStatus()) && Constants.COMPLETED.equalsIgnoreCase(status))) {
296					//Insert record in transaction table when there is a refund or transaction status change from Pending to Completed.
297					Transaction refTransaction = new Transaction();
298					refTransaction.setAmount(new Double(amount));
299					refTransaction.setCreatedDt(now);
300					refTransaction.setUpdatedDt(now);
301					refTransaction.setEmailid(senderEmail);
302					refTransaction.setPayerid(transaction.getPayerid());
303					refTransaction.setPaypaltransid(transactionId);
304					refTransaction.setTransresponse(Utility.getDecodedString(decoder));
305					refTransaction.setStatus(status);
306					refTransaction.setTransactiontype(transactionType);
307					refTransaction.setWidgetexternalid(transaction.getWidgetexternalid());	
308					TransactionHome.getInstance().persist(refTransaction);
309				} 
310			}
311		} else if (res.equals("INVALID")) {
312			LOG.error("Invalid IPN Received -"+ Utility.getDecodedString(decoder));
313		} else {
314			LOG.error("Error in IPN Status -"+ Utility.getDecodedString(decoder));
315		}
316
317	} catch (Exception exc) {
318		APILOG.error("Error in doIPNNotificationMsg");
319		APILOG.error(Utility.getDecodedString(decoder));
320		APILOG.error(Utility.getStackTrace(exc));
321		throw new CustomAPIException();
322	} finally {
323		decoder = null;
324	}
325
326}
327}