private PaymentProcessingResult SendFulfillRequest(IPurchaseOrder po, IOrderForm orderForm, IPayment payment)
        {
            try
            {
                var requestDoc  = _requestDocumentCreation.CreateDocumentForFulfillRequest(payment, orderForm);
                var responseDoc = DocumentHelpers.SendTransaction(requestDoc, _dataCashConfiguration.Config);
                if (DocumentHelpers.IsSuccessful(responseDoc))
                {
                    // Extract the response details.
                    // When doing capture, refund, etc... transactions, DataCase will return a new Reference Id. We need to store this to ProviderTransactionID
                    // instead of TransactionID, because TransactionID should be the Authorization reference Id, and ProviderTransactionID will be used when we want to refund.
                    payment.ProviderTransactionID = DocumentHelpers.GetResponseInfo(responseDoc, "Response.datacash_reference");

                    var message = string.Format("[{0}] [Capture payment-{1}] [Status: {2}] .Response: {3} at Time stamp={4}",
                                                payment.PaymentMethodName,
                                                DocumentHelpers.GetResponseInfo(responseDoc, "Response.merchantreference"),
                                                DocumentHelpers.GetResponseInfo(responseDoc, "Response.status"),
                                                DocumentHelpers.GetResponseInfo(responseDoc, "Response.reason"),
                                                DocumentHelpers.GetResponseInfo(responseDoc, "Response.time")
                                                );

                    // add a new order note about this capture
                    AddNoteToPurchaseOrder(po, po.CustomerId, "CAPTURE", message);
                    _orderRepository.Save(po);

                    return(PaymentProcessingResult.CreateSuccessfulResult(message));
                }

                return(PaymentProcessingResult.CreateUnsuccessfulResult(DocumentHelpers.GetErrorMessage(responseDoc)));
            }
            catch (System.Exception e)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(e.Message));
            }
        }
        private PaymentProcessingResult SendRefundRequest(IPurchaseOrder po, IPayment payment)
        {
            try
            {
                var requestDoc  = _requestDocumentCreation.CreateDocumentForRefundRequest(payment);
                var responseDoc = DocumentHelpers.SendTransaction(requestDoc, _dataCashConfiguration.Config);
                if (DocumentHelpers.IsSuccessful(responseDoc))
                {
                    payment.ProviderTransactionID = DocumentHelpers.GetResponseInfo(responseDoc, "Response.datacash_reference");

                    var message = string.Format("[{0}] [RefundTransaction-{1}] [Status: {2}] Response: {3} at Time stamp={4}.",
                                                payment.PaymentMethodName,
                                                DocumentHelpers.GetResponseInfo(responseDoc, "Response.datacash_reference"),
                                                DocumentHelpers.GetResponseInfo(responseDoc, "Response.status"),
                                                DocumentHelpers.GetResponseInfo(responseDoc, "Response.reason"),
                                                DocumentHelpers.GetResponseInfo(responseDoc, "Response.time")
                                                );

                    // add a new order note about this refund
                    AddNoteToPurchaseOrder(po, po.CustomerId, "REFUND", message);
                    _orderRepository.Save(po);

                    return(PaymentProcessingResult.CreateSuccessfulResult(message));
                }

                return(PaymentProcessingResult.CreateUnsuccessfulResult(DocumentHelpers.GetErrorMessage(responseDoc)));
            }
            catch (System.Exception e)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(e.Message));
            }
        }
Exemple #3
0
        /// <summary>
        /// Process payment when user checkout.
        /// </summary>
        /// <param name="cart">The current cart.</param>
        /// <param name="payment">The payment to process.</param>
        /// <returns>return false and set the message will make the WorkFlow activity raise PaymentExcetion(message)</returns>
        private PaymentProcessingResult ProcessPaymentCheckout(ICart cart, IPayment payment)
        {
            var orderNumberId = _orderNumberGenerator.GenerateOrderNumber(cart);

            if (string.IsNullOrEmpty(_paymentMethodConfiguration.ExpChkoutUrl) || string.IsNullOrEmpty(_paymentMethodConfiguration.PaymentAction))
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PayPalSettingsError")));
            }

            var caller = PayPalApiHelper.GetPayPalApiCallerServices(_paymentMethodConfiguration);
            var setExpressChkOutReqType = new SetExpressCheckoutRequestType(SetupExpressCheckoutReqDetailsType(cart, payment, orderNumberId));
            var setChkOutResponse       = caller.SetExpressCheckout(new SetExpressCheckoutReq {
                SetExpressCheckoutRequest = setExpressChkOutReqType
            });
            var errorCheck = _payPalApiHelper.CheckErrors(setChkOutResponse);

            if (!string.IsNullOrEmpty(errorCheck))
            {
                _logger.Error(errorCheck);
                return(PaymentProcessingResult.CreateUnsuccessfulResult(string.Join("; ", setChkOutResponse.Errors.Select(e => e.LongMessage))));
            }

            payment.Properties[PayPalOrderNumberPropertyName] = orderNumberId;
            payment.Properties[PayPalExpTokenPropertyName]    = setChkOutResponse.Token;

            _orderRepository.Save(cart);

            // validation checking with PayPal OK (Server's PayPal API, Billing Address, Shipping Address, ... do redirect to PayPal.com
            var redirectUrl = CreateRedirectUrl(_paymentMethodConfiguration.ExpChkoutUrl, setChkOutResponse.Token);
            var message     = $"---PayPal-SetExpressCheckout is successful. Redirect end user to {redirectUrl}";

            _logger.Information(message);

            return(PaymentProcessingResult.CreateSuccessfulResult(message, redirectUrl));
        }
        private PaymentProcessingResult ProcessPaymentCheckout(IPayment payment, ICart cart)
        {
            var merchRef = DateTime.Now.Ticks.ToString();

            payment.Properties[DataCashMerchantReferencePropertyName] = merchRef; // A unique reference number for each transaction (Min 6, max 30 alphanumeric character)

            var notifyUrl = UriSupport.AbsoluteUrlBySettings(Utilities.GetUrlFromStartPageReferenceProperty("DataCashPaymentPage"));

            notifyUrl = UriUtil.AddQueryString(notifyUrl, "accept", "true");
            notifyUrl = UriUtil.AddQueryString(notifyUrl, "hash", Utilities.GetSHA256Key(merchRef + "accepted"));

            var requestDoc = _requestDocumentCreation.CreateDocumentForPaymentCheckout(cart, payment, notifyUrl);

            var    responseDoc = DocumentHelpers.SendTransaction(requestDoc, _dataCashConfiguration.Config);
            string redirectUrl;

            if (DocumentHelpers.IsSuccessful(responseDoc))
            {
                redirectUrl = $"{responseDoc.get("Response.HpsTxn.hps_url")}?HPS_SessionID={responseDoc.get("Response.HpsTxn.session_id")}";
                payment.Properties[DataCashReferencePropertyName] = responseDoc.get("Response.datacash_reference");
            }
            else
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(DocumentHelpers.GetErrorMessage(responseDoc)));
            }

            _orderRepository.Save(cart);

            var message = $"---DataCash--. Redirect end user to {redirectUrl}";

            _logger.Information(message);

            return(PaymentProcessingResult.CreateSuccessfulResult(message, redirectUrl));
        }
Exemple #5
0
        private PaymentProcessingResult ProcessPaymentCapture(IOrderGroup orderGroup,
                                                              ICreditCardPayment creditCardPayment,
                                                              IOrderAddress billingAddress)
        {
            if (string.IsNullOrEmpty(creditCardPayment.ProviderPaymentId))
            {
                return(Charge(orderGroup, creditCardPayment, billingAddress));
            }
            try
            {
                var capture = _stripeChargeService.Capture(creditCardPayment.ProviderPaymentId, new StripeChargeCaptureOptions());
                if (!string.IsNullOrEmpty(capture.FailureCode))
                {
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(capture.Outcome.Reason)));
                }
                creditCardPayment.ProviderPaymentId     = capture.Id;
                creditCardPayment.ProviderTransactionID = capture.BalanceTransactionId;
                return(PaymentProcessingResult.CreateSuccessfulResult(""));
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(e.StripeError.Code)));

                default:
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(e.StripeError.Message));
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Processes the payment. Can be used for both positive and negative transactions.
        /// </summary>
        /// <param name="orderGroup">The order group.</param>
        /// <param name="payment">The payment.</param>
        /// <returns>The payment processing result.</returns>
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            var creditCardPayment = (ICreditCardPayment)payment;

            return(creditCardPayment.CreditCardNumber.EndsWith("4")
                ? PaymentProcessingResult.CreateSuccessfulResult(string.Empty)
                : PaymentProcessingResult.CreateUnsuccessfulResult("Invalid credit card number."));
        }
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            OrderGroup = orderGroup;
            _orderForm = orderGroup.GetFirstForm();
            var message = string.Empty;

            return(ProcessPayment(payment, ref message)
                ? PaymentProcessingResult.CreateSuccessfulResult(message)
                : PaymentProcessingResult.CreateUnsuccessfulResult(message));
        }
        /// <summary>Process payment associated with shipment.</summary>
        /// <param name="orderGroup">The order group.</param>
        /// <param name="payment">The payment.</param>
        /// <param name="shipment">The shipment.</param>
        /// <returns><c>True</c> if process successful, otherwise <c>False</c>.</returns>
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment, IShipment shipment)
        {
            OrderGroup = orderGroup;
            _orderForm = orderGroup.GetFirstForm();
            var result  = ProcessPayment(payment, shipment);
            var message = result.Message;

            return(result.Status
                ? PaymentProcessingResult.CreateSuccessfulResult(message)
                : PaymentProcessingResult.CreateUnsuccessfulResult(message));
        }
Exemple #9
0
 public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
 {
     if (orderGroup == null)
     {
         return(PaymentProcessingResult.CreateUnsuccessfulResult("Failed to process your payment."));
     }
     else
     {
         GiftCardManager.PurchaseByGiftCard(payment);
         return(PaymentProcessingResult.CreateSuccessfulResult("Gift card processed"));
     }
 }
        /// <summary>
        /// Captures an authorized payment.
        /// </summary>
        /// <para>
        /// See API doc here https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoCapture_API_Operation_SOAP/
        /// </para>
        /// <param name="orderGroup">The order group to process.</param>
        /// <param name="payment">The payment to process</param>
        /// <returns>return false and set the message will make the WorkFlow activity raise PaymentExcetion(message)</returns>
        private PaymentProcessingResult ProcessPaymentCapture(IOrderGroup orderGroup, IPayment payment)
        {
            // Implement refund feature logic for current payment gateway
            var captureAmount = payment.Amount;
            var purchaseOrder = orderGroup as IPurchaseOrder;

            if (purchaseOrder == null || captureAmount <= 0)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult("Nothing to capture"));
            }

            var captureRequest = new DoCaptureRequestType
            {
                AuthorizationID = payment.TransactionID,                                               // original transactionID (which PayPal gave us when DoExpressCheckoutPayment, DoDirectPayment, or CheckOut)
                Amount          = _payPalAPIHelper.ToPayPalAmount(captureAmount, orderGroup.Currency), // if refund with Partial, we have to set the Amount
                CompleteType    = payment.Amount >= purchaseOrder.GetTotal().Amount ? CompleteCodeType.COMPLETE : CompleteCodeType.NOTCOMPLETE,
                InvoiceID       = purchaseOrder.OrderNumber
            };

            captureRequest.Note = $"[{payment.PaymentMethodName}-{payment.TransactionID}] captured {captureAmount}{captureRequest.Amount.currencyID} for [PurchaseOrder-{purchaseOrder.OrderNumber}]";

            var caller       = PayPalAPIHelper.GetPayPalAPICallerServices(_paymentMethodConfiguration);
            var doCaptureReq = new DoCaptureReq {
                DoCaptureRequest = captureRequest
            };
            var captureResponse = caller.DoCapture(doCaptureReq);

            var errorCheck = _payPalAPIHelper.CheckErrors(captureResponse);

            if (!string.IsNullOrEmpty(errorCheck))
            {
                _logger.Error(errorCheck);
                return(PaymentProcessingResult.CreateUnsuccessfulResult(PaymentTransactionFailedMessage));
            }

            var captureResponseDetails = captureResponse.DoCaptureResponseDetails;
            var paymentInfo            = captureResponseDetails.PaymentInfo;

            // Extract the response details.
            payment.ProviderTransactionID = paymentInfo.TransactionID;
            payment.Status = paymentInfo.PaymentStatus.ToString();

            var message = $"[{payment.PaymentMethodName}] [Capture payment-{paymentInfo.TransactionID}] [Status: {paymentInfo.PaymentStatus.ToString()}] " +
                          $".Response: {captureResponse.Ack.ToString()} at Timestamp={captureResponse.Timestamp.ToString()}: {paymentInfo.GrossAmount.value}{paymentInfo.GrossAmount.currencyID}";

            // add a new order note about this capture
            AddNoteToPurchaseOrder("CAPTURE", message, purchaseOrder.CustomerId, purchaseOrder);

            _orderRepository.Save(purchaseOrder);

            return(PaymentProcessingResult.CreateSuccessfulResult(message));
        }
Exemple #11
0
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            if (orderGroup == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult("Failed to process your payment."));
            }

            var currentOrder = orderGroup;
            var customer     = _customerService.Service.GetContactViewModelById(currentOrder.CustomerId.ToString());

            if (customer == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult("Failed to process your payment."));
            }

            var isQuoteOrder = currentOrder.Properties[Constant.Quote.ParentOrderGroupId] != null &&
                               Convert.ToInt32(currentOrder.Properties[Constant.Quote.ParentOrderGroupId]) != 0;

            if (isQuoteOrder && customer.Role != B2BUserRoles.Approver)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult("Failed to process your payment."));
            }


            var purchaserCustomer = !isQuoteOrder ? customer : _ordersService.Service.GetPurchaserCustomer(currentOrder);

            if (AreBudgetsOnHold(purchaserCustomer))
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult("Budget on hold."));
            }

            if (customer.Role == B2BUserRoles.Purchaser)
            {
                var budget =
                    _budgetService.Service.GetCustomerCurrentBudget(purchaserCustomer.Organization.OrganizationId,
                                                                    purchaserCustomer.ContactId);
                if (budget == null || budget.RemainingBudget < payment.Amount)
                {
                    return(PaymentProcessingResult.CreateUnsuccessfulResult("Insufficient budget."));
                }
            }


            if (payment.TransactionType == TransactionType.Capture.ToString())
            {
                UpdateUserBudgets(purchaserCustomer, payment.Amount);
                payment.Status = PaymentStatus.Processed.ToString();
                _orderRepository.Service.Save(currentOrder);
            }

            return(PaymentProcessingResult.CreateSuccessfulResult(""));
        }
        /// <summary>
        /// Processes the payment.
        /// </summary>
        /// <param name="orderGroup">The order group.</param>
        /// <param name="payment">The payment.</param>
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            if (HttpContext.Current == null)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult(Utilities.Translate("ProcessPaymentNullHttpContext")));
            }

            if (payment == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PaymentNotSpecified")));
            }

            var orderForm = orderGroup.Forms.FirstOrDefault(f => f.Payments.Contains(payment));

            if (orderForm == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PaymentNotAssociatedOrderForm")));
            }

            var purchaseOrder = orderGroup as IPurchaseOrder;

            if (purchaseOrder != null)
            {
                // When a refund is created by return process,
                // this method will be called again with the TransactionType is Credit
                if (payment.TransactionType.Equals(TransactionType.Credit.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    // process refund
                    // Using Transaction id as DataCash Reference to handle upgrade case.  Assume that before upgrading to this version, our system has some authorized transactions that need to be captured.
                    // After upgrading, using Provider Transaction id instead.
                    return(SendRefundRequest(purchaseOrder, payment));
                }

                // active invoice when order is complete
                // when user click complete order in commerce manager the transaction type will be Capture
                if (payment.TransactionType.Equals(TransactionType.Capture.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    var result  = SendFulfillRequest(purchaseOrder, orderForm, payment);
                    var message = result.Message;

                    if (!result.IsSuccessful && !string.IsNullOrEmpty(result.Message))
                    {
                        _logger.Error(message);
                        message = $"{Utilities.Translate("GenericError")}:{message}";
                    }

                    return(result);
                }
            }

            return(ProcessPaymentCheckout(payment, (ICart)orderGroup));
        }
Exemple #13
0
        public virtual PaymentProcessingResult Refund(
            IOrderGroup orderGroup,
            IPayment payment)
        {
            var configuration = _configurationLoader.GetConfiguration(orderGroup.MarketId);

            try
            {
                var orderId    = payment.TransactionID;
                var serviceApi = _vippsServiceApiFactory.Create(configuration);

                var refundPaymentRequest =
                    _requestFactory.CreateUpdatePaymentRequest(payment, configuration);

                var response = AsyncHelper.RunSync(() => serviceApi.Refund(orderId, refundPaymentRequest));

                var creditTotal = orderGroup.GetFirstForm().Payments.Where(x => x.TransactionType == "Credit")
                                  .Sum(x => x.Amount).FormatAmountToVipps();

                if (response.TransactionSummary.RefundedAmount == creditTotal)
                {
                    OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType,
                                                          $"{payment.Amount} kr refunded on vipps order {orderId}");
                    return(PaymentProcessingResult.CreateSuccessfulResult(
                               $"{payment.Amount} kr captured on refunded order {orderId}"));
                }

                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType,
                                                      $"Vipps refund payment failed. Order status: {response.TransactionInfo.Status}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(
                           $"Vipps refund payment failed. Order status: {response.TransactionInfo.Status}"));
            }

            catch (ApiException apiException)
            {
                var errorMessage = GetErrorMessage(apiException);
                _logger.Log(Level.Error, $"Vipps Refund failed: {errorMessage}");
                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType,
                                                      $"Vipps refund payment failed. Error message: {errorMessage}, {apiException}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(errorMessage));
            }

            catch (Exception ex)
            {
                _logger.Log(Level.Error, $"{ex.Message}, {ex.StackTrace}");
                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType,
                                                      $"Vipps refund payment failed. Error message: {ex.Message}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(ex.Message));
            }
        }
Exemple #14
0
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            payment.TransactionType = TransactionType.Sale.ToString();
            var result = GiftCardService.DebitGiftCard(Settings["GiftCardMetaClassName"], (PrimaryKeyId)orderGroup.CustomerId, payment.ValidationCode, payment.Amount);

            if (result)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult($"Gift Card Applied for {payment.Amount}!"));
            }
            else
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult("Gift Card Declined!"));
            }
        }
Exemple #15
0
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            var creditLimit = 500;

            payment.TransactionType = TransactionType.Sale.ToString();
            if (payment.Amount <= creditLimit)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult($"godkendt betaling for {payment.Amount}, key {Settings["SecretKeyExample"]}"));
            }
            else
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult($"beklager du er over limit!!!!"));
            }
        }
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            decimal CreditLimit = 500;
            string  secretKey   = Settings["SecretKeyExample"];

            payment.TransactionType = TransactionType.Sale.ToString();
            if (payment.Amount <= CreditLimit)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult($"Acme credit approved payment for {payment.Amount}! Secret Code: {secretKey}"));
            }
            else
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult($"Sorry, you are over your limit! Secret Code: {secretKey}"));
            }
        }
        public virtual async Task <PaymentProcessingResult> InitiateAsync(IOrderGroup orderGroup, IPayment payment)
        {
            var orderId = OrderNumberHelper.GenerateOrderNumber();

            orderGroup.Properties[VippsConstants.VippsOrderIdField] = orderId;
            payment.TransactionID = orderId;
            _orderRepository.Save(orderGroup);

            var configuration = _configurationLoader.GetConfiguration(orderGroup.MarketId);

            var serviceApi = _vippsServiceApiFactory.Create(configuration);

            try
            {
                var initiatePaymentRequest =
                    _requestFactory.CreateInitiatePaymentRequest(payment, orderGroup, configuration, orderId, orderGroup.CustomerId, orderGroup.MarketId.Value);

                var response = await serviceApi.Initiate(initiatePaymentRequest).ConfigureAwait(false);

                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType,
                                                      $"Vipps payment initiated. Vipps reference: {initiatePaymentRequest.Transaction.OrderId}");

                _vippsPollingService.Start(new VippsPollingEntity
                {
                    OrderId   = orderId,
                    CartName  = orderGroup.Name,
                    ContactId = orderGroup.CustomerId,
                    MarketId  = orderGroup.MarketId.Value
                });

                return(PaymentProcessingResult.CreateSuccessfulResult("", response.Url));
            }

            catch (ApiException apiException)
            {
                var errorMessage = GetErrorMessage(apiException);
                _logger.Log(Level.Error, $"Vipps initiate failed: {errorMessage}");
                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType, $"Vipps payment initiation failed. Error message: {errorMessage}, {apiException}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(errorMessage));
            }

            catch (Exception ex)
            {
                _logger.Log(Level.Error, $"{ex.Message}, {ex.StackTrace}");
                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType, $"Vipps payment initiation failed. Error message: {ex.Message}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(ex.Message));
            }
        }
Exemple #18
0
        public virtual PaymentProcessingResult Capture(
            IOrderGroup orderGroup,
            IPayment payment)
        {
            var configuration = _configurationLoader.GetConfiguration(orderGroup.MarketId);

            try
            {
                var orderId        = payment.TransactionID;
                var idempotencyKey = GetIdempotencyKey(orderGroup, payment, orderId);
                var serviceApi     = _vippsServiceApiFactory.Create(configuration);

                var capturePaymentRequest =
                    _requestFactory.CreateUpdatePaymentRequest(payment, configuration);

                var response = AsyncHelper.RunSync(() => serviceApi.Capture(orderId, capturePaymentRequest, idempotencyKey));

                if (response.TransactionInfo.Status == VippsUpdatePaymentResponseStatus.Captured.ToString())
                {
                    OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType,
                                                          $"{payment.Amount} kr captured on vipps order {orderId}");
                    return(PaymentProcessingResult.CreateSuccessfulResult(
                               $"{payment.Amount} kr captured on vipps order {orderId}"));
                }

                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType,
                                                      $"Vipps capture payment failed. Order status: {response.TransactionInfo.Status}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(
                           $"Vipps capture payment failed. Order status: {response.TransactionInfo.Status}"));
            }

            catch (ApiException apiException)
            {
                var errorMessage = GetErrorMessage(apiException);
                _logger.Log(Level.Error, $"Vipps Capture failed: {errorMessage}");
                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType,
                                                      $"Vipps capture payment failed. Error message: {errorMessage}, {apiException}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(errorMessage));
            }

            catch (Exception ex)
            {
                _logger.Log(Level.Error, $"{ex.Message}, {ex.StackTrace}");
                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType,
                                                      $"Vipps capture payment failed. Error message: {ex.Message}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(ex.Message));
            }
        }
        /// <summary>
        /// Process payment when a refund request happens.
        /// </summary>
        /// <remarks>
        /// <para>
        /// See API doc here https://www.x.com/developers/paypal/documentation-tools/api/refundtransaction-api-operation-soap
        /// </para>
        /// <para>
        /// You may offer a refund only for a limited time, usually 60 days. If you need to make a refund after that time, you will need to initiate a new PayPal payment to your buyer.
        /// If you offer the buyer a partial refund, she has 10 days to decline it if she wishes. (Full refunds are automatically processed.)
        /// </para>
        /// </remarks>
        /// <param name="payment">The payment to process.</param>
        /// <param name="orderGroup">The order group to process.</param>
        /// <returns>True if refund was completed, otherwise false and set the message will make the WorkFlow activity raise PaymentExcetion(message).</returns>
        private PaymentProcessingResult ProcessPaymentRefund(IOrderGroup orderGroup, IPayment payment)
        {
            // Implement refund feature logic for current payment gateway
            var refundAmount  = payment.Amount;
            var purchaseOrder = (orderGroup as IPurchaseOrder);

            if (purchaseOrder == null || refundAmount <= 0)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PayPalRefundError")));
            }

            // Call payment gateway API to do refund business
            // Create the Refund Request
            var refundRequest = new RefundTransactionRequestType
            {
                TransactionID = payment.ProviderTransactionID, // original transactionID (which payPal gave us when do ExpressCheckout)
                Memo          = $"[{payment.PaymentMethodName}-{payment.TransactionID}] refunds {refundAmount}{purchaseOrder.Currency} for [PurchaseOrder-{purchaseOrder.OrderNumber}]",
                // NOTE: If RefundType is Full, do not set the amount.
                // refundRequest.RefundType = RefundType.Full; //refund a full or partial amount
                RefundType = RefundType.PARTIAL,                                                //refund a partial amount
                Amount     = _payPalAPIHelper.ToPayPalAmount(refundAmount, orderGroup.Currency) // if refund with Partial, we have to set the Amount
            };

            var caller         = PayPalAPIHelper.GetPayPalAPICallerServices(_paymentMethodConfiguration);
            var refundResponse = caller.RefundTransaction(new RefundTransactionReq {
                RefundTransactionRequest = refundRequest
            });
            var errorCheck = _payPalAPIHelper.CheckErrors(refundResponse);

            if (!string.IsNullOrEmpty(errorCheck))
            {
                _logger.Error(errorCheck);
                return(PaymentProcessingResult.CreateUnsuccessfulResult(PaymentTransactionFailedMessage));
            }

            // Extract the response details.
            payment.TransactionID = refundResponse.RefundTransactionID;

            var message = $"[{payment.PaymentMethodName}] [RefundTransaction-{refundResponse.RefundTransactionID}] " +
                          $"Response: {refundResponse.Ack.ToString()} at Timestamp={refundResponse.Timestamp.ToString()}: {refundResponse.GrossRefundAmount.value}{refundResponse.GrossRefundAmount.currencyID}";

            // add a new order note about this refund
            AddNoteToPurchaseOrder("REFUND", message, purchaseOrder.CustomerId, purchaseOrder);

            _orderRepository.Save(purchaseOrder);

            return(PaymentProcessingResult.CreateSuccessfulResult(message));
        }
Exemple #20
0
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            if (!(payment is ICreditCardPayment creditCardPayment))
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate("PaymentNotSpecified")));
            }

            var billingAddress = creditCardPayment.BillingAddress;

            if (billingAddress == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate("PaymentNotSpecified")));
            }

            if (string.IsNullOrEmpty(billingAddress.Email))
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate("PaymentNotSpecified")));
            }

            if (_orderTaxTotal == 0)
            {
                _orderTaxTotal = _taxCalculator.Service.GetTaxTotal(orderGroup, orderGroup.Market, orderGroup.Currency).Amount;
            }

            if (orderGroup is ICart cart)
            {
                return(Charge(cart, creditCardPayment, billingAddress));
            }
            // the order which is created by Commerce Manager
            if (!(orderGroup is IPurchaseOrder))
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate("UnsupportedPaymentType") + $".  {orderGroup.GetType().AssemblyQualifiedName}"));
            }

            if (payment.TransactionType == TransactionType.Capture.ToString())
            {
                return(ProcessPaymentCapture(orderGroup, creditCardPayment, billingAddress));
            }

            // When "Refund" shipment in Commerce Manager, this method will be invoked with the TransactionType is Credit
            return(payment.TransactionType == TransactionType.Credit.ToString() ?
                   ProcessPaymentRefund(orderGroup, creditCardPayment) :
                   PaymentProcessingResult.CreateUnsuccessfulResult(Translate("UnsupportedPaymentType") + $".  {orderGroup.GetType().AssemblyQualifiedName}"));
        }
Exemple #21
0
        private PaymentProcessingResult ProcessPaymentRefund(IOrderGroup orderGroup, ICreditCardPayment creditCardPayment)
        {
            var refundAmount  = creditCardPayment.Amount;
            var purchaseOrder = (IPurchaseOrder)orderGroup;

            if (purchaseOrder == null || refundAmount <= 0 || string.IsNullOrEmpty(creditCardPayment.ProviderPaymentId))
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate("RefundError")));
            }

            try
            {
                var refundOptions = new StripeRefundCreateOptions()
                {
                    Amount = (int)refundAmount * GetMultiplier(orderGroup.Currency),
                    Reason = StripeRefundReasons.RequestedByCustomer
                };

                var refund = _stripeRefundService.Create(creditCardPayment.ProviderPaymentId, refundOptions);
                // Extract the response details.
                creditCardPayment.TransactionID = refund.Id;

                var message = $"[{creditCardPayment.PaymentMethodName}] [RefundTransaction-{refund.Id}] " +
                              $"Response: {refund.Status} at Timestamp={refund.Created.ToString()}: {refund.Amount}{refund.Currency}";

                // add a new order note about this refund
                AddNoteToPurchaseOrder("REFUND", message, purchaseOrder.CustomerId, purchaseOrder);

                _orderRepository.Service.Save(purchaseOrder);

                return(PaymentProcessingResult.CreateSuccessfulResult(message));
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(e.StripeError.Code)));

                default:
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(e.StripeError.Message));
                }
            }
        }
        /// <summary>
        /// Processes the payment.
        /// </summary>
        /// <param name="orderGroup">The order group.</param>
        /// <param name="payment">The payment.</param>
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            if (HttpContext.Current == null)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult("ProcessPaymentNullHttpContext"));
            }

            if (payment == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult("PaymentNotSpecified"));
            }

            var orderForm = orderGroup.Forms.FirstOrDefault(f => f.Payments.Contains(payment));

            if (orderForm == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult("PaymentNotAssociatedOrderForm"));
            }

            _paymentMethodConfiguration = new PayooConfiguration(Settings);

            var payooOrder = CreatePayooOrder(orderGroup, payment);
            var checksum   = CreatePayooChecksum(payooOrder);
            //Call Payoo gateway here
            var message  = string.Empty;
            var response = ExecuteCreatePayooPreOrderRequest(payooOrder, checksum, out message);

            if (response == null || !response.IsSuccess)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(message));
            }

            UpdatePaymentPropertiesFromPayooResponse(orderGroup, payment, response);

            var redirectUrl = response.order.payment_url;

            message = $"---Payoo CreatePreOrder is successful. Redirect end user to {redirectUrl}";
            return(PaymentProcessingResult.CreateSuccessfulResult(message, redirectUrl));
        }
        public virtual PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            PaymentStepResult stepResult;

            try
            {
                Logger.Debug("Netaxept checkout gateway. Processing Payment ....");

                if (_orderForm == null)
                {
                    _orderForm = orderGroup.Forms.FirstOrDefault(form => form.Payments.Contains(payment));
                }

                var registerPaymentStep = new RegisterPaymentStep(payment);
                var capturePaymentStep  = new CapturePaymentStep(payment);
                var creditPaymentStep   = new CreditPaymentStep(payment);
                var annulPaymentStep    = new AnnulPaymentStep(payment);

                registerPaymentStep.SetSuccessor(capturePaymentStep);
                capturePaymentStep.SetSuccessor(creditPaymentStep);
                creditPaymentStep.SetSuccessor(annulPaymentStep);

                stepResult = registerPaymentStep.Process(payment, _orderForm, orderGroup);
            }
            catch (Exception exception)
            {
                Logger.Error("Process payment failed with error: " + exception.Message, exception);
                stepResult = new PaymentStepResult {
                    IsSuccessful = false, Message = exception.Message
                };
            }

            if (stepResult.IsSuccessful)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult(stepResult.Message, stepResult.RedirectUrl));
            }

            return(PaymentProcessingResult.CreateUnsuccessfulResult(stepResult.Message));
        }
        public virtual async Task <PaymentProcessingResult> CancelAsync(IOrderGroup orderGroup, IPayment payment)
        {
            var configuration = _configurationLoader.GetConfiguration(orderGroup.MarketId);

            try
            {
                var orderId    = payment.TransactionID;
                var serviceApi = _vippsServiceApiFactory.Create(configuration);

                var cancelPaymentRequest =
                    _requestFactory.CreateUpdatePaymentRequest(payment, configuration);

                var response = await serviceApi.Cancel(orderId, cancelPaymentRequest).ConfigureAwait(false);

                if (response.TransactionInfo.Status == VippsUpdatePaymentResponseStatus.Cancelled.ToString())
                {
                    OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType, $"Payment cancelled for vipps order {orderId}");
                    return(PaymentProcessingResult.CreateSuccessfulResult($"{payment.Amount} Payment cancelled vipps order {orderId}"));
                }

                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType, $"Vipps cancel payment failed. Order status: {response.TransactionInfo.Status}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult($"Vipps cancel payment failed. Order status: {response.TransactionInfo.Status}"));
            }

            catch (ApiException apiException)
            {
                var errorMessage = GetErrorMessage(apiException);
                _logger.Log(Level.Error, $"Vipps cancel failed: {errorMessage}");
                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType, $"Vipps cancel payment failed. Error message: {errorMessage}, {apiException}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(errorMessage));
            }

            catch (Exception ex)
            {
                _logger.Log(Level.Error, $"{ex.Message}, {ex.StackTrace}");
                OrderNoteHelper.AddNoteAndSaveChanges(orderGroup, payment, payment.TransactionType, $"Vipps cancel payment failed. Error message: {ex.Message}");
                return(PaymentProcessingResult.CreateUnsuccessfulResult(ex.Message));
            }
        }
        private PaymentProcessingResult PreAuthenticateRequest(IOrderGroup orderGroup, IOrderForm orderForm, IPayment payment, out string authenticateCode)
        {
            authenticateCode = string.Empty;
            try
            {
                var requestDoc  = _requestDocumentCreation.CreateDocumentForPreAuthenticateRequest(payment, orderForm, orderGroup.Currency);
                var responseDoc = DocumentHelpers.SendTransaction(requestDoc, _dataCashConfiguration.Config);
                if (DocumentHelpers.IsSuccessful(responseDoc))
                {
                    authenticateCode = responseDoc.get("Response.CardTxn.authcode");
                    return(string.IsNullOrEmpty(authenticateCode) ?
                           PaymentProcessingResult.CreateUnsuccessfulResult(string.Empty) :
                           PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
                }

                return(PaymentProcessingResult.CreateUnsuccessfulResult(DocumentHelpers.GetErrorMessage(responseDoc)));
            }
            catch (System.Exception e)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(e.Message));
            }
        }
Exemple #26
0
        /// <summary>
        /// Processes the payment.
        /// </summary>
        /// <param name="orderGroup">The order group.</param>
        /// <param name="payment">The payment.</param>
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            // checks
            if (HttpContext.Current == null)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult(Utilities.Translate("ProcessPaymentNullHttpContext")));
            }

            if (payment == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PaymentNotSpecified")));
            }

            var orderForm = orderGroup.Forms.FirstOrDefault(f => f.Payments.Contains(payment));

            if (orderForm == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PaymentNotAssociatedOrderForm")));
            }

            // todo: not needed...
            // bool isRegularTransaction = IsRegularTransaction(orderGroup);

            // its a purchase order
            var purchaseOrder = orderGroup as IPurchaseOrder;

            if (purchaseOrder != null)
            {
                if (payment.TransactionType == TransactionType.Capture.ToString())
                {
                    // return true meaning the capture request is done by epay
                    var result = _epayRequestHelper.PostCaptureRequest(payment, purchaseOrder);
                    if (result.Equals(false))
                    {
                        return(PaymentProcessingResult.CreateUnsuccessfulResult("There was an error while capturing payment with Epay"));
                    }

                    return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
                }

                //todo: add credit
                if (payment.TransactionType == TransactionType.Credit.ToString())
                {
                    //return PaymentProcessingResult.CreateUnsuccessfulResult("The current payment method credit does not support this order type.");

                    var transactionID = payment.TransactionID;
                    if (string.IsNullOrEmpty(transactionID) || transactionID.Equals("0"))
                    {
                        return(PaymentProcessingResult.CreateUnsuccessfulResult("TransactionID is not valid or the current payment method does not support this order type."));
                    }

                    // The transact must be captured before refunding
                    string message = string.Empty;
                    if (_epayRequestHelper.PostRefundRequest(payment, purchaseOrder, ref message))
                    {
                        return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
                    }
                    return(PaymentProcessingResult.CreateUnsuccessfulResult($"There was an error while refunding with epay. {message}"));
                }

                // right now we do not support processing the order which is created by Commerce Manager
                return(PaymentProcessingResult.CreateUnsuccessfulResult("The current payment method does not support this order type."));
            }

            var cart = orderGroup as ICart;

            if (cart != null && cart.OrderStatus == OrderStatus.Completed)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
            }
            _orderRepository.Save(orderGroup);

            var redirectUrl = Utilities.GetUrlFromStartPageReferenceProperty("EpayPaymentPage");

            return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty, redirectUrl));
        }
Exemple #27
0
        private PaymentProcessingResult Charge(IOrderGroup cart,
                                               ICreditCardPayment creditCardPayment,
                                               IOrderAddress billingAddress)
        {
            var            contact        = CustomerContext.Current.GetContactById(cart.CustomerId);
            StripeCustomer stripeCustomer = null;

            try
            {
                if (contact != null)
                {
                    if (!string.IsNullOrEmpty(contact?["StripeId"]?.ToString()))
                    {
                        stripeCustomer = _stripeCustomerService.Get(contact["StripeId"].ToString());
                    }

                    if (stripeCustomer == null)
                    {
                        stripeCustomer = _stripeCustomerService.Create(new StripeCustomerCreateOptions
                        {
                            Email       = contact.Email,
                            SourceToken = creditCardPayment.CreditCardNumber
                        });

                        contact["StripeId"] = stripeCustomer.Id;
                        contact.SaveChanges();
                    }
                }

                Enum.TryParse(creditCardPayment.TransactionType, out TransactionType transactionType);
                var options = new StripeChargeCreateOptions
                {
                    Amount      = (int)creditCardPayment.Amount * GetMultiplier(cart.Currency),
                    Description = "Ecommerce Charge",
                    Currency    = cart.Currency.ToString().ToLower(),
                    Capture     = transactionType == TransactionType.Capture ||
                                  transactionType == TransactionType.CaptureOnly
                };

                if (stripeCustomer != null)
                {
                    options.CustomerId = stripeCustomer.Id;
                }
                else
                {
                    options.SourceTokenOrExistingSourceId = creditCardPayment.CreditCardNumber;
                }

                var charge = _stripeChargeService.Create(options);

                if (!string.IsNullOrEmpty(charge.FailureCode))
                {
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(charge.Outcome.Reason)));
                }
                creditCardPayment.ProviderPaymentId               = charge.Id;
                creditCardPayment.ProviderTransactionID           = charge.BalanceTransactionId;
                creditCardPayment.Properties["stripe_CustomerId"] = stripeCustomer?.Id;
                return(PaymentProcessingResult.CreateSuccessfulResult(""));
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(e.StripeError.Code)));

                default:
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(e.StripeError.Message));
                }
            }
        }
        public void PlaceOrder_WhenProcessingPaymentNotSuccess_ShouldReturnNullAndAddModelError()
        {
            var cartTotal = new Money(1, Currency.USD);

            _orderGroupCalculatorMock.Setup(x => x.GetTotal(It.IsAny <IOrderGroup>())).Returns(() => cartTotal);

            _orderRepositoryMock.Setup(x => x.Load <IPurchaseOrder>(It.IsAny <int>())).Returns(new Mock <IPurchaseOrder>().Object);

            _orderRepositoryMock.Setup(x => x.SaveAsPurchaseOrder(It.IsAny <ICart>()))
            .Returns(() => new OrderReference(0, "", Guid.Empty, null));

            var cart = new FakeCart(new MarketImpl(MarketId.Empty), Currency.SEK)
            {
                OrderLink = new OrderReference(1, "", Guid.Empty, null)
            };

            cart.GetFirstForm().Payments.Add(new FakePayment {
                Status = PaymentStatus.Processed.ToString(), Amount = cartTotal.Amount
            });

            var modelState = new ModelStateDictionary();

            var viewModel = new CheckoutViewModel
            {
                BillingAddress = new AddressModel {
                    AddressId = "billingAddress"
                },
                Payment = new Mock <CashOnDeliveryPaymentOption>(null, null, null, null, null).Object
            };

            _paymentProcessorMock.Setup(x => x.ProcessPayment(It.IsAny <IOrderGroup>(), It.IsAny <IPayment>(), It.IsAny <IShipment>()))
            .Returns((IOrderGroup orderGroup, IPayment payment, IShipment shipment) => PaymentProcessingResult.CreateUnsuccessfulResult("Payment was failed."));

            var result = _subject.PlaceOrder(cart, modelState, viewModel);

            Assert.Null(result);
            Assert.Equal(1, modelState.Count(x => x.Value.Errors.Count > 0));
        }
Exemple #29
0
        /// <summary>
        /// Processes the payment.
        /// </summary>
        /// <param name="orderGroup">The order group.</param>
        /// <param name="payment">The payment.</param>
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            if (HttpContext.Current == null)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult(Utilities.Translate("ProcessPaymentNullHttpContext")));
            }

            if (payment == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PaymentNotSpecified")));
            }

            var orderForm = orderGroup.Forms.FirstOrDefault(f => f.Payments.Contains(payment));

            if (orderForm == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PaymentNotAssociatedOrderForm")));
            }

            var purchaseOrder = orderGroup as IPurchaseOrder;

            if (purchaseOrder != null)
            {
                if (payment.TransactionType == TransactionType.Capture.ToString())
                {
                    // return true meaning the capture request is done,
                    // actual capturing must be done on DIBS.
                    var result = _dibsRequestHelper.PostCaptureRequest(payment, purchaseOrder);
                    var status = result["status"];
                    if (status == "ACCEPT")
                    {
                        return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
                    }

                    return(PaymentProcessingResult.CreateUnsuccessfulResult(
                               $@"There was an error while capturing payment with DIBS.
                        status: {status}
                        declineReason: {result["declineReason"]}"));
                }

                if (payment.TransactionType == TransactionType.Credit.ToString())
                {
                    var transactionID = payment.TransactionID;
                    if (string.IsNullOrEmpty(transactionID) || transactionID.Equals("0"))
                    {
                        return(PaymentProcessingResult.CreateUnsuccessfulResult("TransactionID is not valid or the current payment method does not support this order type."));
                    }
                    // The transact must be captured before refunding
                    var result = _dibsRequestHelper.PostRefundRequest(payment, purchaseOrder);
                    var status = result["status"];
                    if (status == "ACCEPT")
                    {
                        return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
                    }

                    return(PaymentProcessingResult.CreateUnsuccessfulResult(
                               $@"There was an error while capturing payment with DIBS.
                        status: {status}
                        declineReason: {result["declineReason"]}"));
                }

                // right now we do not support processing the order which is created by Commerce Manager
                return(PaymentProcessingResult.CreateUnsuccessfulResult("The current payment method does not support this order type."));
            }

            var cart = orderGroup as ICart;

            if (cart != null && cart.OrderStatus == OrderStatus.Completed)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
            }
            _orderRepository.Save(orderGroup);

            var redirectUrl = Utilities.GetUrlFromStartPageReferenceProperty("DIBSPaymentPage");

            return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty, redirectUrl));
        }
Exemple #30
0
        /// <summary>
        /// Processes the payment.
        /// </summary>
        /// <param name="orderGroup">The order group.</param>
        /// <param name="payment">The payment.</param>
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            if (HttpContext.Current == null)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult("Http context is null."));
            }

            if (payment == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult("Payment was not specified."));
            }

            var orderForm = orderGroup.Forms.FirstOrDefault(f => f.Payments.Contains(payment));

            if (orderForm == null)
            {
                return(PaymentProcessingResult.CreateUnsuccessfulResult(
                           "There is no order form associated with payment."));
            }

            if (orderGroup is IPurchaseOrder purchaseOrder)
            {
                if (payment.TransactionType == TransactionType.Capture.ToString())
                {
                    // return true meaning the capture request is done,
                    // actual capturing must be done on Dintero.
                    var transaction = _requestsHelper.GetTransactionDetails(payment.TransactionID, _requestsHelper.GetAccessToken());
                    var skipItems   = payment.Amount != 0 && payment.Amount < purchaseOrder.GetTotal().Amount&& !string.IsNullOrEmpty(transaction.PaymentProduct) &&
                                      !transaction.PaymentProduct.Equals("instabank", StringComparison.InvariantCultureIgnoreCase);
                    var result = payment.Amount == 0? new TransactionResult {
                        Success = true
                    } : _requestsHelper.CaptureTransaction(payment, purchaseOrder, skipItems);
                    if (result.Success)
                    {
                        return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
                    }

                    PostProcessPayment.PostCapture(result, payment);

                    return(PaymentProcessingResult.CreateUnsuccessfulResult(
                               $@"There was an error while capturing payment with Dintero:
                           code: {
                                result.ErrorCode
                            };
                           declineReason: {
                                result.Error
                            }"));
                }

                if (payment.TransactionType == TransactionType.Void.ToString())
                {
                    var result = payment.Amount == 0 ? new TransactionResult {
                        Success = true
                    } : _requestsHelper.VoidTransaction(payment);
                    if (result.Success)
                    {
                        return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
                    }

                    return(PaymentProcessingResult.CreateUnsuccessfulResult(
                               $@"There was an error while voiding payment with Dintero:
                           code: {
                                result.ErrorCode
                            };
                           declineReason: {
                                result.Error
                            }"));
                }

                if (payment.TransactionType == TransactionType.Credit.ToString())
                {
                    if (!(purchaseOrder is PurchaseOrder refundOrder))
                    {
                        return(PaymentProcessingResult.CreateUnsuccessfulResult("Order has invalid type."));
                    }

                    var transactionId = payment.TransactionID;
                    if (string.IsNullOrEmpty(transactionId) || transactionId.Equals("0"))
                    {
                        return(PaymentProcessingResult.CreateUnsuccessfulResult(
                                   "TransactionID is not valid or the current payment method does not support this order type."));
                    }

                    var returnForms = refundOrder.ReturnOrderForms.Where(rt =>
                                                                         rt.Status == ReturnFormStatus.Complete.ToString() && rt.Total == payment.Amount).ToList();

                    if (!returnForms.Any())
                    {
                        return(PaymentProcessingResult.CreateUnsuccessfulResult("No items found for refunding."));
                    }

                    var result = payment.Amount == 0 ? new TransactionResult {
                        Success = true
                    } : _requestsHelper.RefundTransaction(payment, returnForms, purchaseOrder.Currency);
                    if (result.Success)
                    {
                        return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
                    }

                    PostProcessPayment.PostCredit(result, payment);

                    return(PaymentProcessingResult.CreateUnsuccessfulResult(
                               $@"There was an error while refunding payment with Dintero: code: { result.ErrorCode }; declineReason: { result.Error }"));
                }

                // right now we do not support processing the order which is created by Commerce Manager
                return(PaymentProcessingResult.CreateUnsuccessfulResult(
                           "The current payment method does not support this order type."));
            }

            if (orderGroup is ICart cart && cart.OrderStatus == OrderStatus.Completed)
            {
                return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
            }

            _orderRepository.Save(orderGroup);

            var redirectUrl = UriUtil.GetUrlFromStartPageReferenceProperty("DinteroPaymentPage");

            return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty, redirectUrl));
        }