📄 paypalevents.java
字号:
// get the user GenericValue userLogin = null; String userLoginId = request.getParameter("custom"); if (userLoginId == null) userLoginId = "admin"; try { userLogin = delegator.findByPrimaryKey("UserLogin", UtilMisc.toMap("userLoginId", userLoginId)); } catch (GenericEntityException e) { Debug.logError(e, "Cannot get UserLogin for: " + userLoginId + "; cannot continue", module); request.setAttribute("_ERROR_MESSAGE_", "Problems getting authentication user."); return "error"; } // get the orderId String orderId = request.getParameter("invoice"); // get the order header GenericValue orderHeader = null; if (UtilValidate.isNotEmpty(orderId)) { try { orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId)); } catch (GenericEntityException e) { Debug.logError(e, "Cannot get the order header for order: " + orderId, module); request.setAttribute("_ERROR_MESSAGE_", "Problems getting order header."); return "error"; } } else { Debug.logError("PayPal did not callback with a valid orderId!", module); request.setAttribute("_ERROR_MESSAGE_", "No valid orderId returned with PayPal Callback."); return "error"; } if (orderHeader == null) { Debug.logError("Cannot get the order header for order: " + orderId, module); request.setAttribute("_ERROR_MESSAGE_", "Problems getting order header; not a valid orderId."); return "error"; } // get payment data String paymentCurrency = request.getParameter("mc_currency"); String paymentAmount = request.getParameter("mc_gross"); String paymentFee = request.getParameter("mc_fee"); String transactionId = request.getParameter("txn_id"); // get the transaction status String paymentStatus = request.getParameter("payment_status"); // attempt to start a transaction boolean okay = false; boolean beganTransaction = false; try { beganTransaction = TransactionUtil.begin(); if (paymentStatus.equals("Completed")) { okay = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId); } else if (paymentStatus.equals("Failed") || paymentStatus.equals("Denied")) { okay = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId); } if (okay) { // set the payment preference okay = setPaymentPreferences(delegator, dispatcher, userLogin, orderId, request); } } catch (Exception e) { String errMsg = "Error handling PayPal notification"; Debug.logError(e, errMsg, module); try { TransactionUtil.rollback(beganTransaction, errMsg, e); } catch (GenericTransactionException gte2) { Debug.logError(gte2, "Unable to rollback transaction", module); } } finally { if (!okay) { try { TransactionUtil.rollback(beganTransaction, "Failure in processing PayPal callback", null); } catch (GenericTransactionException gte) { Debug.logError(gte, "Unable to rollback transaction", module); } } else { try { TransactionUtil.commit(beganTransaction); } catch (GenericTransactionException gte) { Debug.logError(gte, "Unable to commit transaction", module); } } } if (okay) { // attempt to release the offline hold on the order (workflow) OrderChangeHelper.releaseInitialOrderHold(dispatcher, orderId); // call the email confirm service Map emailContext = UtilMisc.toMap("orderId", orderId); try { Map emailResult = dispatcher.runSync("sendOrderConfirmation", emailContext); } catch (GenericServiceException e) { Debug.logError(e, "Problems sending email confirmation", module); } } return "success"; } /** Event called when customer cancels a paypal order */ public static String cancelPayPalOrder(HttpServletRequest request, HttpServletResponse response) { ServletContext application = ((ServletContext) request.getAttribute("servletContext")); GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); // get the stored order id from the session String orderId = (String) request.getSession().getAttribute("PAYPAL_ORDER"); // attempt to start a transaction boolean beganTransaction = false; try { beganTransaction = TransactionUtil.begin(); } catch (GenericTransactionException gte) { Debug.logError(gte, "Unable to begin transaction", module); } // cancel the order boolean okay = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId); if (okay) { try { TransactionUtil.commit(beganTransaction); } catch (GenericTransactionException gte) { Debug.logError(gte, "Unable to commit transaction", module); } } else { try { TransactionUtil.rollback(beganTransaction, "Failure in processing PayPal cancel callback", null); } catch (GenericTransactionException gte) { Debug.logError(gte, "Unable to rollback transaction", module); } } // attempt to release the offline hold on the order (workflow) if (okay) OrderChangeHelper.releaseInitialOrderHold(dispatcher, orderId); request.setAttribute("_EVENT_MESSAGE_", "Previous PayPal order has been cancelled."); return "success"; } private static boolean setPaymentPreferences(GenericDelegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, String orderId, ServletRequest request) { Debug.logVerbose("Setting payment prefrences..", module); List paymentPrefs = null; try { Map paymentFields = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_NOT_RECEIVED"); paymentPrefs = delegator.findByAnd("OrderPaymentPreference", paymentFields); } catch (GenericEntityException e) { Debug.logError(e, "Cannot get payment preferences for order #" + orderId, module); return false; } if (paymentPrefs != null && paymentPrefs.size() > 0) { Iterator i = paymentPrefs.iterator(); while (i.hasNext()) { GenericValue pref = (GenericValue) i.next(); boolean okay = setPaymentPreference(dispatcher, userLogin, pref, request); if (!okay) return false; } } return true; } private static boolean setPaymentPreference(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, ServletRequest request) { String paymentDate = request.getParameter("payment_date"); String paymentType = request.getParameter("payment_type"); String paymentAmount = request.getParameter("mc_gross"); String paymentStatus = request.getParameter("payment_status"); String transactionId = request.getParameter("txn_id"); List toStore = new LinkedList(); // PayPal returns the timestamp in the format 'hh:mm:ss Jan 1, 2000 PST' // Parse this into a valid Timestamp Object SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss MMM d, yyyy z"); java.sql.Timestamp authDate = null; try { authDate = new java.sql.Timestamp(sdf.parse(paymentDate).getTime()); } catch (ParseException e) { Debug.logError(e, "Cannot parse date string: " + paymentDate, module); authDate = UtilDateTime.nowTimestamp(); } catch (NullPointerException e) { Debug.logError(e, "Cannot parse date string: " + paymentDate, module); authDate = UtilDateTime.nowTimestamp(); } paymentPreference.set("maxAmount", new Double(paymentAmount)); if (paymentStatus.equals("Completed")) { paymentPreference.set("statusId", "PAYMENT_RECEIVED"); } else { paymentPreference.set("statusId", "PAYMENT_CANCELLED"); } toStore.add(paymentPreference); GenericDelegator delegator = paymentPreference.getDelegator(); // create the PaymentGatewayResponse String responseId = delegator.getNextSeqId("PaymentGatewayResponse").toString(); GenericValue response = delegator.makeValue("PaymentGatewayResponse", null); response.set("paymentGatewayResponseId", responseId); response.set("paymentServiceTypeEnumId", "PRDS_PAY_EXTERNAL"); response.set("orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId")); response.set("paymentMethodTypeId", paymentPreference.get("paymentMethodTypeId")); response.set("paymentMethodId", paymentPreference.get("paymentMethodId")); // set the auth info response.set("amount", new Double(paymentAmount)); response.set("referenceNum", transactionId); response.set("gatewayCode", paymentStatus); response.set("gatewayFlag", paymentStatus.substring(0,1)); response.set("gatewayMessage", paymentType); response.set("transactionDate", authDate); toStore.add(response); // create a payment record too Map results = null; try { results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "comments", "Payment receive via PayPal")); } catch (GenericServiceException e) { Debug.logError(e, "Failed to execute service createPaymentFromPreference", module); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return false; } if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR))) { Debug.logError((String) results.get(ModelService.ERROR_MESSAGE), module); request.setAttribute("_ERROR_MESSAGE_", (String) results.get(ModelService.ERROR_MESSAGE)); return false; } try { delegator.storeAll(toStore); } catch (GenericEntityException e) { Debug.logError(e, "Cannot set payment preference/payment info", module); return false; } return true; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -