/// <summary>
        /// Handles the ItemDataBound event of the PaymentOptionList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.DataListItemEventArgs"/> instance containing the event data.</param>
        protected void PaymentOptionList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (e.Item.DataItem == null)
                {
                    return;
                }

                PaymentMethodDto.PaymentMethodRow listItem = ((PaymentMethodDto.PaymentMethodRow)((DataRowView)e.Item.DataItem).Row);

                // Check the item if it has been already selected
                if (ViewState["PaymentMethod"] != null)
                {
                    Guid selectedPayment = new Guid(ViewState["PaymentMethod"].ToString());
                    if (listItem.PaymentMethodId == selectedPayment)
                    {
                        GlobalRadioButton radioButton = (GlobalRadioButton)e.Item.FindControl("PaymentOption");
                        radioButton.Checked = true;
                    }
                }

                // Retrieve the Label control in the current DataListItem.
                PlaceHolder           optionPane  = (PlaceHolder)e.Item.FindControl("PaymentOptionHolder");
                System.Web.UI.Control paymentCtrl = StoreHelper.LoadPaymentPlugin(this, listItem.SystemKeyword);
                paymentCtrl.ID = listItem.SystemKeyword;
                paymentCtrl.EnableViewState = true;
                optionPane.Controls.Add(paymentCtrl);
                //TestPaymentOptionHolder.Controls.Add(paymentCtrl);
            }
        }
        /// <summary>
        /// Binds the shipping methods list.
        /// </summary>
        /// <param name="paymentRow">The payment row.</param>
        private void BindShippingMethodsList(PaymentMethodDto.PaymentMethodRow paymentRow)
        {
            List <ShippingMethodDto.ShippingMethodRow> leftShippings  = new List <ShippingMethodDto.ShippingMethodRow>();
            List <ShippingMethodDto.ShippingMethodRow> rightShippings = new List <ShippingMethodDto.ShippingMethodRow>();

            ShippingMethodDto dto = ShippingManager.GetShippingMethods(paymentRow != null ? paymentRow.LanguageId : LanguageCode, true);

            bool allToLeft = false;             // if true, then add all shipping methods to the left list

            if (paymentRow != null)
            {
                PaymentMethodDto.ShippingPaymentRestrictionRow[] restrictedShippingRows = paymentRow.GetShippingPaymentRestrictionRows();
                if (restrictedShippingRows != null && restrictedShippingRows.Length > 0)
                {
                    foreach (ShippingMethodDto.ShippingMethodRow shippingMethodRow in dto.ShippingMethod)
                    {
                        bool found = false;
                        foreach (PaymentMethodDto.ShippingPaymentRestrictionRow restrictedShippingRow in restrictedShippingRows)
                        {
                            if (shippingMethodRow.ShippingMethodId == restrictedShippingRow.ShippingMethodId)
                            {
                                found = true;
                                break;
                            }
                        }

                        if (found)
                        {
                            rightShippings.Add(shippingMethodRow);
                        }
                        else
                        {
                            leftShippings.Add(shippingMethodRow);
                        }
                    }

                    ShippingMethodsList.LeftDataSource  = leftShippings;
                    ShippingMethodsList.RightDataSource = rightShippings;
                }
                else
                {
                    // add all shipping methods to the left list
                    allToLeft = true;
                }
            }
            else
            {
                allToLeft = true;
            }

            if (allToLeft)
            {
                // add all shipping methods to the left list
                ShippingMethodsList.LeftDataSource = dto.ShippingMethod;
            }

            ShippingMethodsList.DataBind();
        }
        /// <summary>
        /// Creates the settings.
        /// </summary>
        /// <param name="methodRow">The method row.</param>
        /// <returns></returns>
        private Dictionary <string, string> CreateSettings(PaymentMethodDto.PaymentMethodRow methodRow)
        {
            Dictionary <string, string> settings = new Dictionary <string, string>();

            PaymentMethodDto.PaymentMethodParameterRow[] rows = methodRow.GetPaymentMethodParameterRows();
            foreach (PaymentMethodDto.PaymentMethodParameterRow row in rows)
            {
                settings.Add(row.Parameter, row.Value);
            }

            return(settings);
        }
Example #4
0
        public DinteroPaymentOption()
        {
            _paymentMethod = DinteroConfiguration.GetDinteroPaymentMethod()?.PaymentMethod?.FirstOrDefault();

            if (_paymentMethod == null)
            {
                return;
            }

            PaymentMethodId = _paymentMethod.PaymentMethodId;
            SystemKeyword   = _paymentMethod.SystemKeyword;
            Name            = _paymentMethod.Name;
            Description     = _paymentMethod.Description;
        }
        public EpayPaymentOption(IOrderGroupFactory orderGroupFactory)
        {
            _orderGroupFactory = orderGroupFactory;
            _paymentMethod     = EpayConfiguration.GetEpayPaymentMethod()?.PaymentMethod?.FirstOrDefault();

            if (_paymentMethod == null)
            {
                return;
            }

            PaymentMethodId = _paymentMethod.PaymentMethodId;
            SystemKeyword   = _paymentMethod.SystemKeyword;
            Name            = _paymentMethod.Name;
            Description     = _paymentMethod.Description;
        }
        /// <summary>
        /// Validates the data.
        /// </summary>
        /// <returns></returns>
        public bool ValidateData()
        {
            bool isValid = false;

            PaymentMethodDto.PaymentMethodRow paymentRow = PaymentMethod;
            if (paymentRow != null)
            {
                IPaymentOption po = FindPaymentControl(paymentRow.SystemKeyword);
                if (po != null)
                {
                    isValid = po.ValidateData();
                }
            }

            return(isValid & RadioButtonsPaymentCustomValidator.IsValid);
        }
        /// <summary>
        /// Binds the form.
        /// </summary>
        private void BindForm()
        {
            // Bind Languages
            BindLanguages();

            // bind available payment gateway classes
            BindClassNames();

            if (_PaymentMethodDto != null && _PaymentMethodDto.PaymentMethod.Count > 0)
            {
                try
                {
                    PaymentMethodDto.PaymentMethodRow paymentRow = _PaymentMethodDto.PaymentMethod[0];

                    this.lblPaymentMethodId.Text      = paymentRow.PaymentMethodId.ToString();
                    this.tbName.Text                  = paymentRow.Name;
                    this.tbDescription.Text           = paymentRow.Description;
                    this.tbSystemName.Text            = paymentRow.SystemKeyword;
                    this.tbSortOrder.Text             = paymentRow.Ordering.ToString();
                    this.IsActive.IsSelected          = paymentRow.IsActive;
                    this.IsDefault.IsSelected         = paymentRow.IsDefault;
                    this.SupportsRecurring.IsSelected = paymentRow.SupportsRecurring;

                    ManagementHelper.SelectListItem(ddlLanguage, paymentRow.LanguageId);
                    ManagementHelper.SelectListItem(ddlClassName, paymentRow.ClassName);

                    // do not allow to change system name
                    this.tbSystemName.Enabled = false;

                    // set initial state of dual list
                    BindShippingMethodsList(paymentRow);
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage("Error during binding form: " + ex.Message);
                }
            }
            else
            {
                // set default form values
                this.tbSortOrder.Text     = "0";
                this.tbSystemName.Enabled = true;

                BindShippingMethodsList(null);
            }
        }
        /// <summary>
        /// Binds the payment config.
        /// </summary>
        private void BindPaymentConfig()
        {
            //this.phAdditionalParameters.EnableViewState = false;

            if (this.phAdditionalParameters.Controls.Count > 0)
            {
                return;
            }

            if (_PaymentMethodDto != null && _PaymentMethodDto.PaymentMethod.Count > 0)
            {
                try
                {
                    PaymentMethodDto.PaymentMethodRow paymentRow = _PaymentMethodDto.PaymentMethod[0];
                    // Load dynamic configuration form
                    System.Web.UI.Control ctrl = null;
                    String mainPath            = string.Concat(_PaymentGatewayConfigurationBasePath, paymentRow.SystemKeyword, _PaymentGatewayConfigurationFileName);
                    if (System.IO.File.Exists(Server.MapPath(mainPath)))
                    {
                        ctrl = base.LoadControl(mainPath);
                    }
                    else
                    {
                        ctrl = base.LoadControl(string.Concat(_PaymentGatewayConfigurationBasePath, "Generic", _PaymentGatewayConfigurationFileName));
                    }

                    if (ctrl != null)
                    {
                        ctrl.ID = paymentRow.SystemKeyword;
                        IGatewayControl tmpCtrl = (IGatewayControl)ctrl;
                        tmpCtrl.LoadObject(_PaymentMethodDto);
                        tmpCtrl.ValidationGroup = "vg" + paymentRow.SystemKeyword;

                        this.phAdditionalParameters.Controls.Add(ctrl);

                        ctrl.DataBind();
                    }
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage("Error during binding additional gateway parameters: " + ex.Message);
                    return;
                }
            }
        }
Example #9
0
        public PayooPaymentMethod(IOrderGroupFactory orderGroupFactory)
        {
            _orderGroupFactory = orderGroupFactory;

            var paymentMethodDto = PayooConfiguration.GetPayooPaymentMethod();

            _paymentMethod = paymentMethodDto?.PaymentMethod?.FirstOrDefault();

            if (_paymentMethod == null)
            {
                return;
            }

            PaymentMethodId = _paymentMethod.PaymentMethodId;
            SystemKeyword   = _paymentMethod.SystemKeyword;
            Name            = _paymentMethod.Name;
            Description     = _paymentMethod.Description;
        }
        private void Create(PaymentMethodInfo paymentMethodInfo, Guid guid, string languageId)
        {
            PaymentMethodDto paymentMethod = new PaymentMethodDto();

            PaymentMethodDto.PaymentMethodRow paymentMethodRow = paymentMethod.PaymentMethod.NewPaymentMethodRow();
            paymentMethodRow[paymentMethod.PaymentMethod.PaymentMethodIdColumn] = guid;
            paymentMethodRow[paymentMethod.PaymentMethod.ApplicationIdColumn]   = AppContext.Current.ApplicationId;
            paymentMethodRow[paymentMethod.PaymentMethod.NameColumn]            = paymentMethodInfo.Name;
            paymentMethodRow[paymentMethod.PaymentMethod.DescriptionColumn]     = paymentMethodInfo.Description;
            paymentMethodRow[paymentMethod.PaymentMethod.LanguageIdColumn]      = languageId;
            paymentMethodRow[paymentMethod.PaymentMethod.SystemKeywordColumn]   = paymentMethodInfo.SystemKeyword;
            paymentMethodRow[paymentMethod.PaymentMethod.IsActiveColumn]        = false;
            paymentMethodRow[paymentMethod.PaymentMethod.IsDefaultColumn]       = false;
            paymentMethodRow[paymentMethod.PaymentMethod.ClassNameColumn]       = paymentMethodInfo.ClassName;
            paymentMethodRow[paymentMethod.PaymentMethod.PaymentImplementationClassNameColumn] = paymentMethodInfo.PaymentClassName;
            paymentMethodRow[paymentMethod.PaymentMethod.SupportsRecurringColumn] = false;
            paymentMethodRow[paymentMethod.PaymentMethod.OrderingColumn]          = paymentMethodInfo.SortOrder;
            paymentMethodRow[paymentMethod.PaymentMethod.CreatedColumn]           = FrameworkContext.Current.CurrentDateTime;
            paymentMethodRow[paymentMethod.PaymentMethod.ModifiedColumn]          = FrameworkContext.Current.CurrentDateTime;
            paymentMethod.PaymentMethod.Rows.Add(paymentMethodRow);
            PaymentManager.SavePayment(paymentMethod);
        }
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="context">The context.</param>
        public void SaveChanges(IDictionary context)
        {
            PaymentMethodDto dto = (PaymentMethodDto)context[_PaymentMethodDtoString];

            PaymentMethodDto.PaymentMethodRow paymentRow = null;

            if (dto == null)
            {
                // dto must be created in base payment control that holds tabs
                return;
            }

            // create the row if it doesn't exist; or update its modified date if it exists
            if (dto.PaymentMethod.Count > 0)
            {
                paymentRow = dto.PaymentMethod[0];
            }
            else
            {
                paymentRow = dto.PaymentMethod.NewPaymentMethodRow();
                paymentRow.PaymentMethodId = Guid.NewGuid();
                paymentRow.ApplicationId   = OrderConfiguration.Instance.ApplicationId;
                paymentRow.Created         = DateTime.UtcNow;
                paymentRow.SystemKeyword   = this.tbSystemName.Text;
            }

            // fill the row with values
            paymentRow.Modified          = DateTime.UtcNow;
            paymentRow.Name              = tbName.Text;
            paymentRow.ClassName         = ddlClassName.SelectedValue;
            paymentRow.LanguageId        = ddlLanguage.SelectedValue;
            paymentRow.Description       = tbDescription.Text;
            paymentRow.IsActive          = this.IsActive.IsSelected;
            paymentRow.IsDefault         = this.IsDefault.IsSelected;
            paymentRow.Ordering          = Int32.Parse(this.tbSortOrder.Text);
            paymentRow.SupportsRecurring = this.SupportsRecurring.IsSelected;

            // add the row to the dto
            if (paymentRow.RowState == DataRowState.Detached)
            {
                dto.PaymentMethod.Rows.Add(paymentRow);
            }

            // populate shipping methods restrictions

            // a). delete rows from dto that are not selected
            foreach (PaymentMethodDto.ShippingPaymentRestrictionRow rowTmp in paymentRow.GetShippingPaymentRestrictionRows())
            {
                bool found = false;
                foreach (ListItem item in ShippingMethodsList.RightItems)
                {
                    if (String.Compare(item.Value, rowTmp.ShippingMethodId.ToString(), true) == 0 && rowTmp.RestrictShippingMethods)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    rowTmp.Delete();
                }
            }

            // b). add selected rows to dto
            foreach (ListItem item in ShippingMethodsList.RightItems)
            {
                bool exists = false;
                foreach (PaymentMethodDto.ShippingPaymentRestrictionRow rowTmp in paymentRow.GetShippingPaymentRestrictionRows())
                {
                    if (String.Compare(item.Value, rowTmp.ShippingMethodId.ToString(), true) == 0 && rowTmp.RestrictShippingMethods)
                    {
                        exists = true;
                        break;
                    }
                }

                if (!exists)
                {
                    PaymentMethodDto.ShippingPaymentRestrictionRow restrictedRow = dto.ShippingPaymentRestriction.NewShippingPaymentRestrictionRow();
                    restrictedRow.ShippingMethodId        = new Guid(item.Value);
                    restrictedRow.PaymentMethodId         = paymentRow.PaymentMethodId;
                    restrictedRow.RestrictShippingMethods = true;

                    // add the row to the dto
                    dto.ShippingPaymentRestriction.Rows.Add(restrictedRow);
                }
            }
        }
        /// <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
                }
            }
        }
        //Exercise (E2) Do CheckOut
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            // ToDo: declare a variable for CartHelper
            CartHelper ch = new CartHelper(Cart.DefaultName);

            int orderAddressId = 0;

            // ToDo: Addresses (an If-Else)
            if (CustomerContext.Current.CurrentContact == null)
            {
                // Anonymous... one way of "doing it"... for example, if no other address exist
                orderAddressId = ch.Cart.OrderAddresses.Add(
                    new OrderAddress
                {
                    CountryCode        = "SWE",
                    CountryName        = "Sweden",
                    Name               = "SomeCustomerAddress",
                    DaytimePhoneNumber = "123456",
                    FirstName          = "John",
                    LastName           = "Smith",
                    Email              = "*****@*****.**",
                });
            }
            else
            {
                // Logged in
                if (CustomerContext.Current.CurrentContact.PreferredShippingAddress == null)
                {
                    // no pref. address set... so we set one for the contact
                    CustomerAddress newCustAddress =
                        CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId);
                    newCustAddress.AddressType        = CustomerAddressTypeEnum.Shipping; // mandatory
                    newCustAddress.ContactId          = CustomerContext.Current.CurrentContact.PrimaryKeyId;
                    newCustAddress.CountryCode        = "SWE";
                    newCustAddress.CountryName        = "Sweden";
                    newCustAddress.Name               = "new customer address"; // mandatory
                    newCustAddress.DaytimePhoneNumber = "123456";
                    newCustAddress.FirstName          = CustomerContext.Current.CurrentContact.FirstName;
                    newCustAddress.LastName           = CustomerContext.Current.CurrentContact.LastName;
                    newCustAddress.Email              = "*****@*****.**";

                    // note: Line1 & City is what is shown in CM at a few places... not the Name
                    CustomerContext.Current.CurrentContact.AddContactAddress(newCustAddress);
                    CustomerContext.Current.CurrentContact.SaveChanges();

                    // ... needs to be in this order
                    CustomerContext.Current.CurrentContact.PreferredShippingAddress = newCustAddress;
                    CustomerContext.Current.CurrentContact.SaveChanges(); // need this ...again

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(new OrderAddress(newCustAddress));
                }
                else
                {
                    // there is a preferred address set (and, a fourth alternative exists... do later )
                    OrderAddress orderAddress =
                        new OrderAddress(CustomerContext.Current.CurrentContact.PreferredShippingAddress);

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(orderAddress);
                }
            }

            // Depending how it was created...
            OrderAddress address = ch.FindAddressById(orderAddressId.ToString());

            // ToDo: Define Shipping
            ShippingMethodDto.ShippingMethodRow theShip =
                ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First();

            int shippingId = ch.Cart.OrderForms[0].Shipments.Add(
                new Shipment
            {                                          // ...removing anything?
                ShippingAddressId      = address.Name, // note: use no custom prefixes
                ShippingMethodId       = theShip.ShippingMethodId,
                ShippingMethodName     = theShip.Name,
                ShipmentTotal          = theShip.BasePrice,
                ShipmentTrackingNumber = "My tracking number",
            });

            // get the Shipping ... check to see if the Shipping knows about the LineItem
            Shipment firstOrderShipment = ch.Cart.OrderForms[0].Shipments.FirstOrDefault();

            // First (and only) OrderForm
            LineItemCollection lineItems = ch.Cart.OrderForms[0].LineItems;

            // ...basic now... one OrderForm - one Shipping
            foreach (LineItem lineItem in lineItems)
            {
                int index = lineItems.IndexOf(lineItem);
                if ((firstOrderShipment != null) && (index != -1))
                {
                    firstOrderShipment.AddLineItemIndex(index, lineItem.Quantity);
                }
            }


            // Execute the "Shipping & Taxes - WF" (CartPrepare) ... and take care of the return object
            WorkflowResults resultPrepare     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartPrepareWorkflowName);
            List <string>   wfMessagesPrepare = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultPrepare));


            // ToDo: Define Shipping
            PaymentMethodDto.PaymentMethodRow thePay = PaymentManager.GetPaymentMethod(model.SelectedPayId).PaymentMethod.First();
            Payment firstOrderPayment = ch.Cart.OrderForms[0].Payments.AddNew(typeof(OtherPayment));

            // ... need both below
            firstOrderPayment.Amount            = firstOrderShipment.SubTotal + firstOrderShipment.ShipmentTotal; // will change...
            firstOrderPayment.BillingAddressId  = address.Name;
            firstOrderPayment.PaymentMethodId   = thePay.PaymentMethodId;
            firstOrderPayment.PaymentMethodName = thePay.Name;
            // ch.Cart.CustomerName = "John Smith"; // ... this line overwrites what´s in there, if logged in


            // Execute the "Payment activation - WF" (CartCheckout) ... and take care of the return object
            // ...activates the gateway (same for shipping)
            WorkflowResults resultCheckout     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartCheckOutWorkflowName, false);
            List <string>   wfMessagesCheckout = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultCheckout));
            //ch.RunWorkflow("CartValidate") ... can see this (or variations)

            string        trackingNumber = String.Empty;
            PurchaseOrder purchaseOrder  = null;

            // Add a transaction scope and convert the cart to PO
            using (var scope = new Mediachase.Data.Provider.TransactionScope())
            {
                purchaseOrder = ch.Cart.SaveAsPurchaseOrder();
                ch.Cart.Delete();
                ch.Cart.AcceptChanges();
                trackingNumber = purchaseOrder.TrackingNumber;
                scope.Complete();
            }

            // Housekeeping below (Shipping release, OrderNotes and save the order)
            OrderStatusManager.ReleaseOrderShipment(purchaseOrder.OrderForms[0].Shipments[0]);

            OrderNotesManager.AddNoteToPurchaseOrder(purchaseOrder, DateTime.UtcNow.ToShortDateString() + " released for shipping", OrderNoteTypes.System, CustomerContext.Current.CurrentContactId);

            purchaseOrder.ExpirationDate = DateTime.UtcNow.AddDays(30);
            purchaseOrder.Status         = OrderStatus.InProgress.ToString();

            purchaseOrder.AcceptChanges(); // need this here, else no "order-note" persisted


            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Service.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            string passingValue = trackingNumber;

            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }