/// <summary> /// When an order needs to be captured the cartridge needs to make an API Call /// POST /ordermanagement/v1/orders/{order_id}/captures for the amount which needs to be captured. /// If it's a partial capture the API call will be the same just for the /// amount that should be captured. Many captures can be made up to the whole amount authorized. /// The shipment information can be added in this call or amended aftewards using the method /// "Add shipping info to a capture". /// The amount captured never can be greater than the authorized. /// When an order is Partally Captured the status of the order in Klarna is PART_CAPTURED /// </summary> public override bool Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment, ref string message) { if (payment.TransactionType == TransactionType.Capture.ToString()) { var amount = AmountHelper.GetAmount(payment.Amount); var orderId = orderGroup.Properties[Common.Constants.KlarnaOrderIdField]?.ToString(); if (!string.IsNullOrEmpty(orderId)) { try { var captureData = KlarnaOrderService.CaptureOrder(orderId, amount, "Capture the payment", orderGroup, orderForm, payment, shipment); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Captured {payment.Amount}, id {captureData.CaptureId}"); } catch (Exception ex) when(ex is ApiException || ex is WebException) { var exceptionMessage = GetExceptionMessage(ex); payment.Status = PaymentStatus.Failed.ToString(); message = exceptionMessage; AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}"); Logger.Error(exceptionMessage, ex); return(false); } } return(true); } else if (Successor != null) { return(Successor.Process(payment, orderForm, orderGroup, shipment, ref message)); } return(false); }
public void CleanOutPayments(ICart cart) { Dictionary <int, IPayment> payments = new Dictionary <int, IPayment>(); foreach (var cartForm in cart.Forms) { foreach (var payment in cartForm.Payments) { payments.Add(cartForm.OrderFormId, payment); } } if (payments.Count >= 1) { var ofp = cart.Forms.GroupBy(f => f.OrderFormId, f => f.Payments); foreach (var item in ofp) { IOrderForm f = cart.Forms.Where(x => x.OrderFormId == item.Key).First(); foreach (var item2 in f.Payments) { f.Payments.Remove(item2); } } } }
public override bool Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment, ref string message) { if (payment.TransactionType == TransactionType.Void.ToString()) { try { var orderId = orderGroup.Properties[Common.Constants.KlarnaOrderIdField]?.ToString(); if (!string.IsNullOrEmpty(orderId)) { KlarnaOrderService.CancelOrder(orderId); payment.Status = PaymentStatus.Processed.ToString(); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Order cancelled at Klarna"); return(true); } } catch (Exception ex) when(ex is ApiException || ex is WebException) { var exceptionMessage = GetExceptionMessage(ex); payment.Status = PaymentStatus.Failed.ToString(); message = exceptionMessage; AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}"); Logger.Error(exceptionMessage, ex); return(false); } } else if (Successor != null) { return(Successor.Process(payment, orderForm, orderGroup, shipment, ref message)); } return(false); }
protected override RewardDescription Evaluate( Free2 promotionData , PromotionProcessorContext context) { // RequiredQty & FreeItem in the model IOrderForm orderForm = context.OrderGroup.GetFirstForm(); IEnumerable <ILineItem> lineItems = context.OrderGroup.GetFirstForm().GetAllLineItems(); ContentReference freeItem = promotionData.FreeItem.Items.First(); // Using "First()" just to show string freeItemCode = _referenceConverter.GetCode(freeItem); FulfillmentStatus status = promotionData.RequiredQty.GetFulfillmentStatus( orderForm, _collectionTargetEvaluator, _fulfillmentEvaluator); IList <string> applicableEntryCodes = _collectionTargetEvaluator.GetApplicableCodes( lineItems, promotionData.RequiredQty.Items, false); string description = promotionData.Description; return(RewardDescription.CreateFreeItemReward( status , GetRedemptionDescriptions(promotionData, context, applicableEntryCodes) , promotionData , description + " : " + freeItemCode)); // description, just to show }
/// <summary> /// Process register payment step /// </summary> /// <param name="payment"></param> /// <param name="orderForm"></param> /// <param name="orderGroup"></param> /// <param name="message"></param> /// <returns></returns> public override PaymentStepResult Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup) { var paymentMethodDto = PaymentManager.GetPaymentMethod(payment.PaymentMethodId); if (payment.TransactionType == TransactionType.Authorization.ToString() && string.IsNullOrEmpty(payment.ProviderTransactionID)) { var transactionId = ""; try { transactionId = this.Client.Register(CreatePaymentRequest(paymentMethodDto, payment, orderForm, orderGroup)); } catch (Exception ex) { Logger.Error(ex.Message); AddNoteAndSaveChanges(orderGroup, "Payment Registered - Error", "Payment Registered - Error: " + ex.Message); return(Fail(ex.Message)); } payment.ProviderTransactionID = transactionId; AddNoteAndSaveChanges(orderGroup, "Payment - Registered", $"Payment - Registered with transactionId {transactionId}"); var isProduction = bool.Parse(paymentMethodDto.GetParameter(NetaxeptConstants.IsProductionField, "false")); var merchantId = paymentMethodDto.GetParameter(NetaxeptConstants.MerchantIdField); var redirectUrl = TerminalHelper.GetRedirectUrl(merchantId, transactionId, isProduction); return(Success(redirectUrl)); } else if (Successor != null) { return(Successor.Process(payment, orderForm, orderGroup)); } return(Fail(null)); }
private static IOrderForm GetCurrentReturnForm(IEnumerable<IOrderForm> returnForms, DinteroTransactionActionResponse transaction) { IOrderForm returnForm = null; if (returnForms != null) { var forms = returnForms.ToList(); if (forms.Count == 1) { returnForm = forms.First(); } else { var refunds = transaction.Events.Where(e => e.Success && e.Event == "REFUND").ToList(); foreach (var form in forms) { if (!refunds.Any(refund => HaveEqualLineItems(refund.Items, form.GetAllLineItems().ToList()))) { returnForm = form; break; } } } } return returnForm; }
public void Handle(OrderCancelledEvent ev) { _order = ev.PurchaseOrder; _orderForm = _order.GetFirstForm(); if (AlreadyVoided()) { return; } var previousPayment = _orderForm.Payments.FirstOrDefault(x => x.IsKlarnaPayment()); if (previousPayment == null) { return; } var voidPayment = _order.CreatePayment(_orderGroupFactory); voidPayment.PaymentType = previousPayment.PaymentType; voidPayment.PaymentMethodId = previousPayment.PaymentMethodId; voidPayment.PaymentMethodName = previousPayment.PaymentMethodName; voidPayment.Amount = previousPayment.Amount; voidPayment.Status = PaymentStatus.Pending.ToString(); voidPayment.TransactionType = TransactionType.Void.ToString(); _order.AddPayment(voidPayment); _paymentProcessor.ProcessPayment(_order, voidPayment, _order.GetFirstShipment()); }
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)); } }
/// <summary> /// Process /// </summary> /// <param name="payment"></param> /// <param name="message"></param> /// <returns></returns> public override PaymentStepResult Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup) { if (payment.TransactionType == "Void") { try { var result = this.Client.Annul(payment.TransactionID); if (result.ErrorOccurred) { payment.Status = "Failed"; AddNoteAndSaveChanges(orderGroup, "Payment Annul - Error", "Payment Annul - Error: " + result.ErrorMessage); return(Fail(result.ErrorMessage)); } } catch (Exception ex) { Logger.Error(ex.Message); payment.Status = "Failed"; AddNoteAndSaveChanges(orderGroup, "Payment Annul - Error", "Payment Annul - Error: " + ex.Message); return(Fail(ex.Message)); } AddNoteAndSaveChanges(orderGroup, "Payment - Annul", "Payment - Annulled"); return(Success()); } else if (Successor != null) { return(Successor.Process(payment, orderForm, orderGroup)); } return(Fail(null)); }
/// <summary> /// Process /// </summary> /// <param name="payment"></param> /// <param name="orderGroup"></param> /// <param name="message"></param> /// <param name="orderForm"></param> /// <returns></returns> public override PaymentStepResult Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup) { if (payment.TransactionType == TransactionType.Capture.ToString()) { var amount = PaymentStepHelper.GetAmount(payment.Amount); try { var result = this.Client.Capture(payment.TransactionID, amount); if (result.ErrorOccurred) { payment.Status = PaymentStatus.Failed.ToString(); AddNoteAndSaveChanges(orderGroup, "Payment Captured - Error", "Payment - Captured - Error: " + result.ErrorMessage); return(Fail(result.ErrorMessage)); } } catch (Exception ex) { Logger.Error(ex.Message); payment.Status = PaymentStatus.Failed.ToString(); AddNoteAndSaveChanges(orderGroup, "Payment Captured - Error", "Payment - Captured - Error: " + ex.Message); return(Fail(ex.Message)); } AddNoteAndSaveChanges(orderGroup, "Payment - Captured", "Payment - Captured"); return(Success()); } else if (Successor != null) { return(Successor.Process(payment, orderForm, orderGroup)); } return(Fail(null)); }
public bool ProcessPayment(IPayment payment, ref string message) { try { Logger.Debug("Klarna checkout gateway. Processing Payment ...."); if (_orderForm == null) { _orderForm = OrderGroup.Forms.FirstOrDefault(form => form.Payments.Contains(payment)); } var authorizePaymentStep = new AuthorizePaymentStep(payment, OrderGroup.MarketId, KlarnaOrderServiceFactory); var capturePaymentStep = new CapturePaymentStep(payment, OrderGroup.MarketId, KlarnaOrderServiceFactory); var creditPaymentStep = new CreditPaymentStep(payment, OrderGroup.MarketId, KlarnaOrderServiceFactory); var cancelPaymentStep = new CancelPaymentStep(payment, OrderGroup.MarketId, KlarnaOrderServiceFactory); authorizePaymentStep.SetSuccessor(capturePaymentStep); capturePaymentStep.SetSuccessor(creditPaymentStep); creditPaymentStep.SetSuccessor(cancelPaymentStep); return(authorizePaymentStep.Process(payment, _orderForm, OrderGroup, OrderGroup.GetFirstShipment(), ref message)); } catch (Exception ex) { Logger.Error("Process checkout failed with error: " + ex.Message, ex); message = ex.Message; throw; } }
public void Handle(ReleaseRemainingEvent ev) { _order = ev.PurchaseOrder; _orderForm = _order.GetFirstForm(); var market = _marketService.GetMarket(_order.MarketId); var previousPayment = _orderForm.Payments.FirstOrDefault(x => x.IsKlarnaPayment()); if (previousPayment == null) { return; } var payment = _order.CreatePayment(_orderGroupFactory); payment.PaymentType = previousPayment.PaymentType; payment.PaymentMethodId = previousPayment.PaymentMethodId; payment.PaymentMethodName = previousPayment.PaymentMethodName; var remainingAmount = _orderForm .Shipments .Where(s => s.OrderShipmentStatus != OrderShipmentStatus.Shipped) .Sum(x => x.GetShippingItemsTotal(_order.Currency).Amount + x.GetShippingCost(market, _order.Currency).Amount); payment.Amount = remainingAmount; payment.Status = PaymentStatus.Pending.ToString(); payment.TransactionType = KlarnaAdditionalTransactionType.ReleaseRemainingAuthorization.ToString(); _order.AddPayment(payment); _paymentProcessor.ProcessPayment(_order, payment, _order.GetFirstShipment()); }
/// <summary> /// Populates default fields on the first order form. Override to populate custom order form fields. /// </summary> protected virtual void PopulateMetaFields( IPurchaseOrder purchaseOrder, IOrderForm orderForm, IMarket market, SaleViewModel kachingSale) { orderForm.Name = purchaseOrder.Name; }
private static List<DinteroOrderLine> ConvertRefundOrderLineItems(IOrderForm orderForm, DinteroTransactionActionResponse transaction, Currency currency) { // TODO: resolve address var shippingAddress = orderForm.Shipments.FirstOrDefault(); return orderForm.GetAllLineItems().Select(lineItem => TransformLineItem(currency, lineItem, shippingAddress?.ShippingAddress, ResolveLineItemDinteroId(transaction, lineItem.Code))).ToList(); }
public override OmniumOrder MapOrder(IPurchaseOrder purchaseOrder, IOrderForm orderForm, IShipment[] shipments) { var omniumOrder = base.MapOrder(purchaseOrder, orderForm, shipments); omniumOrder.StoreId = "123"; omniumOrder.MarketId = "NOR"; return(omniumOrder); }
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)); }
public override bool ProcessPayment(Payment payment, ref string message) { OrderGroup = payment.Parent.Parent; _orderForm = payment.Parent; var result = ProcessPayment(payment); message = result.Message; return(result.Status); }
/// <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)); }
public Money GetTaxTotal(IOrderForm orderForm, IMarket market, Currency currency) { var formTaxes = 0m; //calculate tax for each shipment foreach (var shipment in orderForm.Shipments.Where(x => x.ShippingAddress != null)) { var shippingTaxes = new List <ITaxValue>(); foreach (var item in shipment.LineItems) { //get the variation entry that the item is associated with var reference = _referenceConverter.GetContentLink(item.Code); var entry = _contentRepository.Get <VariationContent>(reference); if (entry == null || !entry.TaxCategoryId.HasValue) { continue; } //get the tax values applicable for the entry. If not taxes found then continue with next line item. var taxCategory = CatalogTaxManager.GetTaxCategoryNameById(entry.TaxCategoryId.Value); var taxes = GetTaxValues(taxCategory, market.DefaultLanguage.Name, shipment.ShippingAddress).ToList(); if (taxes.Count <= 0) { continue; } //calculate the line item price, excluding tax var lineItem = (LineItem)item; var lineItemPricesExcludingTax = item.PlacedPrice - (lineItem.OrderLevelDiscountAmount + lineItem.LineItemDiscountAmount) / item.Quantity; var quantity = 0m; if (orderForm.Name.Equals(OrderForm.ReturnName)) { quantity = item.ReturnQuantity; } else { quantity = item.Quantity; } formTaxes += taxes.Where(x => x.TaxType == TaxType.SalesTax).Sum(x => lineItemPricesExcludingTax * (decimal)x.Percentage * 0.01m) * quantity; //add shipping taxes for later tax calculation shippingTaxes.AddRange( taxes.Where(x => x.TaxType == TaxType.ShippingTax && !shippingTaxes.Any(y => y.Name.Equals(x.Name)))); } //sum the calculated tax for each shipment formTaxes += CalculateShippingTax(shippingTaxes, shipment, market, currency); } return(new Money(currency.Round(formTaxes), currency)); }
protected virtual IOrderAddress FindShippingAddress(VerifonePaymentRequest payment, IOrderGroup orderGroup) { IOrderForm orderForm = FindCorrectOrderForm(payment.PaymentMethodId, orderGroup.Forms); IShipment shipment = orderForm.Shipments.FirstOrDefault(); if (shipment?.ShippingAddress != null) { return(shipment.ShippingAddress); } return(FindBillingAddress(payment, orderGroup)); }
protected virtual IOrderAddress FindBillingAddress(VerifonePaymentRequest payment, IOrderGroup orderGroup) { IOrderForm orderForm = FindCorrectOrderForm(payment.PaymentMethodId, orderGroup.Forms); IPayment orderPayment = orderForm.Payments.FirstOrDefault(x => x.PaymentMethodId == payment.PaymentMethodId); IOrderAddress billingAddress = orderPayment?.BillingAddress; if (billingAddress == null) { billingAddress = orderGroup.Forms.SelectMany(x => x.Payments) .FirstOrDefault(x => x.BillingAddress != null)?.BillingAddress; } return(billingAddress); }
public override bool Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment, ref string message) { if (payment.TransactionType != TransactionType.Authorization.ToString()) { return(Successor != null && Successor.Process(payment, orderForm, orderGroup, shipment, ref message)); } if (ShouldProcessFraudUpdate(payment, orderGroup)) { return(ProcessFraudUpdate(payment, orderGroup, ref message)); } return(ProcessAuthorization(payment, orderGroup, ref message)); }
public PaymentStepResult ProcessPayment(IPayment payment, IShipment shipment) { var paymentStepResult = new PaymentStepResult(); _shipment = shipment; if (_orderForm == null) { _orderForm = (payment as Payment)?.Parent ?? OrderGroup?.Forms.FirstOrDefault(form => form.Payments.Contains(payment)); } if (OrderGroup == null) { OrderGroup = (_orderForm as OrderForm)?.Parent; } if (OrderGroup == null) { paymentStepResult.Message = "OrderGroup is null"; throw new Exception(paymentStepResult.Message); } try { Logger.Debug("SwedbankPay checkout gateway. Processing Payment ...."); if (_orderForm == null) { _orderForm = OrderGroup.Forms.FirstOrDefault(form => form.Payments.Contains(payment)); } var market = MarketService.GetMarket(OrderGroup.MarketId); var authorizePaymentStep = new AuthorizePaymentStep(payment, market, SwedbankPayClientFactory); var capturePaymentStep = new CapturePaymentStep(payment, market, SwedbankPayClientFactory, RequestFactory); var creditPaymentStep = new CreditPaymentStep(payment, market, SwedbankPayClientFactory, RequestFactory); var cancelPaymentStep = new CancelPaymentStep(payment, market, SwedbankPayClientFactory, RequestFactory); authorizePaymentStep.SetSuccessor(capturePaymentStep); capturePaymentStep.SetSuccessor(creditPaymentStep); creditPaymentStep.SetSuccessor(cancelPaymentStep); return(authorizePaymentStep.Process(payment, _orderForm, OrderGroup, _shipment)); } catch (Exception ex) { Logger.Error("Process checkout failed with error: " + ex.Message, ex); paymentStepResult.Message = ex.Message; throw; } }
public Document CreateDocumentForFulfillRequest(IPayment payment, IOrderForm orderForm) { var captureCount = orderForm.Payments.Count(x => x.TransactionType == TransactionType.Capture.ToString()); var merchantReference = payment.Properties[DataCashPaymentGateway.DataCashMerchantReferencePropertyName] as string; var requestDoc = CreateDocument(); requestDoc.set("Request.Transaction.TxnDetails.merchantreference", $"{merchantReference}_{captureCount}"); requestDoc.set("Request.Transaction.TxnDetails.amount", payment.Amount.ToString("0.##")); requestDoc.set("Request.Transaction.HistoricTxn.method", "fulfill"); requestDoc.set("Request.Transaction.HistoricTxn.authcode", payment.Properties[DataCashPaymentGateway.DataCashAuthenticateCodePropertyName] as string); requestDoc.set("Request.Transaction.HistoricTxn.reference", payment.Properties[DataCashPaymentGateway.DataCashReferencePropertyName] as string); return(requestDoc); }
public bool ProcessPayment(IPayment payment, ref string message) { if (_orderForm == null) { _orderForm = OrderGroup.GetFirstForm(); } _shipment = _orderForm.Shipments.FirstOrDefault(); var result = ProcessPayment(payment, _shipment); message = result.Message; return(result.Status); }
protected override RewardDescription Evaluate( FreeItemPromotion data, PromotionProcessorContext ctx) { // is this used IEnumerable <ContentReference> targetItems = data.DiscountTargets.Items.ToList(); // get which LI this promo is for var targets = data.DiscountTargets; var freeItem = data.FreeItem.Items.First().ToReferenceWithoutVersion(); //var freeItemCode = ServiceLocator.Current.GetInstance<ReferenceConverter>().GetCode(freeItem); var freeItemCode = _refConv.Service.GetCode(freeItem); // Have RefConv. below IOrderForm form = ctx.OrderForm; var lineItems = form.GetAllLineItems(); //var lineItems = GetLineItems(ctx.OrderForm.get); // not anymore var matchRecursive = false; // mandatory var skuCodes = _targetEvaluator.GetApplicableCodes( lineItems, targets.Items, targets.MatchRecursive); // get one if kicked in, 0 if not FulfillmentStatus status = data.RequiredQty.GetFulfillmentStatus(form, _targetEvaluator, _fulfillmentEvaluator); List <RewardDescription> rewardDescriptions = new List <RewardDescription>(); List <RedemptionDescription> redemptionDescriptions = new List <RedemptionDescription>(); // GetAllAffectedItems is the only method - name was changed var affectedItems = _targetEvaluator.GetApplicableCodes(lineItems, targetItems, matchRecursive); // only a single method to use on the "FulfillmentEvaluator" - out commented //var status = FulfillmentEvaluator.GetStatusForBuyQuantityPromotion(affectedItems.Select(x => x.LineItem) // , data.RequiredQty,0); // "Required" in the model // This way (demo) of using it is maybe not the intended, thought of like "buy 5 - get one for free" // ...have to load the gift and add it to the cart // ...have "Money" and "Percentage" return(RewardDescription.CreateFreeItemReward( status , GetRedemptions(skuCodes, data, ctx) , data , data.Description + " : " + freeItemCode //status, //affectedItems, //data //GetRewardDescriptionText(tagets, status, data) )); }
public override async Task <PaymentStepResult> Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment) { var paymentStepResult = new PaymentStepResult(); if (payment.TransactionType == TransactionType.Credit.ToString()) { try { var orderId = orderGroup.Properties[Common.Constants.KlarnaOrderIdField]?.ToString(); if (!string.IsNullOrEmpty(orderId)) { var purchaseOrder = orderGroup as IPurchaseOrder; if (purchaseOrder != null) { var returnForm = purchaseOrder.ReturnForms.FirstOrDefault(x => ((OrderForm)x).Status == ReturnFormStatus.Complete.ToString() && ((OrderForm)x).ObjectState == MetaObjectState.Modified); if (returnForm != null) { await KlarnaOrderService.Refund(orderId, orderGroup, (OrderForm)returnForm, payment).ConfigureAwait(false); } } payment.Status = PaymentStatus.Processed.ToString(); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Refunded {payment.Amount}"); paymentStepResult.Status = true; } } catch (Exception ex) when(ex is ApiException || ex is WebException || ex is AggregateException) { var exceptionMessage = GetExceptionMessage(ex); payment.Status = PaymentStatus.Failed.ToString(); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}"); Logger.Error(exceptionMessage, ex); paymentStepResult.Message = exceptionMessage; } } else if (Successor != null) { return(await Successor.Process(payment, orderForm, orderGroup, shipment).ConfigureAwait(false)); } return(paymentStepResult); }
public override RewardDescription Evaluate(IOrderForm orderForm, BuyXFromCategoryGetProductForFree promotionData, PromotionProcessorContext context) { IEnumerable <ILineItem> items = GetLineItemsInOrder(orderForm); List <AffectedItem> affectedItems = new List <AffectedItem>(); var lineItemCategories = items.Select(i => new { Quantity = i.Quantity, NodesForEntry = GetNodesForEntry(i.Code), Code = i.Code, LineItem = i }); decimal numberOfItemsInPromotionCategory = 0; NodeContent category = _contentLoader.Get <NodeContent>(promotionData.Category); foreach (var lineItemCategory in lineItemCategories) { if (lineItemCategory.NodesForEntry.Contains(category.Code)) { numberOfItemsInPromotionCategory += lineItemCategory.Quantity; // TODO: This has not yet been implemented //affectedItems.Add( // new AffectedItem( // _referenceConverter.GetContentLink(lineItemCategory.Code), // lineItemCategory.LineItem, // lineItemCategory.Quantity)); } } FulfillmentStatus fulfillment = this.GetFulfillment(numberOfItemsInPromotionCategory, promotionData.Threshold); // context.OrderGroup //if(fulfillment == FulfillmentStatus.Fulfilled) //{ // affectedItems.Add( // new AffectedItem( // promotionData // _referenceConverter.GetContentLink(lineItemCategory.Code), // lineItemCategory.LineItem, // lineItemCategory.Quantity)); //} return(RewardDescription.CreateFreeItemReward(fulfillment, affectedItems, promotionData, "Got something for free")); // return new RewardDescription(fulfillment, affectedItems, promotionData, 0, 0, RewardType.Free, "Got something for free"); }
public override PaymentStepResult Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment) { if (payment.TransactionType != TransactionType.Authorization.ToString()) { var paymentStepResult = new PaymentStepResult(); if (Successor != null) { paymentStepResult = Successor.Process(payment, orderForm, orderGroup, shipment); paymentStepResult.Status = true; paymentStepResult.Status = Successor != null && paymentStepResult.Status; } return(paymentStepResult); } return(ProcessAuthorization(payment, orderGroup)); }
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); }
protected override Money CalculateSubtotal(IOrderForm orderForm, Currency currency) { var result = orderForm.GetAllLineItems().Where(x => !x.IsGift).Sum(lineItem => _lineItemCalculator.GetDiscountedPrice(lineItem, currency).Amount); return new Money(result, currency); }