Search in sources :

Example 1 with CheckoutException

use of org.broadleafcommerce.core.checkout.service.exception.CheckoutException in project BroadleafCommerce by BroadleafCommerce.

the class DefaultPaymentGatewayCheckoutService method initiateCheckout.

@Override
public String initiateCheckout(Long orderId) throws Exception {
    Order order = orderService.findOrderById(orderId, true);
    if (order == null || order instanceof NullOrderImpl) {
        throw new IllegalArgumentException("Could not order with id " + orderId);
    }
    CheckoutResponse response;
    try {
        response = checkoutService.performCheckout(order);
    } catch (CheckoutException e) {
        throw new Exception(e);
    }
    if (response.getOrder().getOrderNumber() == null) {
        LOG.error("Order Number for Order ID: " + order.getId() + " is null.");
    }
    return response.getOrder().getOrderNumber();
}
Also used : Order(org.broadleafcommerce.core.order.domain.Order) CheckoutResponse(org.broadleafcommerce.core.checkout.service.workflow.CheckoutResponse) NullOrderImpl(org.broadleafcommerce.core.order.domain.NullOrderImpl) CheckoutException(org.broadleafcommerce.core.checkout.service.exception.CheckoutException) CheckoutException(org.broadleafcommerce.core.checkout.service.exception.CheckoutException)

Example 2 with CheckoutException

use of org.broadleafcommerce.core.checkout.service.exception.CheckoutException in project BroadleafCommerce by BroadleafCommerce.

the class ValidateAndConfirmPaymentActivity method execute.

@Override
public ProcessContext<CheckoutSeed> execute(ProcessContext<CheckoutSeed> context) throws Exception {
    Order order = context.getSeedData().getOrder();
    Map<String, Object> rollbackState = new HashMap<>();
    // There are definitely enough payments on the order. We now need to confirm each unconfirmed payment on the order.
    // Unconfirmed payments could be added for things like gift cards and account credits; they are not actually
    // decremented from the user's account until checkout. This could also be used in some credit card processing
    // situations
    // Important: The payment.getAmount() must be the final amount that is going to be confirmed. If the order total
    // changed, the order payments need to be adjusted to reflect this and must add up to the order total.
    // This can happen in the case of PayPal Express or other hosted gateways where the unconfirmed payment comes back
    // to a review page, the customer selects shipping and the order total is adjusted.
    /**
     * This list contains the additional transactions that were created to confirm previously unconfirmed transactions
     * which can occur if you send credit card data directly to Broadleaf and rely on this activity to confirm
     * that transaction
     */
    Map<OrderPayment, PaymentTransaction> additionalTransactions = new HashMap<>();
    List<ResponseTransactionPair> failedTransactions = new ArrayList<>();
    // Used for the rollback handler; we want to make sure that we roll back transactions that have already been confirmed
    // as well as transactions that we are about to confirm here
    List<PaymentTransaction> confirmedTransactions = new ArrayList<>();
    /**
     * This is a subset of the additionalTransactions that contains the transactions that were confirmed in this activity
     */
    Map<OrderPayment, PaymentTransactionType> additionalConfirmedTransactions = new HashMap<>();
    for (OrderPayment payment : order.getPayments()) {
        if (payment.isActive()) {
            for (PaymentTransaction tx : payment.getTransactions()) {
                if (OrderPaymentStatus.UNCONFIRMED.equals(orderPaymentStatusService.determineOrderPaymentStatus(payment)) && PaymentTransactionType.UNCONFIRMED.equals(tx.getType())) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Transaction " + tx.getId() + " is not confirmed. Proceeding to confirm transaction.");
                    }
                    PaymentResponseDTO responseDTO = orderPaymentConfirmationStrategy.confirmTransaction(tx, context);
                    if (responseDTO == null) {
                        String msg = "Unable to 'confirm' the UNCONFIRMED Transaction with id: " + tx.getId() + ". " + "The ResponseDTO null. Please check your order payment" + "confirmation strategy implementation";
                        LOG.error(msg);
                        throw new CheckoutException(msg, context.getSeedData());
                    }
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Transaction Confirmation Raw Response: " + responseDTO.getRawResponse());
                    }
                    if (responseDTO.getAmount() == null || responseDTO.getPaymentTransactionType() == null) {
                        // Log an error, an exception will get thrown later as the payments won't add up.
                        LOG.error("The ResponseDTO returned from the Gateway does not contain either an Amount or Payment Transaction Type. " + "Please check your implementation");
                    }
                    // Create a new transaction that references its parent UNCONFIRMED transaction.
                    PaymentTransaction transaction = orderPaymentService.createTransaction();
                    transaction.setAmount(responseDTO.getAmount());
                    transaction.setRawResponse(responseDTO.getRawResponse());
                    transaction.setSuccess(responseDTO.isSuccessful());
                    transaction.setType(responseDTO.getPaymentTransactionType());
                    transaction.setParentTransaction(tx);
                    transaction.setOrderPayment(payment);
                    transaction.setAdditionalFields(responseDTO.getResponseMap());
                    transaction = orderPaymentService.save(transaction);
                    additionalTransactions.put(payment, transaction);
                    if (responseDTO.isSuccessful()) {
                        // if response is successful, attempt to create a customer payment token
                        createCustomerPaymentToken(transaction);
                        additionalConfirmedTransactions.put(payment, transaction.getType());
                    } else {
                        failedTransactions.add(new ResponseTransactionPair(responseDTO, transaction.getId()));
                    }
                } else if (PaymentTransactionType.AUTHORIZE.equals(tx.getType()) || PaymentTransactionType.AUTHORIZE_AND_CAPTURE.equals(tx.getType())) {
                    // attempt to create a customer payment token if payment is marked as tokenized
                    createCustomerPaymentToken(tx);
                    // After each transaction is confirmed, associate the new list of confirmed transactions to the rollback state. This has the added
                    // advantage of being able to invoke the rollback handler if there is an exception thrown at some point while confirming multiple
                    // transactions. This is outside of the transaction confirmation block in order to capture transactions
                    // that were already confirmed prior to this activity running
                    confirmedTransactions.add(tx);
                }
            }
        }
    }
    // regardless of an error in the workflow later.
    for (OrderPayment payment : order.getPayments()) {
        if (additionalTransactions.containsKey(payment)) {
            PaymentTransactionType confirmedType = null;
            if (additionalConfirmedTransactions.containsKey(payment)) {
                confirmedType = additionalConfirmedTransactions.get(payment);
            }
            payment.addTransaction(additionalTransactions.get(payment));
            payment = orderPaymentService.save(payment);
            if (confirmedType != null) {
                List<PaymentTransaction> types = payment.getTransactionsForType(confirmedType);
                if (types.size() == 1) {
                    confirmedTransactions.add(types.get(0));
                } else {
                    throw new IllegalArgumentException("There should only be one AUTHORIZE or AUTHORIZE_AND_CAPTURE transaction." + "There are more than one confirmed payment transactions for Order Payment:" + payment.getId());
                }
            }
        }
    }
    // Once all transactions have been confirmed, add them to the rollback state.
    // If an exception is thrown after this, the confirmed transactions will need to be voided or reversed
    // (based on the implementation requirements of the Gateway)
    rollbackState.put(ROLLBACK_TRANSACTIONS, confirmedTransactions);
    ActivityStateManagerImpl.getStateManager().registerState(this, context, getRollbackHandler(), rollbackState);
    // Handle the failed transactions (default implementation is to throw a new CheckoutException)
    if (!failedTransactions.isEmpty()) {
        handleUnsuccessfulTransactions(failedTransactions, context);
    }
    // Add authorize and authorize_and_capture transactions;
    // there should only be one or the other in the payment
    // Also add any pending transactions (as these are marked as being AUTH or CAPTURED later)
    Money paymentSum = new Money(BigDecimal.ZERO);
    for (OrderPayment payment : order.getPayments()) {
        if (payment.isActive()) {
            paymentSum = paymentSum.add(payment.getSuccessfulTransactionAmountForType(PaymentTransactionType.AUTHORIZE)).add(payment.getSuccessfulTransactionAmountForType(PaymentTransactionType.AUTHORIZE_AND_CAPTURE)).add(payment.getSuccessfulTransactionAmountForType(PaymentTransactionType.PENDING));
        }
    }
    if (paymentSum.lessThan(order.getTotal())) {
        throw new IllegalArgumentException("There are not enough payments to pay for the total order. The sum of " + "the payments is " + paymentSum.getAmount().toPlainString() + " and the order total is " + order.getTotal().getAmount().toPlainString());
    }
    // that as well. Currently there isn't really a concept for that
    return context;
}
Also used : Order(org.broadleafcommerce.core.order.domain.Order) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) OrderPayment(org.broadleafcommerce.core.payment.domain.OrderPayment) CheckoutException(org.broadleafcommerce.core.checkout.service.exception.CheckoutException) PaymentTransaction(org.broadleafcommerce.core.payment.domain.PaymentTransaction) Money(org.broadleafcommerce.common.money.Money) PaymentTransactionType(org.broadleafcommerce.common.payment.PaymentTransactionType) PaymentResponseDTO(org.broadleafcommerce.common.payment.dto.PaymentResponseDTO)

Example 3 with CheckoutException

use of org.broadleafcommerce.core.checkout.service.exception.CheckoutException in project BroadleafCommerce by BroadleafCommerce.

the class ValidateAndConfirmPaymentActivity method handleUnsuccessfulTransactions.

/**
 * <p>
 * Default implementation is to throw a generic CheckoutException which will be caught and displayed
 * on the Checkout Page where the Customer can try again. In many cases, this is
 * sufficient as it is usually recommended to display a generic Error Message to prevent
 * Credit Card fraud.
 *
 * <p>
 * The configured payment gateway may return a more specific error.
 * Each gateway is different and will often times return different error codes based on the acquiring bank as well.
 * In that case, you may override this method to decipher these errors
 * and handle it appropriately based on your business requirements.
 */
protected void handleUnsuccessfulTransactions(List<ResponseTransactionPair> failedTransactions, ProcessContext<CheckoutSeed> context) throws Exception {
    // The Response DTO was not successful confirming/authorizing a transaction.
    String msg = "Attempting to confirm/authorize an UNCONFIRMED transaction on the order was unsuccessful.";
    /**
     * For each of the failed transactions we might need to register state with the rollback handler
     */
    List<OrderPayment> invalidatedPayments = new ArrayList<>();
    List<PaymentTransaction> failedTransactionsToRollBack = new ArrayList<>();
    List<PaymentResponseDTO> failedResponses = new ArrayList<>();
    for (ResponseTransactionPair responseTransactionPair : failedTransactions) {
        PaymentTransaction tx = orderPaymentService.readTransactionById(responseTransactionPair.getTransactionId());
        if (shouldRollbackFailedTransaction(responseTransactionPair)) {
            failedTransactionsToRollBack.add(tx);
        } else if (!invalidatedPayments.contains(tx.getOrderPayment())) {
            paymentGatewayCheckoutService.markPaymentAsInvalid(tx.getOrderPayment().getId());
            OrderPayment payment = orderPaymentService.save(tx.getOrderPayment());
            invalidatedPayments.add(payment);
        }
        failedResponses.add(responseTransactionPair.getResponseDTO());
    }
    /**
     * Even though the original transaction confirmation failed, there is still a possibility that we need to rollback
     * the failure. The use case is in the case of fraud checks, some payment gateways complete the AUTHORIZE prior to
     * executing the fraud check. Thus, the AUTHORIZE technically fails because of fraud but the user's card was still
     * charged. This handles the case of rolling back the AUTHORIZE transaction in that case
     */
    Map<String, Object> rollbackState = new HashMap<>();
    rollbackState.put(ROLLBACK_TRANSACTIONS, failedTransactionsToRollBack);
    context.getSeedData().getUserDefinedFields().put(FAILED_RESPONSES, failedResponses);
    ActivityStateManagerImpl.getStateManager().registerState(this, context, getRollbackHandler(), rollbackState);
    if (LOG.isErrorEnabled()) {
        LOG.error(msg);
    }
    if (LOG.isTraceEnabled()) {
        for (ResponseTransactionPair responseTransactionPair : failedTransactions) {
            LOG.trace(responseTransactionPair.getResponseDTO().getRawResponse());
        }
    }
    throw new CheckoutException(msg, context.getSeedData());
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) OrderPayment(org.broadleafcommerce.core.payment.domain.OrderPayment) CheckoutException(org.broadleafcommerce.core.checkout.service.exception.CheckoutException) PaymentTransaction(org.broadleafcommerce.core.payment.domain.PaymentTransaction) PaymentResponseDTO(org.broadleafcommerce.common.payment.dto.PaymentResponseDTO)

Example 4 with CheckoutException

use of org.broadleafcommerce.core.checkout.service.exception.CheckoutException in project BroadleafCommerce by BroadleafCommerce.

the class OrderPaymentConfirmationStrategyImpl method confirmTransactionInternal.

protected PaymentResponseDTO confirmTransactionInternal(PaymentTransaction tx, ProcessContext<CheckoutSeed> context, boolean isCheckout) throws PaymentException, WorkflowException, CheckoutException {
    // Cannot confirm anything here if there is no provider
    if (paymentConfigurationServiceProvider == null) {
        String msg = "There are unconfirmed payment transactions on this payment but no payment gateway" + " configuration or transaction confirmation service configured";
        LOG.error(msg);
        throw new CheckoutException(msg, context.getSeedData());
    }
    OrderPayment payment = tx.getOrderPayment();
    PaymentGatewayConfigurationService cfg = paymentConfigurationServiceProvider.getGatewayConfigurationService(tx.getOrderPayment().getGatewayType());
    PaymentResponseDTO responseDTO = null;
    // Auto-calculate totals and line items to send to the gateway when in a "Checkout Payment flow"
    // (i.e. where the transaction is part of a final payment that is meant to be charged last at checkout: UNCONFIRMED -> AUTHORIZE or UNCONFIRMED -> AUTHORIZE_AND_CAPTURE)
    // Note: the total for the request cannot be auto-calculated if the order contains multiple final payments (i.e. multiple credit cards)
    PaymentRequestDTO confirmationRequest;
    if (payment.isFinalPayment() && !orderContainsMultipleFinalPayments(payment.getOrder())) {
        confirmationRequest = orderToPaymentRequestService.translatePaymentTransaction(payment.getAmount(), tx, true);
    } else {
        confirmationRequest = orderToPaymentRequestService.translatePaymentTransaction(payment.getAmount(), tx);
    }
    populateBillingAddressOnRequest(confirmationRequest, payment);
    populateCustomerOnRequest(confirmationRequest, payment);
    populateShippingAddressOnRequest(confirmationRequest, payment);
    if (isCheckout && enablePendingPaymentsOnCheckoutConfirmation()) {
        responseDTO = constructPendingTransaction(payment.getType(), payment.getGatewayType(), confirmationRequest);
    } else {
        if (PaymentType.CREDIT_CARD.equals(payment.getType())) {
            // Handles the PCI-Compliant Scenario where you have an UNCONFIRMED CREDIT_CARD payment on the order.
            // This can happen if you send the Credit Card directly to Broadleaf or you use a Digital Wallet solution like MasterPass.
            // The Actual Credit Card PAN is stored in blSecurePU and will need to be sent to the Payment Gateway for processing.
            populateCreditCardOnRequest(confirmationRequest, payment);
            if (cfg.getConfiguration().isPerformAuthorizeAndCapture()) {
                responseDTO = cfg.getTransactionService().authorizeAndCapture(confirmationRequest);
            } else {
                responseDTO = cfg.getTransactionService().authorize(confirmationRequest);
            }
        } else {
            // This handles the THIRD_PARTY_ACCOUNT scenario (like PayPal Express Checkout) where
            // the transaction just needs to be confirmed with the Gateway
            responseDTO = cfg.getTransactionConfirmationService().confirmTransaction(confirmationRequest);
        }
    }
    return responseDTO;
}
Also used : PaymentRequestDTO(org.broadleafcommerce.common.payment.dto.PaymentRequestDTO) OrderPayment(org.broadleafcommerce.core.payment.domain.OrderPayment) PaymentGatewayConfigurationService(org.broadleafcommerce.common.payment.service.PaymentGatewayConfigurationService) PaymentResponseDTO(org.broadleafcommerce.common.payment.dto.PaymentResponseDTO) CheckoutException(org.broadleafcommerce.core.checkout.service.exception.CheckoutException)

Example 5 with CheckoutException

use of org.broadleafcommerce.core.checkout.service.exception.CheckoutException in project BroadleafCommerce by BroadleafCommerce.

the class CheckoutServiceImpl method performCheckout.

@Override
public CheckoutResponse performCheckout(Order order) throws CheckoutException {
    // Immediately fail if another thread is currently attempting to check out the order
    Object lockObject = putLock(order.getId());
    if (lockObject != null) {
        throw new CheckoutException("This order is already in the process of being submitted, unable to checkout order -- id: " + order.getId(), new CheckoutSeed(order, new HashMap<String, Object>()));
    }
    // Immediately fail if this order has already been checked out previously
    if (hasOrderBeenCompleted(order)) {
        throw new CheckoutException("This order has already been submitted or cancelled, unable to checkout order -- id: " + order.getId(), new CheckoutSeed(order, new HashMap<String, Object>()));
    }
    CheckoutSeed seed = null;
    try {
        // Do a final save of the order before going through with the checkout workflow
        order = orderService.save(order, false);
        seed = new CheckoutSeed(order, new HashMap<String, Object>());
        ProcessContext<CheckoutSeed> context = checkoutWorkflow.doActivities(seed);
        // We need to pull the order off the seed and save it here in case any activity modified the order.
        order = orderService.save(seed.getOrder(), false);
        order.getOrderMessages().addAll(((ActivityMessages) context).getActivityMessages());
        seed.setOrder(order);
        return seed;
    } catch (PricingException e) {
        throw new CheckoutException("Unable to checkout order -- id: " + order.getId(), e, seed);
    } catch (WorkflowException e) {
        throw new CheckoutException("Unable to checkout order -- id: " + order.getId(), e.getRootCause(), seed);
    } catch (RequiredAttributeNotProvidedException e) {
        throw new CheckoutException("Unable to checkout order -- id: " + order.getId(), e.getCause(), seed);
    } finally {
        // The order has completed processing, remove the order from the processing map
        removeLock(order.getId());
    }
}
Also used : PricingException(org.broadleafcommerce.core.pricing.service.exception.PricingException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) WorkflowException(org.broadleafcommerce.core.workflow.WorkflowException) RequiredAttributeNotProvidedException(org.broadleafcommerce.core.order.service.exception.RequiredAttributeNotProvidedException) CheckoutSeed(org.broadleafcommerce.core.checkout.service.workflow.CheckoutSeed) CheckoutException(org.broadleafcommerce.core.checkout.service.exception.CheckoutException)

Aggregations

CheckoutException (org.broadleafcommerce.core.checkout.service.exception.CheckoutException)5 HashMap (java.util.HashMap)3 PaymentResponseDTO (org.broadleafcommerce.common.payment.dto.PaymentResponseDTO)3 OrderPayment (org.broadleafcommerce.core.payment.domain.OrderPayment)3 ArrayList (java.util.ArrayList)2 Order (org.broadleafcommerce.core.order.domain.Order)2 PaymentTransaction (org.broadleafcommerce.core.payment.domain.PaymentTransaction)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Money (org.broadleafcommerce.common.money.Money)1 PaymentTransactionType (org.broadleafcommerce.common.payment.PaymentTransactionType)1 PaymentRequestDTO (org.broadleafcommerce.common.payment.dto.PaymentRequestDTO)1 PaymentGatewayConfigurationService (org.broadleafcommerce.common.payment.service.PaymentGatewayConfigurationService)1 CheckoutResponse (org.broadleafcommerce.core.checkout.service.workflow.CheckoutResponse)1 CheckoutSeed (org.broadleafcommerce.core.checkout.service.workflow.CheckoutSeed)1 NullOrderImpl (org.broadleafcommerce.core.order.domain.NullOrderImpl)1 RequiredAttributeNotProvidedException (org.broadleafcommerce.core.order.service.exception.RequiredAttributeNotProvidedException)1 PricingException (org.broadleafcommerce.core.pricing.service.exception.PricingException)1 WorkflowException (org.broadleafcommerce.core.workflow.WorkflowException)1