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
  * 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;
     @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;
     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) {
            if (StringUtils.isEmpty(customer.getLastName()) && gatewayCustomer != null) {
            if (StringUtils.isEmpty(customer.getEmailAddress()) && gatewayCustomer != null) {
        // 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))) {
        for (OrderPayment payment : paymentsToInvalidate) {
        // 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();
        Address billingAddress = null;
        if (responseDTO.getBillTo() != null) {
            billingAddress = .create();
            AddressDTO<PaymentResponseDTObillToDTO = responseDTO.getBillTo();
            //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");
            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");
            if (billToDTO.getAddressPhone() != null) {
                Phone billingPhone = .create();
        // Create the transaction for the payment
        PaymentTransaction transaction = .createTransaction();
        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()) {
        //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 = .save(payment);
        if (transaction.getSuccess()) {
        } 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
        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.

    protected void handleUnsuccessfulTransaction(OrderPayment payment) {
    public void markPaymentAsInvalid(Long orderPaymentId) {
        OrderPayment payment = .readPaymentById(orderPaymentId);
        if (payment == null) {
            throw new IllegalArgumentException("Could not find payment with id " + orderPaymentId);
    //TODO: this should return something more than just a String
    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();
        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