PageRenderTime 53ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

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