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));
            }
        }
        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));
            }
        }
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            if (payment.TransactionType != TransactionType.Authorization.ToString() ||
                payment.Status != PaymentStatus.Pending.ToString())
            {
                return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
            }

            var settings = ServiceLocator.Current.GetInstance <IVerifoneSettings>();

            if (settings == null)
            {
                throw new ArgumentException($"Configure a default instance for {nameof(IVerifoneSettings)}", nameof(settings));
            }

            var urlResolver = ServiceLocator.Current.GetInstance <UrlResolver>();
            var redirectUrl = urlResolver.GetUrl(settings.PaymentRedirectPage);

            if (!string.IsNullOrEmpty(settings.PaymentRedirectAction))
            {
                redirectUrl  = VirtualPathUtility.AppendTrailingSlash(redirectUrl);
                redirectUrl += settings.PaymentRedirectAction;
            }

            return(PaymentProcessingResult.CreateSuccessfulResult("Redirection is required", redirectUrl));
        }
示例#4
0
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            var message     = "message";
            var redirectUrl = CreateRedirectUrl(orderGroup);

            return(PaymentProcessingResult.CreateSuccessfulResult(message, redirectUrl));
        }
示例#5
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));
        }
示例#7
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));
                }
            }
        }
示例#8
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."));
        }
 private IHttpActionResult GetSuccessfulResult(PaymentProcessingResult paymentProcessingResult)
 {
     return(Ok(new ExpressCheckoutResponse
     {
         Success = paymentProcessingResult.IsSuccessful,
         ErrorMessage = paymentProcessingResult.Message,
         RedirectUrl = paymentProcessingResult.RedirectUrl
     }));
 }
示例#10
0
        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));
        }
示例#12
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>
        /// 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));
        }
示例#14
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>
        /// 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));
        }
示例#16
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));
            }
        }
示例#17
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!"));
            }
        }
示例#18
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));
            }
        }
        /// <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));
        }
示例#22
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));
            }
        }
        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 authorizationPaymentStep = new AuthorizationPaymentStep(payment);
                var capturePaymentStep       = new CapturePaymentStep(payment);
                var creditPaymentStep        = new CreditPaymentStep(payment);
                var annulPaymentStep         = new AnnulPaymentStep(payment);

                registerPaymentStep.SetSuccessor(authorizationPaymentStep);
                authorizationPaymentStep.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));
            }

            // COM-10168 Payment: bug in Commerce 12 but fixed in Commerce 13.13. The unsuccessfull result is ignored by Episerver and payment is set to processed. When package
            // is made compatible for Commerce 13 this code can be removed and the commented out code can be restored.
            // return PaymentProcessingResult.CreateUnsuccessfulResult(stepResult.Message);

            throw new PaymentException(PaymentException.ErrorType.ProviderError, string.Empty, stepResult.Message);
        }
示例#24
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));
                }
            }
        }
示例#25
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}"));
        }
示例#26
0
        public ActionResult SimulatePurchase(PaymentDemoViewModel viewModel)
        {
            var cart = _orderRepository.LoadOrCreateCart <ICart>(CustomerContext.Current.CurrentContactId, "Default");

            cart.GetFirstShipment().ShippingMethodId = viewModel.SelectedShippingMethodId;

            var primaryPayment = _orderGroupFactory.CreatePayment(cart);

            primaryPayment.PaymentMethodId   = viewModel.SelectedPaymentId;
            primaryPayment.Amount            = _orderGroupCalculator.GetTotal(cart).Amount;
            primaryPayment.PaymentMethodName = PaymentManager.GetPaymentMethod(viewModel.SelectedPaymentId).PaymentMethod[0].Name;

            if (viewModel.UseGiftCard)
            {
                var giftMethod  = PaymentManager.GetPaymentMethodBySystemName("GiftCard", ContentLanguage.PreferredCulture.Name);
                var giftPayment = _orderGroupFactory.CreatePayment(cart);
                giftPayment.PaymentMethodId   = giftMethod.PaymentMethod[0].PaymentMethodId;
                giftPayment.Amount            = viewModel.GiftCardDebitAmt;
                giftPayment.ValidationCode    = viewModel.RedemtionCode;
                giftPayment.PaymentMethodName = giftMethod.PaymentMethod[0].Name;

                PaymentProcessingResult giftPayResult = _paymentProcessor.ProcessPayment(cart, giftPayment, cart.GetFirstShipment());
                if (giftPayResult.IsSuccessful)
                {
                    primaryPayment.Amount -= giftPayment.Amount;
                    cart.AddPayment(giftPayment);
                }
                viewModel.GiftInfoMessage = giftPayResult.Message;
            }

            PaymentProcessingResult payResult = _paymentProcessor.ProcessPayment(cart, primaryPayment, cart.GetFirstShipment());

            if (payResult.IsSuccessful)
            {
                cart.AddPayment(primaryPayment);
                _orderRepository.SaveAsPurchaseOrder(cart);
                _orderRepository.Delete(cart.OrderLink);
            }
            viewModel.MessageOutput = payResult.Message;

            InitializeModel(viewModel);

            return(View("Index", viewModel));
        }
        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));
            }
        }
        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));
        }
        /// <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 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));
            }
        }