Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * #%L
   * BroadleafCommerce Framework
   * %%
   * Copyright (C) 2009 - 2013 Broadleaf Commerce
   * %%
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
  * 
  *       http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * #L%
  */
 
 package org.broadleafcommerce.core.payment.service;
 
 
 import java.util.List;
 
 
 @Service("blPaymentGatewayCheckoutService")
 
     @Resource(name = "blOrderService")
     protected OrderService orderService;
     
     @Resource(name = "blOrderPaymentService")
     
     @Resource(name = "blCheckoutService")
     protected CheckoutService checkoutService;
     
     @Resource(name = "blAddressService")
     protected AddressService addressService;
     
     @Resource(name = "blStateService")
     protected StateService stateService;
     
     @Resource(name = "blCountryService")
     protected CountryService countryService;
     
     @Resource(name = "blPhoneService")
     protected PhoneService phoneService;
     
     @Override
     public Long applyPaymentToOrder(PaymentResponseDTO responseDTOPaymentGatewayConfiguration config) {
         
         //Payments can ONLY be parsed into Order Payments if they are 'valid'
         if (!responseDTO.isValid()) {
             throw new IllegalArgumentException("Invalid payment responses cannot be parsed into the order payment domain");
         }
         
         if (config == null) {
            throw new IllegalArgumentException("Config service cannot be null");
        }
        
        Long orderId = Long.parseLong(responseDTO.getOrderId());
        Order order = .findOrderById(orderId);
        
        if (!..equals(order.getStatus()) && !..equals(order.getStatus())) {
            throw new IllegalArgumentException("Cannot apply another payment to an Order that is not IN_PROCESS or CSR_OWNED");
        }
        
        Customer customer = order.getCustomer();
        if (customer.isAnonymous()) {
            GatewayCustomerDTO<PaymentResponseDTOgatewayCustomer = responseDTO.getCustomer();
            if (StringUtils.isEmpty(customer.getFirstName()) && gatewayCustomer != null) {
                customer.setFirstName(gatewayCustomer.getFirstName());
            }
            if (StringUtils.isEmpty(customer.getLastName()) && gatewayCustomer != null) {
                customer.setLastName(gatewayCustomer.getLastName());
            }
            if (StringUtils.isEmpty(customer.getEmailAddress()) && gatewayCustomer != null) {
                customer.setEmailAddress(gatewayCustomer.getEmail());
            }
        }
        // If this gateway does not support multiple payments then mark all of the existing payments
        // as invalid before adding the new one
        List<OrderPaymentpaymentsToInvalidate = new ArrayList<OrderPayment>();
        if (!config.handlesMultiplePayments()) {
            PaymentGatewayType gateway = config.getGatewayType();
            for (OrderPayment payment : order.getPayments()) {
                // There may be a temporary Order Payment on the Order (e.g. to save the billing address)
                // This will be marked as invalid, as the billing address that will be saved on the order will be parsed off the
                // Response DTO sent back from the Gateway
                if (payment.getGatewayType() == . ||
                        (payment.getGatewayType() != null && payment.getGatewayType().equals(gateway))) {
                    paymentsToInvalidate.add(payment);
                }
            }
        }
        for (OrderPayment payment : paymentsToInvalidate) {
            order.getPayments().remove(payment);
            markPaymentAsInvalid(payment.getId());
        }
        // ALWAYS create a new order payment for the payment that comes in. Invalid payments should be cleaned up by
        // invoking {@link #markPaymentAsInvalid}.
        OrderPayment payment = .create();
        payment.setType(responseDTO.getPaymentType());
        payment.setPaymentGatewayType(responseDTO.getPaymentGatewayType());
        payment.setAmount(responseDTO.getAmount());
        
        Address billingAddress = null;
        if (responseDTO.getBillTo() != null) {
            billingAddress = .create();
            AddressDTO<PaymentResponseDTObillToDTO = responseDTO.getBillTo();
            billingAddress.setFirstName(billToDTO.getAddressFirstName());
            billingAddress.setLastName(billToDTO.getAddressLastName());
            billingAddress.setAddressLine1(billToDTO.getAddressLine1());
            billingAddress.setAddressLine2(billToDTO.getAddressLine2());
            billingAddress.setCity(billToDTO.getAddressCityLocality());
            
            //TODO: what happens if State and Country cannot be found?
            State state = .findStateByAbbreviation(billToDTO.getAddressStateRegion());
            if (state == null) {
                Log.warn("The given state from the response: " + billToDTO.getAddressStateRegion() + " could not be found"
                        + " as a state abbreviation in BLC_STATE");
            }
            billingAddress.setState(state);
            billingAddress.setPostalCode(billToDTO.getAddressPostalCode());
            
            Country country = .findCountryByAbbreviation(billToDTO.getAddressCountryCode());
            if (country == null) {
                Log.warn("The given country from the response: " + billToDTO.getAddressCountryCode() + " could not be found"
                        + " as a country abbreviation in BLC_COUNTRY");
            }
            billingAddress.setCountry(country);
            if (billToDTO.getAddressPhone() != null) {
                Phone billingPhone = .create();
                billingPhone.setPhoneNumber(billToDTO.getAddressPhone());
                billingAddress.setPhonePrimary(billingPhone);
            }
            payment.setBillingAddress(billingAddress);
        }
        
        // Create the transaction for the payment
        PaymentTransaction transaction = .createTransaction();
        transaction.setAmount(responseDTO.getAmount());
        transaction.setRawResponse(responseDTO.getRawResponse());
        transaction.setSuccess(responseDTO.isSuccessful());
        transaction.setType(responseDTO.getPaymentTransactionType());
        for (Entry<StringStringentry : responseDTO.getResponseMap().entrySet()) {
            transaction.getAdditionalFields().put(entry.getKey(), entry.getValue());
        }
        //Set the Credit Card Info on the Additional Fields Map
        if (..equals(responseDTO.getPaymentType()) &&
                responseDTO.getCreditCard().creditCardPopulated()) {
                    responseDTO.getCreditCard().getCreditCardHolderName());
            transaction.getAdditionalFields().put(..getType(),
                    responseDTO.getCreditCard().getCreditCardType());
            transaction.getAdditionalFields().put(..getType(),
                    responseDTO.getCreditCard().getCreditCardExpDate());
            transaction.getAdditionalFields().put(..getType(),
                    responseDTO.getCreditCard().getCreditCardLastFour());
        }
        
        //TODO: validate that this particular type of transaction can be added to the payment (there might already
        // be an AUTHORIZE transaction, for instance)
        //Persist the order payment as well as its transaction
        payment.setOrder(order);
        transaction.setOrderPayment(payment);
        payment.addTransaction(transaction);
        payment = .save(payment);
        if (transaction.getSuccess()) {
            .addPaymentToOrder(orderpaymentnull);
        } else {
            // We will have to mark the entire payment as invalid and boot the user to re-enter their
            // billing info and payment information as there may be an error either with the billing address/or credit card
            handleUnsuccessfulTransaction(payment);
        }
        
        return payment.getId();
    }

    
This default implementation will mark the entire payment as invalid and boot the user to re-enter their billing info and payment information as there may be an error with either the billing address or credit card. This is the safest method, because depending on the implementation of the Gateway, we may not know exactly where the error occurred (e.g. Address Verification enabled, etc...) So, we will assume that the error invalidates the entire Order Payment, and the customer will have to re-enter their billing and credit card information to be processed again.

Parameters:
payment
    protected void handleUnsuccessfulTransaction(OrderPayment payment) {
        markPaymentAsInvalid(payment.getId());
    }
    @Override
    public void markPaymentAsInvalid(Long orderPaymentId) {
        OrderPayment payment = .readPaymentById(orderPaymentId);
        if (payment == null) {
            throw new IllegalArgumentException("Could not find payment with id " + orderPaymentId);
        }
        .delete(payment);
    }
    //TODO: this should return something more than just a String
    @Override
    public String initiateCheckout(Long orderIdthrows Exception{
        Order order = .findOrderById(orderId);
        if (order == null || order instanceof NullOrderImpl) {
            throw new IllegalArgumentException("Could not order with id " + orderId);
        }
        
        try {
            CheckoutResponse response = .performCheckout(order);
        } catch (CheckoutException e) {
            //TODO: wrap the exception or put CheckoutException in common
            throw new Exception(e);
        }
        return order.getOrderNumber();
    }
    @Override
        Order order = .findOrderById(Long.parseLong(responseDTO.getOrderId()));
        if (order == null) {
            throw new IllegalArgumentException("An order with ID " + responseDTO.getOrderId() + " cannot be found for the" +
            		" given payment response.");
        }
        return order.getOrderNumber();
    }
New to GrepCode? Check out our FAQ X