/// <summary> /// Creates a purchase order with the given order number and deletes the cart /// </summary> /// <param name="cart">Cart</param> /// <param name="payment">Payment</param> /// <param name="orderNumber">orderNumber</param> /// <returns>Boolean indicating success or failure</returns> private bool CreatePurchaseOrder(Cart cart, Payment payment, string orderNumber) { try { using (TransactionScope scope = new TransactionScope()) { PaymentStatusManager.ProcessPayment(payment); cart.OrderNumberMethod = c => orderNumber; PurchaseOrder purchaseOrder = cart.SaveAsPurchaseOrder(); cart.Delete(); cart.AcceptChanges(); purchaseOrder.AcceptChanges(); scope.Complete(); } return(true); } catch (Exception e) { // Add your own logging return(false); } }
/// <summary> /// Processes the successful transaction, will be called when DIBS server processes /// the payment successfully and redirect back. /// </summary> /// <param name="cart">The cart that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="transactionID">The transaction id.</param> /// <param name="orderNumber">The order number.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The redirection url after processing.</returns> public string ProcessSuccessfulTransaction(ICart cart, IPayment payment, string transactionID, string orderNumber, string acceptUrl, string cancelUrl) { if (cart == null) { return(cancelUrl); } string redirectionUrl; // Change status of payments to processed. // It must be done before execute workflow to ensure payments which should mark as processed. // To avoid get errors when executed workflow. PaymentStatusManager.ProcessPayment(payment); var errorMessages = new List <string>(); var cartCompleted = DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Save the transact from DIBS to payment. payment.TransactionID = transactionID; var purchaseOrder = MakePurchaseOrder(cart, orderNumber); redirectionUrl = UpdateAcceptUrl(purchaseOrder, payment, acceptUrl); return(redirectionUrl); }
public void FraudUpdate(NotificationModel notification) { var order = GetPurchaseOrderByKlarnaOrderId(notification.OrderId); if (order != null) { var orderForm = order.GetFirstForm(); var payment = orderForm.Payments.FirstOrDefault(); if (payment != null && payment.Status == PaymentStatus.Pending.ToString()) { payment.Properties[Constants.FraudStatusPaymentField] = notification.Status.ToString(); try { var result = order.ProcessPayments(_paymentProcessor, _orderGroupCalculator); if (result.FirstOrDefault()?.IsSuccessful == false) { PaymentStatusManager.FailPayment((Payment)payment); _orderRepository.Save(order); } } catch (Exception ex) { _logger.Error(ex.Message, ex); } _orderRepository.Save(order); } } }
private void FillDropDowns() { this.ddlOrderStatus.Items.Clear(); ListItem itemOrderStatus = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlOrderStatus.Items.Add(itemOrderStatus); OrderStatusCollection orderStatuses = OrderManager.GetAllOrderStatuses(); foreach (OrderStatus orderStatus in orderStatuses) { ListItem item2 = new ListItem(orderStatus.Name, orderStatus.OrderStatusID.ToString()); this.ddlOrderStatus.Items.Add(item2); } this.ddlPaymentStatus.Items.Clear(); ListItem itemPaymentStatus = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlPaymentStatus.Items.Add(itemPaymentStatus); PaymentStatusCollection paymentStatuses = PaymentStatusManager.GetAllPaymentStatuses(); foreach (PaymentStatus paymentStatus in paymentStatuses) { ListItem item2 = new ListItem(paymentStatus.Name, paymentStatus.PaymentStatusID.ToString()); this.ddlPaymentStatus.Items.Add(item2); } }
/// <summary> /// Processes the payment. /// </summary> private void ProcessPayment() { // Calculate payment total var formPayments = OrderGroup.OrderForms[0].Payments.ToArray(); var resultingAuthorizedPayments = OrderGroup.OrderForms[0].GetPaymentsByTransactionType(formPayments, TransactionType.Authorization); var authorizedPayments = resultingAuthorizedPayments.Where(x => PaymentStatusManager.GetPaymentStatus(x) == PaymentStatus.Processed); // Find intire authorization var shipmentTotal = CalculateShipmentTotal(); var intirePayment = authorizedPayments.OrderBy(x => x.Amount).FirstOrDefault(x => x.Amount >= shipmentTotal); if (intirePayment == null) { var payments = authorizedPayments.OrderByDescending(x => x.Amount); foreach (Payment partialPayment in payments) { if (partialPayment.Amount < shipmentTotal) { DoCapture(partialPayment, partialPayment.Amount); shipmentTotal -= partialPayment.Amount; } else { DoCapture(partialPayment, shipmentTotal); break; } } } else { DoCapture((Payment)intirePayment, shipmentTotal); } }
/// <summary> /// Validates and completes a cart. /// </summary> /// <param name="cart">The cart.</param> /// <param name="errorMessages">The error messages.</param> private bool DoCompletingCart(ICart cart, IList <string> errorMessages) { // Change status of payments to processed. // It must be done before execute workflow to ensure payments which should mark as processed. // To avoid get errors when executed workflow. foreach (var p in cart.Forms.SelectMany(f => f.Payments).Where(p => p != null)) { PaymentStatusManager.ProcessPayment(p); } var validationIssues = new Dictionary <ILineItem, IList <ValidationIssue> >(); cart.AdjustInventoryOrRemoveLineItems((item, issue) => AddValidationIssues(validationIssues, item, issue), _inventoryProcessor); var isSuccess = !validationIssues.Any(); foreach (var issue in validationIssues.Values.SelectMany(x => x).Distinct()) { errorMessages.Add( issue == ValidationIssue.RejectedInventoryRequestDueToInsufficientQuantity ? Utilities.Translate("NotEnoughStockWarning") : Utilities.Translate("CartValidationWarning")); } return(isSuccess); }
public void SetPaymentProcessed(PaymentMethod paymentMethod) { var payment = (Mediachase.Commerce.Orders.Payment)paymentMethod.Payment; PaymentStatusManager.ProcessPayment(payment); payment.AcceptChanges(); Log.InfoFormat("Successfully set payment status to pros for payment with ID:{0} belonging to order with ID: {1}", paymentMethod.Payment.Id, paymentMethod.OrderGroupId); }
/// <summary> /// Processes the successful transaction, will be called when Dintero server processes /// the payment successfully and redirect back. /// </summary> /// <param name="cart">The cart that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="transactionId">The transaction id.</param> /// <param name="orderNumber">The order number.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The redirection url after processing.</returns> public virtual string ProcessSuccessfulTransaction(ICart cart, IPayment payment, string transactionId, string orderNumber, string acceptUrl, string cancelUrl) { Logger.Debug("DinteroPaymentGateway.ProcessSuccessfulTransaction starting..."); if (cart == null) { return(cancelUrl); } // check whether transaction was authorized by Dintero (prevent order creation on manual hack) var transaction = _requestsHelper.GetTransactionDetails(payment.TransactionID); if (transaction == null) { Logger.Debug($"Unable to get Dintero transaction by id: [{payment.TransactionID}]!"); return(cancelUrl); } Logger.Debug($"Dintero transaction #'{payment.TransactionID}' status = [{transaction.Status}]!"); if (transaction.Status != "AUTHORIZED" && transaction.Status != "ON_HOLD") { return(cancelUrl); } string redirectionUrl; using (var scope = new TransactionScope()) { // Change status of payments to processed. // It must be done before execute workflow to ensure payments which should mark as processed. // To avoid get errors when executed workflow. PaymentStatusManager.ProcessPayment(payment); var isOnHold = transaction.Status == "ON_HOLD"; var errorMessages = new List <string>(); var cartCompleted = DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Save the transact from Dintero to payment. payment.TransactionID = transactionId; var purchaseOrder = MakePurchaseOrder(cart, orderNumber, isOnHold); redirectionUrl = UpdateAcceptUrl(purchaseOrder, acceptUrl, isOnHold); // Commit changes scope.Complete(); } return(redirectionUrl); }
/// <summary> /// Validates and completes a cart. /// </summary> /// <param name="cart">The cart.</param> /// <param name="errorMessages">The error messages.</param> public virtual bool DoCompletingCart(ICart cart, IList <string> errorMessages) { // Change status of payments to processed. // It must be done before execute workflow to ensure payments which should mark as processed. // To avoid get errors when executed workflow. foreach (IPayment p in cart.Forms.SelectMany(f => f.Payments).Where(p => p != null)) { PaymentStatusManager.ProcessPayment(p); } var isSuccess = true; if (_databaseMode.Value != DatabaseMode.ReadOnly) { if (_featureSwitch.IsSerializedCartsEnabled()) { var validationIssues = new Dictionary <ILineItem, IList <ValidationIssue> >(); cart.AdjustInventoryOrRemoveLineItems( (item, issue) => AddValidationIssues(validationIssues, item, issue), _inventoryProcessor); isSuccess = !validationIssues.Any(); foreach (var issue in validationIssues.Values.SelectMany(x => x).Distinct()) { if (issue == ValidationIssue.RejectedInventoryRequestDueToInsufficientQuantity) { errorMessages.Add("NotEnoughStockWarning"); } else { errorMessages.Add("CartValidationWarning"); } } return(isSuccess); } // Execute CheckOutWorkflow with parameter to ignore running process payment activity again. var isIgnoreProcessPayment = new Dictionary <string, object> { { "PreventProcessPayment", true } }; var workflowResults = OrderGroupWorkflowManager.RunWorkflow((OrderGroup)cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName, true, isIgnoreProcessPayment); var warnings = workflowResults.OutputParameters["Warnings"] as StringDictionary; isSuccess = warnings.Count == 0; foreach (string message in warnings.Values) { errorMessages.Add(message); } } return(isSuccess); }
/// <summary> /// Processes the successful transaction, will be called when epay server processes /// the payment successfully and redirect back. /// </summary> /// <param name="cart">The cart that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="transactionId">The transaction id.</param> /// <param name="subscriptionId">The subscription id in case returned</param> /// <param name="orderNumber">The order number.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The redirection url after processing.</returns> public string ProcessSuccessfulTransaction(ICart cart, IPayment payment, string transactionId, string subscriptionId, string orderNumber, string acceptUrl, string cancelUrl) { if (cart == null) { return(cancelUrl); } var redirectionUrl = string.Empty; using (TransactionScope scope = new TransactionScope()) { // Change status of payments to processed. // It must be done before execute workflow to ensure payments which should mark as processed. // To avoid get errors when executed workflow. PaymentStatusManager.ProcessPayment(payment); var errorMessages = new List <string>(); var cartCompleted = DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriSupport.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Save the transact from epay to payment. payment.TransactionID = transactionId; // Save subscription id in the payment properties. if (!string.IsNullOrEmpty(subscriptionId)) { payment.AuthorizationCode = subscriptionId; //properties wasnt saved } // Create a purchase order var purchaseOrder = MakePurchaseOrder(cart, orderNumber); // Create a subscription plan var supscriptionPlan = MakeSubscription(cart, payment); // Commit changes scope.Complete(); if (HttpContext.Current.Session != null) { HttpContext.Current.Session.Remove("LastCouponCode"); //todo: is this needed? } //todo: change in case of subscription or? redirectionUrl = UpdateAcceptUrl(purchaseOrder, payment, acceptUrl); } return(redirectionUrl); }
protected IEnumerable <Payment> GetResultingPaymentsByTransactionType(IEnumerable <Payment> payments, TransactionType type) { List <Payment> retVal = new List <Payment>(); var paymentsWithSameTranType = GetPaymentsByTransactionType(payments, new TransactionType[] { type }); foreach (var payment in paymentsWithSameTranType) { //Get all related payments only in Processing status var allRelatedPayments = GetAllRelatedPayments(payment).Where(x => PaymentStatusManager.GetPaymentStatus(x) == PaymentStatus.Processed); //do not return authorization payments which have Void related payments, or it has been Captured all amount. if (type == TransactionType.Authorization) { var anyVoidTransaction = allRelatedPayments.Any(x => GetPaymentTransactionType(x) == TransactionType.Void); var anyCaptureTransaction = allRelatedPayments.Any(x => GetPaymentTransactionType(x) == TransactionType.Capture); var capturedAmount = allRelatedPayments.Where(x => GetPaymentTransactionType(x) == TransactionType.Capture).Sum(x => x.Amount); if (!anyVoidTransaction) { if (anyCaptureTransaction) { // get total captured amount, then check if it is lower than the authorized amount to return the payment. // in other word, we will not return the payment if all of authorized amount has been captured, which means no need to capture anymore. if (capturedAmount < payment.Amount) { yield return(payment); } } else { yield return(payment); } } } else { //do not return other payments with haved Void related payments if (!allRelatedPayments.Any(x => GetPaymentTransactionType(x) == TransactionType.Void)) { yield return(payment); } } } }
/// <summary> /// Calculates the totals order forms. /// </summary> /// <param name="form">The form.</param> private void CalculateTotalsOrderForms(OrderForm form) { decimal subTotal = 0m; decimal discountTotal = 0m; decimal shippingDiscountTotal = 0m; decimal shippingTotal = 0m; foreach (LineItem item in form.LineItems) { decimal lineItemDiscount = item.LineItemDiscountAmount + item.OrderLevelDiscountAmount; item.ExtendedPrice = item.PlacedPrice * item.Quantity - lineItemDiscount; subTotal += item.ExtendedPrice; discountTotal += lineItemDiscount; } foreach (Shipment shipment in form.Shipments) { shipment.SubTotal = CalculateShipmentSubtotal(shipment); shippingTotal += shipment.ShipmentTotal; shippingTotal -= shipment.ShippingDiscountAmount; shippingDiscountTotal += shipment.ShippingDiscountAmount; } form.ShippingTotal = shippingTotal; form.DiscountAmount = discountTotal + shippingDiscountTotal; form.SubTotal = subTotal; form.Total = subTotal + shippingTotal; //Calculate payment total var formPayments = form.Payments.ToArray(); var resultingAuthorizedPayments = PaymentTransactionTypeManager.GetResultingPaymentsByTransactionType(formPayments, TransactionType.Authorization); var resultingCapturedPayments = PaymentTransactionTypeManager.GetResultingPaymentsByTransactionType(formPayments, TransactionType.Capture); var resultingSalsePayments = PaymentTransactionTypeManager.GetResultingPaymentsByTransactionType(formPayments, TransactionType.Sale); var resultingCreditPayments = PaymentTransactionTypeManager.GetResultingPaymentsByTransactionType(formPayments, TransactionType.Credit); form.AuthorizedPaymentTotal = resultingAuthorizedPayments.Where(x => PaymentStatusManager.GetPaymentStatus(x) == PaymentStatus.Processed).Sum(y => y.Amount); form.CapturedPaymentTotal = resultingSalsePayments.Where(x => PaymentStatusManager.GetPaymentStatus(x) == PaymentStatus.Processed).Sum(y => y.Amount); form.CapturedPaymentTotal += resultingCapturedPayments.Where(x => PaymentStatusManager.GetPaymentStatus(x) == PaymentStatus.Processed).Sum(y => y.Amount); form.CapturedPaymentTotal -= resultingCreditPayments.Where(x => PaymentStatusManager.GetPaymentStatus(x) == PaymentStatus.Processed).Sum(y => y.Amount); }
private void FillDropDowns() { //order statuses this.ddlOrderStatus.Items.Clear(); ListItem itemOrderStatus = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlOrderStatus.Items.Add(itemOrderStatus); var orderStatuses = OrderManager.GetAllOrderStatuses(); foreach (OrderStatus orderStatus in orderStatuses) { ListItem item2 = new ListItem(OrderManager.GetOrderStatusName(orderStatus.OrderStatusId), orderStatus.OrderStatusId.ToString()); this.ddlOrderStatus.Items.Add(item2); } //payment statuses this.ddlPaymentStatus.Items.Clear(); ListItem itemPaymentStatus = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlPaymentStatus.Items.Add(itemPaymentStatus); var paymentStatuses = PaymentStatusManager.GetAllPaymentStatuses(); foreach (PaymentStatus paymentStatus in paymentStatuses) { ListItem item2 = new ListItem(PaymentStatusManager.GetPaymentStatusName(paymentStatus.PaymentStatusId), paymentStatus.PaymentStatusId.ToString()); this.ddlPaymentStatus.Items.Add(item2); } //countries ddlBillingCountry.Items.Clear(); ListItem itemBillingCountry = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlBillingCountry.Items.Add(itemBillingCountry); var countries = CountryManager.GetAllCountriesForBilling(); foreach (var country in countries) { ListItem ddlCountryItem2 = new ListItem(country.Name, country.CountryId.ToString()); ddlBillingCountry.Items.Add(ddlCountryItem2); } }
protected void FillDropDowns() { this.ddlOrderStatus.Items.Clear(); ListItem itemOrderStatus = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlOrderStatus.Items.Add(itemOrderStatus); OrderStatusCollection orderStatuses = OrderManager.GetAllOrderStatuses(); foreach (OrderStatus orderStatus in orderStatuses) { ListItem item2 = new ListItem(OrderManager.GetOrderStatusName(orderStatus.OrderStatusId), orderStatus.OrderStatusId.ToString()); this.ddlOrderStatus.Items.Add(item2); } this.ddlPaymentStatus.Items.Clear(); ListItem itemPaymentStatus = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlPaymentStatus.Items.Add(itemPaymentStatus); PaymentStatusCollection paymentStatuses = PaymentStatusManager.GetAllPaymentStatuses(); foreach (PaymentStatus paymentStatus in paymentStatuses) { ListItem item2 = new ListItem(PaymentStatusManager.GetPaymentStatusName(paymentStatus.PaymentStatusId), paymentStatus.PaymentStatusId.ToString()); this.ddlPaymentStatus.Items.Add(item2); } this.ddlShippingStatus.Items.Clear(); ListItem itemShippingStatus = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlShippingStatus.Items.Add(itemShippingStatus); ShippingStatusCollection shippingStatuses = ShippingStatusManager.GetAllShippingStatuses(); foreach (ShippingStatus shippingStatus in shippingStatuses) { ListItem item2 = new ListItem(ShippingStatusManager.GetShippingStatusName(shippingStatus.ShippingStatusId), shippingStatus.ShippingStatusId.ToString()); this.ddlShippingStatus.Items.Add(item2); } }
public bool Capture(PaymentMethod currentPayment, string additionalValues) { Mediachase.Commerce.Orders.Payment payment = (Mediachase.Commerce.Orders.Payment)currentPayment.Payment; Log.InfoFormat("Capturing payment with ID:{0} belonging to order with ID: {1}", payment.Id, payment.OrderGroupId); int transactionId; if (!int.TryParse(payment.AuthorizationCode, out transactionId)) { Log.ErrorFormat("Could not get PayEx transaction ID from payment with ID:{0} belonging to order with ID: {1}", payment.Id, payment.OrderGroupId); return(false); } Log.InfoFormat("PayEx transaction ID is {0} on payment with ID:{1} belonging to order with ID: {2}", transactionId, payment.Id, payment.OrderGroupId); long amount = payment.Amount.RoundToLong(); string orderNumber = OrderNumberFormatter.MakeNumeric(currentPayment.PurchaseOrder.TrackingNumber); CaptureResult result = _paymentManager.Capture(transactionId, amount, orderNumber, currentPayment.Payment.Vat, additionalValues); bool success = false; if (result.Success && !string.IsNullOrWhiteSpace(result.TransactionNumber)) { Log.InfoFormat("Setting PayEx transaction number to {0} on payment with ID:{1} belonging to order with ID: {2} during capture", result.TransactionNumber, payment.Id, payment.OrderGroupId); payment.ValidationCode = result.TransactionNumber; PaymentStatusManager.ProcessPayment(payment); payment.AcceptChanges(); success = true; Log.InfoFormat("Successfully captured payment with ID:{0} belonging to order with ID: {1}", currentPayment.Payment.Id, currentPayment.OrderGroupId); } if (_paymentCapturer != null) { return(_paymentCapturer.Capture(currentPayment) && success); } return(success); }
protected void Page_Load(object sender, EventArgs e) { CommonHelper.SetResponseNoCache(Response); if (!Page.IsPostBack) { byte[] param = Request.BinaryRead(Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); Dictionary <string, string> values; PayPalStandardPaymentProcessor processor = new PayPalStandardPaymentProcessor(); if (processor.VerifyIPN(strRequest, out values)) { #region values decimal total = decimal.Zero; try { total = decimal.Parse(values["mc_gross"], new CultureInfo("en-US")); } catch { } string payer_status = string.Empty; values.TryGetValue("payer_status", out payer_status); string payment_status = string.Empty; values.TryGetValue("payment_status", out payment_status); string pending_reason = string.Empty; values.TryGetValue("pending_reason", out pending_reason); string mc_currency = string.Empty; values.TryGetValue("mc_currency", out mc_currency); string txn_id = string.Empty; values.TryGetValue("txn_id", out txn_id); string txn_type = string.Empty; values.TryGetValue("txn_type", out txn_type); string rp_invoice_id = string.Empty; values.TryGetValue("rp_invoice_id", out rp_invoice_id); string payment_type = string.Empty; values.TryGetValue("payment_type", out payment_type); string payer_id = string.Empty; values.TryGetValue("payer_id", out payer_id); string receiver_id = string.Empty; values.TryGetValue("receiver_id", out receiver_id); string invoice = string.Empty; values.TryGetValue("invoice", out invoice); string payment_fee = string.Empty; values.TryGetValue("payment_fee", out payment_fee); #endregion StringBuilder sb = new StringBuilder(); sb.AppendLine("Paypal IPN:"); foreach (KeyValuePair <string, string> kvp in values) { sb.AppendLine(kvp.Key + ": " + kvp.Value); } PaymentStatusEnum newPaymentStatus = PaypalHelper.GetPaymentStatus(payment_status, pending_reason); sb.AppendLine("New payment status: " + PaymentStatusManager.GetPaymentStatusName((int)newPaymentStatus)); switch (txn_type) { case "recurring_payment_profile_created": //do nothing here break; case "recurring_payment": #region Recurring payment { Guid orderNumberGuid = Guid.Empty; try { orderNumberGuid = new Guid(rp_invoice_id); } catch { } Order initialOrder = OrderManager.GetOrderByGuid(orderNumberGuid); if (initialOrder != null) { RecurringPaymentCollection recurringPayments = OrderManager.SearchRecurringPayments(0, initialOrder.OrderId, null); foreach (var rp in recurringPayments) { switch (newPaymentStatus) { case PaymentStatusEnum.Authorized: case PaymentStatusEnum.Paid: { var recurringPaymentHistory = rp.RecurringPaymentHistory; if (recurringPaymentHistory.Count == 0) { //first payment OrderManager.InsertRecurringPaymentHistory(rp.RecurringPaymentId, initialOrder.OrderId, DateTime.Now); } else { //next payments OrderManager.ProcessNextRecurringPayment(rp.RecurringPaymentId); //UNDONE change new order status according to newPaymentStatus //UNDONE refund/void is not supported } } break; } } //OrderManager.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.Now); LogManager.InsertLog(LogTypeEnum.Unknown, "PayPal IPN. Recurring info", new NopException(sb.ToString())); } else { LogManager.InsertLog(LogTypeEnum.OrderError, "PayPal IPN. Order is not found", new NopException(sb.ToString())); } } #endregion break; default: #region Standard payment { string orderNumber = string.Empty; values.TryGetValue("custom", out orderNumber); Guid orderNumberGuid = Guid.Empty; try { orderNumberGuid = new Guid(orderNumber); } catch { } Order order = OrderManager.GetOrderByGuid(orderNumberGuid); if (order != null) { OrderManager.InsertOrderNote(order.OrderId, sb.ToString(), false, DateTime.Now); switch (newPaymentStatus) { case PaymentStatusEnum.Pending: { } break; case PaymentStatusEnum.Authorized: { if (OrderManager.CanMarkOrderAsAuthorized(order)) { OrderManager.MarkAsAuthorized(order.OrderId); } } break; case PaymentStatusEnum.Paid: { if (OrderManager.CanMarkOrderAsPaid(order)) { OrderManager.MarkOrderAsPaid(order.OrderId); } } break; case PaymentStatusEnum.Refunded: { if (OrderManager.CanRefundOffline(order)) { OrderManager.RefundOffline(order.OrderId); } } break; case PaymentStatusEnum.Voided: { if (OrderManager.CanVoidOffline(order)) { OrderManager.VoidOffline(order.OrderId); } } break; default: break; } } else { LogManager.InsertLog(LogTypeEnum.OrderError, "PayPal IPN. Order is not found", new NopException(sb.ToString())); } } #endregion break; } } else { LogManager.InsertLog(LogTypeEnum.OrderError, "PayPal IPN failed.", strRequest); } } }
/// <summary> /// Processes the payment. /// </summary> private void ProcessPayment() { // If total is 0, we do not need to proceed if (OrderGroup.Total == 0 || OrderGroup is PaymentPlan) { return; } // Start Charging! PaymentMethodDto methods = PaymentManager.GetPaymentMethods(/*Thread.CurrentThread.CurrentCulture.Name*/ String.Empty); foreach (OrderForm orderForm in OrderGroup.OrderForms) { foreach (Payment payment in orderForm.Payments) { if (this.Payment != null && !this.Payment.Equals(payment)) { continue; } //Do not process payments with status Processing and Fail var paymentStatus = PaymentStatusManager.GetPaymentStatus(payment); if (paymentStatus != PaymentStatus.Pending) { continue; } PaymentMethodDto.PaymentMethodRow paymentMethod = methods.PaymentMethod.FindByPaymentMethodId(payment.PaymentMethodId); // If we couldn't find payment method specified, generate an error if (paymentMethod == null) { throw new MissingMethodException(String.Format("Specified payment method \"{0}\" has not been defined.", payment.PaymentMethodId)); } Logger.Debug(String.Format("Getting the type \"{0}\".", paymentMethod.ClassName)); Type type = Type.GetType(paymentMethod.ClassName); if (type == null) { throw new TypeLoadException(String.Format("Specified payment method class \"{0}\" can not be created.", paymentMethod.ClassName)); } Logger.Debug(String.Format("Creating instance of \"{0}\".", type.Name)); IPaymentGateway provider = (IPaymentGateway)Activator.CreateInstance(type); provider.Settings = CreateSettings(paymentMethod); string message = ""; Logger.Debug(String.Format("Processing the payment.")); if (provider.ProcessPayment(payment, ref message)) { Mediachase.Commerce.Orders.Managers.PaymentStatusManager.ProcessPayment(payment); } else { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", String.Format(message)); } Logger.Debug(String.Format("Payment processed.")); PostProcessPayment(payment); // TODO: add message to transaction log } } }
protected void Page_Load(object sender, EventArgs e) { CommonHelper.SetResponseNoCache(Response); if (!Page.IsPostBack) { //item_id_1 or vendor_order_id string nopOrderIdStr = HttpContext.Current.Request.Form["item_id_1"]; int nopOrderId = 0; int.TryParse(nopOrderIdStr, out nopOrderId); Order order = OrderManager.GetOrderById(nopOrderId); if (order != null) { //debug info StringBuilder sbDebug = new StringBuilder(); sbDebug.AppendLine("2Checkout IPN:"); foreach (string key in HttpContext.Current.Request.Form.AllKeys) { string value = HttpContext.Current.Request.Form[key]; sbDebug.AppendLine(key + ": " + value); } OrderManager.InsertOrderNote(order.OrderId, sbDebug.ToString(), false, DateTime.UtcNow); bool useSandbox = SettingManager.GetSettingValueBoolean("PaymentMethod.TwoCheckout.UseSandbox"); //sale id string sale_id = string.Empty; if (useSandbox) { sale_id = "1"; } else { sale_id = HttpContext.Current.Request.Form["sale_id"]; } if (sale_id == null) { sale_id = string.Empty; } //invoice id string invoice_id = HttpContext.Current.Request.Form["invoice_id"]; if (invoice_id == null) { invoice_id = string.Empty; } if (SettingManager.GetSettingValueBoolean("PaymentMethod.TwoCheckout.UseMD5Hashing")) { string vendorId = SettingManager.GetSettingValue("PaymentMethod.TwoCheckout.VendorId"); string secretWord = SettingManager.GetSettingValue("PaymentMethod.TwoCheckout.SecretWord"); string compareHash1 = TwoCheckoutPaymentProcessor.CalculateMD5hash(sale_id + vendorId + invoice_id + secretWord); if (String.IsNullOrEmpty(compareHash1)) { throw new NopException("2Checkout empty hash string"); } string compareHash2 = HttpContext.Current.Request.Form["md5_hash"]; if (compareHash2 == null) { compareHash2 = string.Empty; } if (compareHash1.ToUpperInvariant() != compareHash2.ToUpperInvariant()) { OrderManager.InsertOrderNote(order.OrderId, "Hash validation failed", false, DateTime.UtcNow); Response.Redirect(CommonHelper.GetStoreLocation()); } } string message_type = HttpContext.Current.Request.Form["message_type"]; if (message_type == null) { message_type = string.Empty; } string invoice_status = HttpContext.Current.Request.Form["invoice_status"]; if (invoice_status == null) { invoice_status = string.Empty; } string fraud_status = HttpContext.Current.Request.Form["fraud_status"]; if (fraud_status == null) { fraud_status = string.Empty; } string payment_type = HttpContext.Current.Request.Form["payment_type"]; if (payment_type == null) { payment_type = string.Empty; } PaymentStatusEnum newPaymentStatus = TwoCheckoutPaymentProcessor.GetPaymentStatus(message_type, invoice_status, fraud_status, payment_type); StringBuilder sb = new StringBuilder(); sb.AppendLine("2Checkout IPN:"); sb.AppendLine("sale_id: " + sale_id); sb.AppendLine("invoice_id: " + invoice_id); sb.AppendLine("message_type: " + message_type); sb.AppendLine("invoice_status: " + invoice_status); sb.AppendLine("fraud_status: " + fraud_status); sb.AppendLine("payment_type: " + payment_type); sb.AppendLine("New payment status: " + PaymentStatusManager.GetPaymentStatusName((int)newPaymentStatus)); OrderManager.InsertOrderNote(order.OrderId, sb.ToString(), false, DateTime.UtcNow); //new payment status switch (newPaymentStatus) { case PaymentStatusEnum.Pending: { } break; case PaymentStatusEnum.Authorized: { if (OrderManager.CanMarkOrderAsAuthorized(order)) { OrderManager.MarkAsAuthorized(order.OrderId); } } break; case PaymentStatusEnum.Paid: { if (OrderManager.CanMarkOrderAsPaid(order)) { OrderManager.MarkOrderAsPaid(order.OrderId); } } break; case PaymentStatusEnum.Refunded: { if (OrderManager.CanRefundOffline(order)) { OrderManager.RefundOffline(order.OrderId); } } break; case PaymentStatusEnum.Voided: { if (OrderManager.CanVoidOffline(order)) { OrderManager.VoidOffline(order.OrderId); } } break; default: break; } } else { Response.Redirect(CommonHelper.GetStoreLocation()); } } }
public void FraudUpdate(NotificationModel notification) { var order = GetPurchaseOrderByKlarnaOrderId(notification.OrderId); if (order == null) { return; } var orderForm = order.GetFirstForm(); var payment = orderForm.Payments.FirstOrDefault(); if (payment == null) { return; } // Get payment method used and the configuration data var paymentMethodDto = PaymentManager.GetPaymentMethod(payment.PaymentMethodId); var connectionConfiguration = paymentMethodDto.GetConnectionConfiguration(order.MarketId); string userAgent = $"Platform/Episerver.Commerce_{typeof(EPiServer.Commerce.ApplicationContext).Assembly.GetName().Version} Module/Klarna.Common_{typeof(KlarnaService).Assembly.GetName().Version}"; var client = new OrderManagementStore(new ApiSession { ApiUrl = connectionConfiguration.ApiUrl, UserAgent = userAgent, Credentials = new ApiCredentials { Username = connectionConfiguration.Username, Password = connectionConfiguration.Password } }, new JsonSerializer()); // Make sure the order exists in Klarna var klarnaOrder = AsyncHelper.RunSync(() => client.GetOrder(notification.OrderId)); if (klarnaOrder == null) { return; } // Compare fraud status of notification with Klarna order fraud status and stop process if it's still pending or doesn't match switch (klarnaOrder.FraudStatus) { case OrderManagementFraudStatus.ACCEPTED: if (notification.Status != NotificationFraudStatus.FRAUD_RISK_ACCEPTED) { return; } break; case OrderManagementFraudStatus.REJECTED: if (notification.Status != NotificationFraudStatus.FRAUD_RISK_REJECTED) { return; } break; case OrderManagementFraudStatus.PENDING: return; } payment.Status = PaymentStatus.Pending.ToString(); payment.Properties[Constants.FraudStatusPaymentField] = notification.Status; try { var result = order.ProcessPayments(_paymentProcessor, _orderGroupCalculator); if (result.FirstOrDefault()?.IsSuccessful == false) { PaymentStatusManager.FailPayment((Payment)payment); _orderRepository.Save(order); } } catch (Exception ex) { _logger.Error(ex.Message, ex); } _orderRepository.Save(order); }
protected void FillDropDowns() { var orderStatuses = OrderManager.GetAllOrderStatuses(); var paymentStatuses = PaymentStatusManager.GetAllPaymentStatuses(); var shippingStatuses = ShippingStatusManager.GetAllShippingStatuses(); //by order total this.ddlOrderStatusByOrderTotal.Items.Clear(); ListItem itemOrderStatusByOrderTotal = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlOrderStatusByOrderTotal.Items.Add(itemOrderStatusByOrderTotal); foreach (OrderStatus orderStatus in orderStatuses) { ListItem item2 = new ListItem(OrderManager.GetOrderStatusName(orderStatus.OrderStatusId), orderStatus.OrderStatusId.ToString()); this.ddlOrderStatusByOrderTotal.Items.Add(item2); } this.ddlPaymentStatusByOrderTotal.Items.Clear(); ListItem itemPaymentStatusByOrderTotal = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlPaymentStatusByOrderTotal.Items.Add(itemPaymentStatusByOrderTotal); foreach (PaymentStatus paymentStatus in paymentStatuses) { ListItem item2 = new ListItem(PaymentStatusManager.GetPaymentStatusName(paymentStatus.PaymentStatusId), paymentStatus.PaymentStatusId.ToString()); this.ddlPaymentStatusByOrderTotal.Items.Add(item2); } this.ddlShippingStatusByOrderTotal.Items.Clear(); ListItem itemShippingStatusByOrderTotal = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlShippingStatusByOrderTotal.Items.Add(itemShippingStatusByOrderTotal); foreach (ShippingStatus shippingStatus in shippingStatuses) { ListItem item2 = new ListItem(ShippingStatusManager.GetShippingStatusName(shippingStatus.ShippingStatusId), shippingStatus.ShippingStatusId.ToString()); this.ddlShippingStatusByOrderTotal.Items.Add(item2); } //by number of orders this.ddlOrderStatusByNumberOfOrder.Items.Clear(); ListItem itemOrderStatusByNumberOfOrder = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlOrderStatusByNumberOfOrder.Items.Add(itemOrderStatusByNumberOfOrder); foreach (OrderStatus orderStatus in orderStatuses) { ListItem item2 = new ListItem(OrderManager.GetOrderStatusName(orderStatus.OrderStatusId), orderStatus.OrderStatusId.ToString()); this.ddlOrderStatusByNumberOfOrder.Items.Add(item2); } this.ddlPaymentStatusByNumberOfOrder.Items.Clear(); ListItem itemPaymentStatusByNumberOfOrder = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlPaymentStatusByNumberOfOrder.Items.Add(itemPaymentStatusByNumberOfOrder); foreach (PaymentStatus paymentStatus in paymentStatuses) { ListItem item2 = new ListItem(PaymentStatusManager.GetPaymentStatusName(paymentStatus.PaymentStatusId), paymentStatus.PaymentStatusId.ToString()); this.ddlPaymentStatusByNumberOfOrder.Items.Add(item2); } this.ddlShippingStatusByNumberOfOrder.Items.Clear(); ListItem itemShippingStatusByNumberOfOrder = new ListItem(GetLocaleResourceString("Admin.Common.All"), "0"); this.ddlShippingStatusByNumberOfOrder.Items.Add(itemShippingStatusByNumberOfOrder); foreach (ShippingStatus shippingStatus in shippingStatuses) { ListItem item2 = new ListItem(ShippingStatusManager.GetShippingStatusName(shippingStatus.ShippingStatusId), shippingStatus.ShippingStatusId.ToString()); this.ddlShippingStatusByNumberOfOrder.Items.Add(item2); } }
private void BindPaymentInfo(Order order) { if (order == null) { return; } string cardTypeDecrypted = SecurityHelper.Decrypt(order.CardType); if (!String.IsNullOrEmpty(cardTypeDecrypted)) { this.lblCardType.Text = Server.HtmlEncode(cardTypeDecrypted); } else { pnlCartType.Visible = false; } string cardNameDecrypted = SecurityHelper.Decrypt(order.CardName); if (!String.IsNullOrEmpty(cardNameDecrypted)) { this.lblCardName.Text = Server.HtmlEncode(cardNameDecrypted); } else { pnlCardName.Visible = false; } if (order.AllowStoringCreditCardNumber) { string cardNumberDecrypted = SecurityHelper.Decrypt(order.CardNumber); if (!String.IsNullOrEmpty(cardNumberDecrypted)) { this.lblCardNumber.Text = Server.HtmlEncode(cardNumberDecrypted); } else { pnlCardNumber.Visible = false; } } else { string maskedCreditCardNumberDecrypted = SecurityHelper.Decrypt(order.MaskedCreditCardNumber); if (!String.IsNullOrEmpty(maskedCreditCardNumberDecrypted)) { this.lblCardNumber.Text = Server.HtmlEncode(maskedCreditCardNumberDecrypted); } else { pnlCardNumber.Visible = false; } } if (order.AllowStoringCreditCardNumber) { string cardCVV2Decrypted = SecurityHelper.Decrypt(order.CardCVV2); this.lblCardCVV2.Text = Server.HtmlEncode(cardCVV2Decrypted); } else { pnlCardCVV2.Visible = false; } string cardExpirationMonthDecrypted = SecurityHelper.Decrypt(order.CardExpirationMonth); if (!String.IsNullOrEmpty(cardExpirationMonthDecrypted) && cardExpirationMonthDecrypted != "0") { this.lblCardExpirationMonth.Text = cardExpirationMonthDecrypted; } else { pnlCardExpiryMonth.Visible = false; } string cardExpirationYearDecrypted = SecurityHelper.Decrypt(order.CardExpirationYear); if (!String.IsNullOrEmpty(cardExpirationYearDecrypted) && cardExpirationYearDecrypted != "0") { this.lblCardExpirationYear.Text = cardExpirationYearDecrypted; } else { pnlCardExpiryYear.Visible = false; } this.lblPONumber.Text = Server.HtmlEncode(order.PurchaseOrderNumber); this.lblPaymentMethodName.Text = Server.HtmlEncode(order.PaymentMethodName); this.lblPaymentStatus.Text = PaymentStatusManager.GetPaymentStatusName(order.PaymentStatusID); this.btnCapture.Visible = OrderManager.CanCapture(order); this.btnMarkAsPaid.Visible = OrderManager.CanMarkOrderAsPaid(order); }