Search in sources :

Example 6 with OrderReadHelper

use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.

the class PaymentGatewayServices method releaseOrderPaymentPreference.

/**
 * Releases authorization for a single OrderPaymentPreference through service calls to the defined processing service for the ProductStore/PaymentMethodType
 * @return SUCCESS|FAILED|ERROR for complete processing of payment.
 */
public static Map<String, Object> releaseOrderPaymentPreference(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> result = ServiceUtil.returnSuccess();
    // Get the OrderPaymentPreference
    GenericValue paymentPref = null;
    try {
        paymentPref = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", orderPaymentPreferenceId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logWarning(e, "Problem getting OrderPaymentPreference for orderPaymentPreferenceId " + orderPaymentPreferenceId, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
    }
    // Error if no OrderPaymentPreference was found
    if (paymentPref == null) {
        Debug.logWarning("Could not find OrderPaymentPreference with orderPaymentPreferenceId: " + orderPaymentPreferenceId, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
    }
    // Get the OrderHeader
    GenericValue orderHeader = null;
    String orderId = paymentPref.getString("orderId");
    try {
        orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logWarning(e, "Problem getting OrderHeader for orderId " + orderId, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
    }
    // Error if no OrderHeader was found
    if (orderHeader == null) {
        Debug.logWarning("Could not find OrderHeader with orderId: " + orderId + "; not processing payments.", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
    }
    OrderReadHelper orh = new OrderReadHelper(orderHeader);
    String currency = orh.getCurrency();
    // look up the payment configuration settings
    String serviceName = null;
    String paymentConfig = null;
    String paymentGatewayConfigId = null;
    // get the payment settings i.e. serviceName and config properties file name
    GenericValue paymentSettings = getPaymentSettings(orderHeader, paymentPref, RELEASE_SERVICE_TYPE, false);
    if (paymentSettings != null) {
        String customMethodId = paymentSettings.getString("paymentCustomMethodId");
        if (UtilValidate.isNotEmpty(customMethodId)) {
            serviceName = getPaymentCustomMethod(orh.getOrderHeader().getDelegator(), customMethodId);
        }
        if (UtilValidate.isEmpty(serviceName)) {
            serviceName = paymentSettings.getString("paymentService");
        }
        paymentConfig = paymentSettings.getString("paymentPropertiesPath");
        paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
        if (serviceName == null) {
            Debug.logWarning("No payment release service for - " + paymentPref.getString("paymentMethodTypeId"), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale) + " " + paymentPref.getString("paymentMethodTypeId"));
        }
    } else {
        Debug.logWarning("No payment release settings found for - " + paymentPref.getString("paymentMethodTypeId"), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale) + " " + paymentPref.getString("paymentMethodTypeId"));
    }
    if (UtilValidate.isEmpty(paymentConfig)) {
        paymentConfig = "payment.properties";
    }
    GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(paymentPref);
    Map<String, Object> releaseContext = new HashMap<>();
    releaseContext.put("orderPaymentPreference", paymentPref);
    releaseContext.put("releaseAmount", authTransaction.getBigDecimal("amount"));
    releaseContext.put("currency", currency);
    releaseContext.put("paymentConfig", paymentConfig);
    releaseContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
    releaseContext.put("userLogin", userLogin);
    // run the defined service
    Map<String, Object> releaseResult = null;
    try {
        releaseResult = dispatcher.runSync(serviceName, releaseContext, TX_TIME, true);
    } catch (GenericServiceException e) {
        Debug.logError(e, "Problem releasing payment", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale));
    }
    // get the release result code
    if (releaseResult != null && ServiceUtil.isSuccess(releaseResult)) {
        Map<String, Object> releaseResRes;
        try {
            ModelService model = dctx.getModelService("processReleaseResult");
            releaseResult.put("orderPaymentPreference", paymentPref);
            releaseResult.put("userLogin", userLogin);
            Map<String, Object> resCtx = model.makeValid(releaseResult, ModelService.IN_PARAM);
            releaseResRes = dispatcher.runSync(model.name, resCtx);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Trouble processing the release results", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale) + " " + e.getMessage());
        }
        if (releaseResRes != null && ServiceUtil.isError(releaseResRes)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(releaseResRes));
        }
    } else if (ServiceUtil.isError(releaseResult)) {
        saveError(dispatcher, userLogin, paymentPref, releaseResult, RELEASE_SERVICE_TYPE, "PGT_RELEASE");
        result = ServiceUtil.returnError(ServiceUtil.getErrorMessage(releaseResult));
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) ModelService(org.apache.ofbiz.service.ModelService)

Example 7 with OrderReadHelper

use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.

the class PaymentGatewayServices method refundPayment.

public static Map<String, Object> refundPayment(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal refundAmount = (BigDecimal) context.get("refundAmount");
    Locale locale = (Locale) context.get("locale");
    GenericValue orderHeader = null;
    try {
        orderHeader = paymentPref.getRelatedOne("OrderHeader", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot get OrderHeader from OrderPaymentPreference", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + e.toString());
    }
    OrderReadHelper orh = new OrderReadHelper(orderHeader);
    GenericValue paymentSettings = null;
    if (orderHeader != null) {
        paymentSettings = getPaymentSettings(orderHeader, paymentPref, REFUND_SERVICE_TYPE, false);
    }
    String serviceName = null;
    String paymentGatewayConfigId = null;
    if (paymentSettings != null) {
        String customMethodId = paymentSettings.getString("paymentCustomMethodId");
        if (UtilValidate.isNotEmpty(customMethodId)) {
            serviceName = getPaymentCustomMethod(orh.getOrderHeader().getDelegator(), customMethodId);
        }
        if (UtilValidate.isEmpty(serviceName)) {
            serviceName = paymentSettings.getString("paymentService");
        }
        String paymentConfig = paymentSettings.getString("paymentPropertiesPath");
        paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
        if (serviceName != null) {
            Map<String, Object> serviceContext = new HashMap<>();
            serviceContext.put("orderPaymentPreference", paymentPref);
            serviceContext.put("paymentConfig", paymentConfig);
            serviceContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
            serviceContext.put("currency", orh.getCurrency());
            // get the creditCard/address/email
            String payToPartyId = null;
            try {
                payToPartyId = getBillingInformation(orh, paymentPref, new HashMap<String, Object>());
            } catch (GenericEntityException e) {
                Debug.logError(e, "Problems getting billing information", module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingBillingAccountNotFound", UtilMisc.toMap("billingAccountId", ""), locale));
            }
            BigDecimal processAmount = refundAmount.setScale(decimals, rounding);
            serviceContext.put("refundAmount", processAmount);
            serviceContext.put("userLogin", userLogin);
            // call the service
            Map<String, Object> refundResponse = null;
            try {
                refundResponse = dispatcher.runSync(serviceName, serviceContext, TX_TIME, true);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Problem refunding payment through processor", module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentRefundError", locale));
            }
            if (ServiceUtil.isError(refundResponse)) {
                saveError(dispatcher, userLogin, paymentPref, refundResponse, REFUND_SERVICE_TYPE, "PGT_REFUND");
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(refundResponse));
            }
            // get the pay to party ID for the order (will be the payFrom)
            String payFromPartyId = getPayToPartyId(orderHeader);
            // process the refund result
            Map<String, Object> refundResRes;
            try {
                ModelService model = dctx.getModelService("processRefundResult");
                Map<String, Object> refundResCtx = model.makeValid(context, ModelService.IN_PARAM);
                refundResCtx.put("currencyUomId", orh.getCurrency());
                refundResCtx.put("payToPartyId", payToPartyId);
                refundResCtx.put("payFromPartyId", payFromPartyId);
                refundResCtx.put("refundRefNum", refundResponse.get("refundRefNum"));
                refundResCtx.put("refundAltRefNum", refundResponse.get("refundAltRefNum"));
                refundResCtx.put("refundMessage", refundResponse.get("refundMessage"));
                refundResCtx.put("refundResult", refundResponse.get("refundResult"));
                // The refund amount could be different from what we tell the payment gateway due to issues
                // such as having to void the entire original auth amount and re-authorize the new order total.
                BigDecimal actualRefundAmount = (BigDecimal) refundResponse.get("refundAmount");
                if (actualRefundAmount != null && actualRefundAmount.compareTo(processAmount) != 0) {
                    refundResCtx.put("refundAmount", refundResponse.get("refundAmount"));
                }
                refundResRes = dispatcher.runSync(model.name, refundResCtx);
                if (ServiceUtil.isError(refundResRes)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(refundResRes));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentRefundError", locale) + " " + e.getMessage());
            }
            return refundResRes;
        } else {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentRefundServiceNotDefined", locale));
        }
    } else {
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "AccountingPaymentSettingNotFound", UtilMisc.toMap("productStoreId", orderHeader.getString("productStoreId"), "transactionType", REFUND_SERVICE_TYPE), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) BigDecimal(java.math.BigDecimal) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) ModelService(org.apache.ofbiz.service.ModelService)

Example 8 with OrderReadHelper

use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.

the class PaymentGatewayServices method processReAuthFromCaptureFailure.

private static void processReAuthFromCaptureFailure(DispatchContext dctx, Map<String, Object> result, BigDecimal amount, GenericValue userLogin, GenericValue paymentPreference, Locale locale) throws GeneralException {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    // lookup the order header
    OrderReadHelper orh = null;
    try {
        GenericValue orderHeader = paymentPreference.getRelatedOne("OrderHeader", false);
        if (orderHeader != null) {
            orh = new OrderReadHelper(orderHeader);
        }
    } catch (GenericEntityException e) {
        throw new GeneralException("Problems getting OrderHeader; cannot re-auth the payment", e);
    }
    // make sure the order exists
    if (orh == null) {
        throw new GeneralException("No order found for payment preference #" + paymentPreference.get("orderPaymentPreferenceId"));
    }
    // set the re-auth amount
    if (amount == null) {
        amount = ZERO;
    }
    if (amount.compareTo(ZERO) == 0) {
        amount = paymentPreference.getBigDecimal("maxAmount");
        Debug.logInfo("resetting payment amount from 0.00 to correctMax amount", module);
    }
    Debug.logInfo("reauth with amount: " + amount, module);
    // first re-auth the card
    Map<String, Object> authPayRes = authPayment(dispatcher, userLogin, orh, paymentPreference, amount, true, null);
    if (authPayRes == null) {
        throw new GeneralException("Null result returned from payment re-authorization");
    }
    // check the auth-response
    Boolean authResp = (Boolean) authPayRes.get("authResult");
    Boolean capResp = (Boolean) authPayRes.get("captureResult");
    if (authResp != null && Boolean.TRUE.equals(authResp)) {
        GenericValue authTrans = processAuthRetryResult(dctx, authPayRes, userLogin, paymentPreference);
        // check if auto-capture was enabled; process if so
        if (capResp != null && capResp.booleanValue()) {
            processCaptureResult(dctx, result, userLogin, paymentPreference, locale);
        } else {
            // no auto-capture; do manual capture now
            Map<String, Object> capPayRes = capturePayment(dctx, userLogin, orh, paymentPreference, amount, authTrans, locale);
            if (capPayRes == null) {
                throw new GeneralException("Problems trying to capture payment (null result)");
            }
            // process the capture result
            Boolean capPayResp = (Boolean) capPayRes.get("captureResult");
            if (capPayResp != null && capPayResp.booleanValue()) {
                // process the capture result
                processCaptureResult(dctx, capPayRes, userLogin, paymentPreference, locale);
            } else {
                throw new GeneralException("Capture of authorized payment failed");
            }
        }
    } else {
        throw new GeneralException("Payment re-authorization failed");
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper)

Example 9 with OrderReadHelper

use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.

the class PaymentGatewayServices method authOrderPaymentPreference.

/**
 * Authorizes a single order preference with an option to specify an amount. The result map has the Booleans
 * "errors" and "finished" which notify the user if there were any errors and if the authorization was finished.
 * There is also a List "messages" for the authorization response messages and a BigDecimal, "processAmount" as the
 * amount processed.
 *
 * TODO: it might be nice to return the paymentGatewayResponseId
 */
public static Map<String, Object> authOrderPaymentPreference(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
    BigDecimal overrideAmount = (BigDecimal) context.get("overrideAmount");
    // validate overrideAmount if its available
    if (overrideAmount != null) {
        if (overrideAmount.compareTo(BigDecimal.ZERO) < 0) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingPaymentAmountIsNegative", UtilMisc.toMap("overrideAmount", overrideAmount), locale));
        }
        if (overrideAmount.compareTo(BigDecimal.ZERO) == 0) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingPaymentAmountIsZero", UtilMisc.toMap("overrideAmount", overrideAmount), locale));
        }
    }
    GenericValue orderHeader = null;
    GenericValue orderPaymentPreference = null;
    try {
        orderPaymentPreference = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", orderPaymentPreferenceId).queryOne();
        orderHeader = orderPaymentPreference.getRelatedOne("OrderHeader", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
    }
    OrderReadHelper orh = new OrderReadHelper(orderHeader);
    // get the total remaining
    BigDecimal totalRemaining = orh.getOrderGrandTotal();
    // get the process attempts so far
    Long procAttempt = orderPaymentPreference.getLong("processAttempt");
    if (procAttempt == null) {
        procAttempt = Long.valueOf(0);
    }
    // update the process attempt count
    orderPaymentPreference.set("processAttempt", Long.valueOf(procAttempt.longValue() + 1));
    try {
        orderPaymentPreference.store();
        orderPaymentPreference.refresh();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale));
    }
    // if we are already authorized, then this is a re-auth request
    boolean reAuth = false;
    if (orderPaymentPreference.get("statusId") != null && "PAYMENT_AUTHORIZED".equals(orderPaymentPreference.getString("statusId"))) {
        reAuth = true;
    }
    // use overrideAmount or maxAmount
    BigDecimal transAmount = null;
    if (overrideAmount != null) {
        transAmount = overrideAmount;
    } else {
        transAmount = orderPaymentPreference.getBigDecimal("maxAmount");
    }
    // round this before moving on just in case a funny number made it this far
    transAmount = transAmount.setScale(decimals, rounding);
    // if our transaction amount exists and is zero, there's nothing to process, so return
    if ((transAmount != null) && (transAmount.compareTo(BigDecimal.ZERO) <= 0)) {
        Map<String, Object> results = ServiceUtil.returnSuccess();
        // finished is true since there is nothing to do
        results.put("finished", Boolean.TRUE);
        // errors is false since no error occurred
        results.put("errors", Boolean.FALSE);
        return results;
    }
    try {
        // call the authPayment method
        Map<String, Object> authPaymentResult = authPayment(dispatcher, userLogin, orh, orderPaymentPreference, totalRemaining, reAuth, transAmount);
        // handle the response
        if (authPaymentResult != null) {
            // not null result means either an approval or decline; null would mean error
            BigDecimal thisAmount = (BigDecimal) authPaymentResult.get("processAmount");
            // process the auth results
            try {
                boolean processResult = processResult(dctx, authPaymentResult, userLogin, orderPaymentPreference, locale);
                if (processResult) {
                    Map<String, Object> results = ServiceUtil.returnSuccess();
                    results.put("messages", authPaymentResult.get("customerRespMsgs"));
                    results.put("processAmount", thisAmount);
                    results.put("finished", Boolean.TRUE);
                    results.put("errors", Boolean.FALSE);
                    results.put("authCode", authPaymentResult.get("authCode"));
                    return results;
                } else {
                    boolean needsNsfRetry = needsNsfRetry(orderPaymentPreference, authPaymentResult, delegator);
                    // if we are doing an NSF retry then also...
                    if (needsNsfRetry) {
                    // TODO: what do we do with this? we need to fail the auth but still allow the order through so it can be fixed later
                    // NOTE: this is called through a different path for auto re-orders, so it should be good to go... will leave this comment here just in case...
                    }
                    // if we have a failure at this point and no NSF retry is needed, then try other credit cards on file, if the user has any
                    if (!needsNsfRetry) {
                        // is this an auto-order?
                        if (UtilValidate.isNotEmpty(orderHeader.getString("autoOrderShoppingListId"))) {
                            GenericValue productStore = orderHeader.getRelatedOne("ProductStore", false);
                            // according to the store should we try other cards?
                            if ("Y".equals(productStore.getString("autoOrderCcTryOtherCards"))) {
                                // get other credit cards for the bill to party
                                List<GenericValue> otherPaymentMethodAndCreditCardList = null;
                                String billToPartyId = null;
                                GenericValue billToParty = orh.getBillToParty();
                                if (billToParty != null) {
                                    billToPartyId = billToParty.getString("partyId");
                                } else {
                                // TODO optional: any other ways to find the bill to party? perhaps look at info from OrderPaymentPreference, ie search back from other PaymentMethod...
                                }
                                if (UtilValidate.isNotEmpty(billToPartyId)) {
                                    otherPaymentMethodAndCreditCardList = EntityQuery.use(delegator).from("PaymentMethodAndCreditCard").where("partyId", billToPartyId, "paymentMethodTypeId", "CREDIT_CARD").filterByDate().queryList();
                                }
                                if (UtilValidate.isNotEmpty(otherPaymentMethodAndCreditCardList)) {
                                    for (GenericValue otherPaymentMethodAndCreditCard : otherPaymentMethodAndCreditCardList) {
                                        // change OrderPaymentPreference in memory only and call auth service
                                        orderPaymentPreference.set("paymentMethodId", otherPaymentMethodAndCreditCard.getString("paymentMethodId"));
                                        Map<String, Object> authRetryResult = authPayment(dispatcher, userLogin, orh, orderPaymentPreference, totalRemaining, reAuth, transAmount);
                                        try {
                                            boolean processRetryResult = processResult(dctx, authPaymentResult, userLogin, orderPaymentPreference, locale);
                                            if (processRetryResult) {
                                                // wow, we got here that means the other card was successful...
                                                // on success save the OrderPaymentPreference, and then return finished (which will break from loop)
                                                orderPaymentPreference.store();
                                                Map<String, Object> results = ServiceUtil.returnSuccess();
                                                results.put("messages", authRetryResult.get("customerRespMsgs"));
                                                results.put("processAmount", thisAmount);
                                                results.put("finished", Boolean.TRUE);
                                                results.put("errors", Boolean.FALSE);
                                                return results;
                                            }
                                        } catch (GeneralException e) {
                                            String errMsg = "Error saving and processing payment authorization results: " + e.toString();
                                            Debug.logError(e, errMsg + "; authRetryResult: " + authRetryResult, module);
                                            Map<String, Object> results = ServiceUtil.returnSuccess();
                                            results.put(ModelService.ERROR_MESSAGE, errMsg);
                                            results.put("finished", Boolean.FALSE);
                                            results.put("errors", Boolean.TRUE);
                                            return results;
                                        }
                                    // if no sucess, fall through to return not finished
                                    }
                                }
                            }
                        }
                    }
                    Map<String, Object> results = ServiceUtil.returnSuccess();
                    results.put("messages", authPaymentResult.get("customerRespMsgs"));
                    results.put("finished", Boolean.FALSE);
                    results.put("errors", Boolean.FALSE);
                    return results;
                }
            } catch (GeneralException e) {
                String errMsg = "Error saving and processing payment authorization results: " + e.toString();
                Debug.logError(e, errMsg + "; authPaymentResult: " + authPaymentResult, module);
                Map<String, Object> results = ServiceUtil.returnSuccess();
                results.put(ModelService.ERROR_MESSAGE, errMsg);
                results.put("finished", Boolean.FALSE);
                results.put("errors", Boolean.TRUE);
                return results;
            }
        } else {
            // error with payment processor; will try later
            String errMsg = "Invalid Order Payment Preference: maxAmount is 0";
            Debug.logInfo(errMsg, module);
            Map<String, Object> results = ServiceUtil.returnSuccess();
            results.put("finished", Boolean.FALSE);
            results.put("errors", Boolean.TRUE);
            results.put(ModelService.ERROR_MESSAGE, errMsg);
            orderPaymentPreference.set("statusId", "PAYMENT_CANCELLED");
            try {
                orderPaymentPreference.store();
            } catch (GenericEntityException e) {
                Debug.logError(e, "ERROR: Problem setting OrderPaymentPreference status to CANCELLED", module);
            }
            return results;
        }
    } catch (GeneralException e) {
        Debug.logError(e, "Error processing payment authorization", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingPaymentCannotBeAuthorized", UtilMisc.toMap("errroString", e.toString()), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) BigDecimal(java.math.BigDecimal) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with OrderReadHelper

use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.

the class PaymentGatewayServices method processCaptureSplitPayment.

public static Map<String, Object> processCaptureSplitPayment(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal splitAmount = (BigDecimal) context.get("splitAmount");
    String orderId = paymentPref.getString("orderId");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    String statusId = "PAYMENT_NOT_AUTH";
    if ("EXT_BILLACT".equals(paymentPref.getString("paymentMethodTypeId"))) {
        statusId = "PAYMENT_NOT_RECEIVED";
    } else if ("EXT_PAYPAL".equals(paymentPref.get("paymentMethodTypeId"))) {
        statusId = "PAYMENT_AUTHORIZED";
    }
    // create a new payment preference
    Debug.logInfo("Creating payment preference split", module);
    String newPrefId = delegator.getNextSeqId("OrderPaymentPreference");
    GenericValue newPref = delegator.makeValue("OrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", newPrefId));
    newPref.set("orderId", paymentPref.get("orderId"));
    newPref.set("paymentMethodTypeId", paymentPref.get("paymentMethodTypeId"));
    newPref.set("paymentMethodId", paymentPref.get("paymentMethodId"));
    newPref.set("maxAmount", splitAmount);
    newPref.set("statusId", statusId);
    newPref.set("createdDate", UtilDateTime.nowTimestamp());
    if (userLogin != null) {
        newPref.set("createdByUserLogin", userLogin.getString("userLoginId"));
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("New preference : " + newPref, module);
    }
    Map<String, Object> processorResult = null;
    try {
        // create the new payment preference
        delegator.create(newPref);
        // fake it and copy the existing auth with the remaining amount
        if ("EXT_PAYPAL".equals(paymentPref.get("paymentMethodTypeId"))) {
            String newAuthId = delegator.getNextSeqId("PaymentGatewayResponse");
            GenericValue authTrans = getAuthTransaction(paymentPref);
            GenericValue newAuthTrans = delegator.makeValue("PaymentGatewayResponse", authTrans);
            newAuthTrans.set("paymentGatewayResponseId", newAuthId);
            newAuthTrans.set("orderPaymentPreferenceId", newPref.get("orderPaymentPreferenceId"));
            newAuthTrans.set("amount", splitAmount);
            savePgr(dctx, newAuthTrans);
        } else if ("PAYMENT_NOT_AUTH".equals(statusId)) {
            // authorize the new preference
            processorResult = authPayment(dispatcher, userLogin, orh, newPref, splitAmount, false, null);
            if (processorResult != null) {
                // process the auth results
                boolean authResult = processResult(dctx, processorResult, userLogin, newPref, locale);
                if (!authResult) {
                    Debug.logError("Authorization failed : " + newPref + " : " + processorResult, module);
                }
            } else {
                Debug.logError("Payment not authorized : " + newPref + " (no process result)", module);
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "ERROR: cannot create new payment preference : " + newPref, module);
    } catch (GeneralException e) {
        if (processorResult != null) {
            Debug.logError(e, "Trouble processing the auth result: " + newPref + " : " + processorResult, module);
        } else {
            Debug.logError(e, "Trouble authorizing the payment: " + newPref, module);
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BigDecimal(java.math.BigDecimal) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper)

Aggregations

GenericValue (org.apache.ofbiz.entity.GenericValue)32 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)32 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)30 Delegator (org.apache.ofbiz.entity.Delegator)28 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)28 BigDecimal (java.math.BigDecimal)24 Locale (java.util.Locale)24 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)24 HashMap (java.util.HashMap)22 Timestamp (java.sql.Timestamp)7 Map (java.util.Map)5 GeneralException (org.apache.ofbiz.base.util.GeneralException)5 LinkedList (java.util.LinkedList)4 ModelService (org.apache.ofbiz.service.ModelService)3 NVPDecoder (com.paypal.sdk.core.nvp.NVPDecoder)2 NVPEncoder (com.paypal.sdk.core.nvp.NVPEncoder)2 PayPalException (com.paypal.sdk.exceptions.PayPalException)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 List (java.util.List)2