use of org.broadleafcommerce.common.payment.dto.PaymentResponseDTO in project BroadleafCommerce by BroadleafCommerce.
the class CustomerPaymentGatewayAbstractController method createCustomerPayment.
// ***********************************************
// Customer Payment Result Processing
// ***********************************************
/**
* <p>This method is intended to initiate the creation of a saved payment token.</p>
*
* <p>This assumes that the implementing gateway's {@link org.broadleafcommerce.common.payment.service.PaymentGatewayWebResponseService}
* knows how to parse an incoming {@link javax.servlet.http.HttpServletRequest} into a
* {@link org.broadleafcommerce.common.payment.dto.PaymentResponseDTO} which will then be used by the
* customer profile engine to save a token to the user's account (e.g. wallet).</p>
*
* @param model - Spring MVC model
* @param request - the HTTPServletRequest (originating either from a Payment Gateway or from the implementing checkout engine)
* @param redirectAttributes - Spring MVC redirect attributes
* @return the resulting view
* @throws org.broadleafcommerce.common.vendor.service.exception.PaymentException
*/
public String createCustomerPayment(Model model, HttpServletRequest request, final RedirectAttributes redirectAttributes) throws PaymentException {
try {
PaymentResponseDTO responseDTO = getWebResponseService().translateWebResponse(request);
if (LOG.isTraceEnabled()) {
LOG.trace("HTTPRequest translated to Raw Response: " + responseDTO.getRawResponse());
}
Long customerPaymentId = applyCustomerTokenToProfile(responseDTO);
if (customerPaymentId != null) {
return getCustomerPaymentViewRedirect(String.valueOf(customerPaymentId));
}
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("HTTPRequest - " + webResponsePrintService.printRequest(request));
LOG.error("An exception was caught either from processing the response or saving the resulting " + "payment token to the customer's profile - delegating to the payment module to handle any other " + "exception processing. The error caught was: " + e);
}
handleProcessingException(e, redirectAttributes);
}
return getCustomerPaymentErrorRedirect();
}
use of org.broadleafcommerce.common.payment.dto.PaymentResponseDTO in project BroadleafCommerce by BroadleafCommerce.
the class PaymentGatewayAbstractController method process.
// ***********************************************
// Common Checkout Result Processing
// ***********************************************
/**
* This method is intended to initiate the final steps in checkout either
* via a request coming directly from a Payment Gateway (i.e. a Transparent Redirect) or from
* some sort of tokenization mechanism client-side.
*
* The assumption is that the implementing gateway's controller that extends this class
* will have implemented a {@link org.broadleafcommerce.common.payment.service.PaymentGatewayWebResponseService}
* with the ability to translate an {@link javax.servlet.http.HttpServletRequest} into a
* {@link org.broadleafcommerce.common.payment.dto.PaymentResponseDTO} which will then be used by the framework
* to create the appropriate order payments and transactions as well as invoke the checkout workflow
* if configured to do so.
*
* The general flow is as follows:
*
* try {
* translate http request to DTO
* apply payment to order (if unsuccessful, payment will be archived)
* if (not successful or not valid)
* redirect to error view
* if (complete checkout on callback == true)
* initiateCheckout(order id);
* else
* show review page;
* } catch (Exception e) {
* log error
* handle processing exception
* }
*
* @param model - Spring MVC model
* @param request - the HTTPServletRequest (originating either from a Payment Gateway or from the implementing checkout engine)
* @param redirectAttributes - Spring MVC redirect attributes
* @return the resulting view
* @throws PaymentException
*/
public String process(Model model, HttpServletRequest request, final RedirectAttributes redirectAttributes) throws PaymentException {
Long orderPaymentId = null;
try {
PaymentResponseDTO responseDTO = getWebResponseService().translateWebResponse(request);
if (LOG.isTraceEnabled()) {
LOG.trace("HTTPRequest translated to Raw Response: " + responseDTO.getRawResponse());
}
orderPaymentId = applyPaymentToOrder(responseDTO);
if (!responseDTO.isSuccessful()) {
if (LOG.isTraceEnabled()) {
LOG.trace("The Response DTO is marked as unsuccessful. Delegating to the " + "payment module to handle an unsuccessful transaction");
}
handleUnsuccessfulTransaction(model, redirectAttributes, responseDTO);
return getErrorViewRedirect();
}
if (!responseDTO.isValid()) {
throw new PaymentException("The validity of the response cannot be confirmed." + "Check the Tamper Proof Seal for more details.");
}
String orderId = responseDTO.getOrderId();
if (orderId == null) {
throw new RuntimeException("Order ID must be set on the Payment Response DTO");
}
if (responseDTO.isCompleteCheckoutOnCallback()) {
if (LOG.isTraceEnabled()) {
LOG.trace("The Response DTO for this Gateway is configured to complete checkout on callback. " + "Initiating Checkout with Order ID: " + orderId);
}
String orderNumber = initiateCheckout(Long.parseLong(orderId));
return getConfirmationViewRedirect(orderNumber);
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("The Gateway is configured to not complete checkout. " + "Redirecting to the Order Review Page for Order ID: " + orderId);
}
return getOrderReviewRedirect();
}
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("HTTPRequest - " + webResponsePrintService.printRequest(request));
LOG.error("An exception was caught either from processing the response and applying the payment to " + "the order, or an activity in the checkout workflow threw an exception. Attempting to " + "mark the payment as invalid and delegating to the payment module to handle any other " + "exception processing", e);
}
if (paymentGatewayCheckoutService != null && orderPaymentId != null) {
paymentGatewayCheckoutService.markPaymentAsInvalid(orderPaymentId);
}
handleProcessingException(e, redirectAttributes);
}
return getErrorViewRedirect();
}
use of org.broadleafcommerce.common.payment.dto.PaymentResponseDTO in project BroadleafCommerce by BroadleafCommerce.
the class AbstractTRCreditCardExtensionHandler method createTransparentRedirectForm.
@Override
public ExtensionResultStatusType createTransparentRedirectForm(Map<String, Map<String, String>> formParameters, PaymentRequestDTO requestDTO, Map<String, String> configurationSettings) throws PaymentException {
if (paymentGatewayResolver.isHandlerCompatible(getHandlerType())) {
if (formParameters != null && requestDTO != null && configurationSettings != null) {
// Populate any additional configs on the RequestDTO
for (String config : configurationSettings.keySet()) {
requestDTO.additionalField(config, configurationSettings.get(config));
}
PaymentResponseDTO responseDTO;
if (PaymentGatewayRequestType.CREATE_CUSTOMER_PAYMENT_TR.equals(requestDTO.getGatewayRequestType())) {
responseDTO = getTransparentRedirectService().createCustomerPaymentTokenForm(requestDTO);
} else if (PaymentGatewayRequestType.UPDATE_CUSTOMER_PAYMENT_TR.equals(requestDTO.getGatewayRequestType())) {
responseDTO = getTransparentRedirectService().updateCustomerPaymentTokenForm(requestDTO);
} else if (getConfiguration().isPerformAuthorizeAndCapture()) {
responseDTO = getTransparentRedirectService().createAuthorizeAndCaptureForm(requestDTO);
} else {
responseDTO = getTransparentRedirectService().createAuthorizeForm(requestDTO);
}
overrideCustomerPaymentReturnURLs(requestDTO, responseDTO);
populateFormParameters(formParameters, responseDTO);
}
return ExtensionResultStatusType.HANDLED_CONTINUE;
}
return ExtensionResultStatusType.NOT_HANDLED;
}
use of org.broadleafcommerce.common.payment.dto.PaymentResponseDTO 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;
}
use of org.broadleafcommerce.common.payment.dto.PaymentResponseDTO 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());
}
Aggregations