public PaymentInfo GetPaymentInfo()
 {
     PaymentInfo paymentInfo = new PaymentInfo();
     paymentInfo.CreditCardName = this.creditCardName.Text;
     paymentInfo.CreditCardNumber = this.creditCardNumber.Text;
     paymentInfo.CreditCardExpireYear = int.Parse((this.creditCardExpireYear.SelectedValue == null) ? "0" : this.creditCardExpireYear.SelectedValue);
     paymentInfo.CreditCardExpireMonth = int.Parse((this.creditCardExpireMonth.SelectedValue == null) ? "0" : this.creditCardExpireMonth.SelectedValue);
     paymentInfo.CreditCardCvv2 = this.creditCardCVV2.Text;
     return paymentInfo;
 }
Esempio n. 2
0
 public PaymentInfo GetPaymentInfo()
 {
     PaymentInfo paymentInfo = new PaymentInfo();
     paymentInfo.CreditCardType = string.Empty;
     paymentInfo.CreditCardName = string.Empty;
     paymentInfo.CreditCardNumber = string.Empty;
     paymentInfo.CreditCardExpireYear = 0;
     paymentInfo.CreditCardExpireMonth = 0;
     paymentInfo.CreditCardCvv2 = string.Empty;
     return paymentInfo;
 }
Esempio n. 3
0
 public PaymentInfo GetPaymentInfo()
 {
     PaymentInfo paymentInfo = new PaymentInfo();
     int creditCardTypeId = int.Parse(this.ddlCreditCardType.SelectedItem.Value);
     CreditCardType creditCardType = CreditCardTypeManager.GetCreditCardTypeById(creditCardTypeId);
     if (creditCardType == null)
         throw new NopException("Couldn't load credit card type");
     paymentInfo.CreditCardType = creditCardType.SystemKeyword;
     paymentInfo.CreditCardName = this.creditCardName.Text;
     paymentInfo.CreditCardNumber = this.creditCardNumber.Text;
     paymentInfo.CreditCardExpireYear = int.Parse((this.creditCardExpireYear.SelectedValue == null) ? "0" : this.creditCardExpireYear.SelectedValue);
     paymentInfo.CreditCardExpireMonth = int.Parse((this.creditCardExpireMonth.SelectedValue == null) ? "0" : this.creditCardExpireMonth.SelectedValue);
     paymentInfo.CreditCardCvv2 = this.creditCardCVV2.Text;
     return paymentInfo;
 }
Esempio n. 4
0
 /// <summary>
 /// Process payment
 /// </summary>
 /// <param name="paymentInfo">Payment info required for an order processing</param>
 /// <param name="customer">Customer</param>
 /// <param name="OrderGuid">Unique order identifier</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public static void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid OrderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     if (paymentInfo.OrderTotal == decimal.Zero)
     {
         processPaymentResult.Error = string.Empty;
         processPaymentResult.FullError = string.Empty;
         processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
     }
     else
     {
         PaymentMethod paymentMethod = PaymentMethodManager.GetPaymentMethodByID(paymentInfo.PaymentMethodID);
         if (paymentMethod == null)
             throw new NopException("Payment method couldn't be loaded");
         IPaymentMethod iPaymentMethod = Activator.CreateInstance(Type.GetType(paymentMethod.ClassName)) as IPaymentMethod;
         iPaymentMethod.ProcessPayment(paymentInfo, customer, OrderGuid, ref processPaymentResult);
     }
 }
        protected void btnNextStep_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    PayPalExpressPaymentProcessor payPalExpress = new PayPalExpressPaymentProcessor();
                    string token = CommonHelper.QueryString("token");
                    PaypalPayer payer = payPalExpress.GetExpressCheckout(token);
                    if (string.IsNullOrEmpty(payer.PayerID))
                        throw new NopException("Payer ID is not set");

                    PaymentInfo paymentInfo = new PaymentInfo();

                    PaymentMethod paypalExpressPaymentMethod = PaymentMethodManager.GetPaymentMethodBySystemKeyword("PayPalExpress");

                    paymentInfo.PaymentMethodId = paypalExpressPaymentMethod.PaymentMethodId;
                    paymentInfo.BillingAddress = NopContext.Current.User.BillingAddress;
                    paymentInfo.ShippingAddress = NopContext.Current.User.ShippingAddress;
                    paymentInfo.PaypalPayerId = payer.PayerID;
                    paymentInfo.PaypalToken = token;
                    paymentInfo.CustomerLanguage = NopContext.Current.WorkingLanguage;
                    paymentInfo.CustomerCurrency = NopContext.Current.WorkingCurrency;

                    int orderId = 0;
                    string result = OrderManager.PlaceOrder(paymentInfo, NopContext.Current.User, out orderId);

                    Order order = OrderManager.GetOrderById(orderId);
                    if (!String.IsNullOrEmpty(result))
                    {
                        lConfirmOrderError.Text = Server.HtmlEncode(result);
                        btnNextStep.Visible = false;
                        return;
                    }
                    else
                        PaymentManager.PostProcessPayment(order);
                    Response.Redirect("~/checkoutcompleted.aspx");
                }
                catch (Exception exc)
                {
                    LogManager.InsertLog(LogTypeEnum.OrderError, exc.Message, exc);
                    lConfirmOrderError.Text = Server.HtmlEncode(exc.ToString());
                    btnNextStep.Visible = false;
                }
            }
        }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            XmlTransaction sxml = new XmlTransaction(XmlPaymentSettings.TestMode ? XmlTransaction.MODE_TEST : XmlTransaction.MODE_LIVE, SecurePaySettings.MerchantId, SecurePaySettings.MerchantPassword, ID);
            bool success = false;
            string code = "";

            if(XmlPaymentSettings.AuthorizeOnly)
            {
                success = sxml.processPreauth(paymentInfo.OrderTotal, orderGuid.ToString(), paymentInfo.CreditCardNumber, paymentInfo.CreditCardExpireMonth.ToString("D2"), paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2), paymentInfo.CreditCardCvv2.ToString());
            }
            else
            {
                success = sxml.processCredit(paymentInfo.OrderTotal, orderGuid.ToString(), paymentInfo.CreditCardNumber, paymentInfo.CreditCardExpireMonth.ToString("D2"), paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2), paymentInfo.CreditCardCvv2.ToString());
            }

            code = sxml["response_code"];

            if (!success)
            {
                processPaymentResult.Error = String.Format("Declined ({0})", code);
                processPaymentResult.FullError = sxml.Error;
            }
            else
            {
                if(XmlPaymentSettings.AuthorizeOnly)
                {
                    processPaymentResult.AuthorizationTransactionCode = (XmlPaymentSettings.AuthorizeOnly ? sxml["preauth_id"] : "");
                    processPaymentResult.AuthorizationTransactionId = sxml["transaction_id"];
                    processPaymentResult.AuthorizationTransactionResult = String.Format("Approved ({0})", code);
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                }
                else
                {
                    processPaymentResult.CaptureTransactionId = sxml["transaction_id"];
                    processPaymentResult.CaptureTransactionResult = String.Format("Approved ({0})", code);
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                }
            }
        }
Esempio n. 7
0
		/// <summary>
		/// Places an order
		/// </summary>
		/// <param name="paymentInfo">Payment info</param>
		/// <param name="customer">Customer</param>
		/// <param name="OrderID">Order identifier</param>
		/// <returns>The error status, or String.Empty if no errors</returns>
		public static string PlaceOrder(PaymentInfo paymentInfo, Customer customer, out int OrderID)
		{
			Guid OrderGuid = Guid.NewGuid();
			return PlaceOrder(paymentInfo, customer, OrderGuid, out OrderID);
		}
Esempio n. 8
0
        /// <summary>
        /// Places an order
        /// </summary>
        /// <param name="paymentInfo">Payment info</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Order GUID to use</param>
        /// <param name="orderId">Order identifier</param>
        /// <returns>The error status, or String.Empty if no errors</returns>
        public string PlaceOrder(PaymentInfo paymentInfo, Customer customer, 
            Guid orderGuid, out int orderId)
        {
            orderId = 0;
            var processPaymentResult = new ProcessPaymentResult();

            var customerService = IoC.Resolve<ICustomerService>();
            var shoppingCartService = IoC.Resolve<IShoppingCartService>();
            var taxService = IoC.Resolve<ITaxService>();
            var currencyService = IoC.Resolve<ICurrencyService>();
            var shippingService= IoC.Resolve<IShippingService>();
            var paymentService = IoC.Resolve<IPaymentService>();
            var productService = IoC.Resolve<IProductService>();
            var discountService = IoC.Resolve<IDiscountService>();
            var localizationManager = IoC.Resolve<ILocalizationManager>();
            var messageService = IoC.Resolve<IMessageService>();
            var customerActivityService = IoC.Resolve<ICustomerActivityService>();
            var smsService = IoC.Resolve<ISMSService>();
            var logService = IoC.Resolve<ILogService>();

            try
            {
                if (customer == null)
                    throw new ArgumentNullException("customer");

                if (customer.IsGuest && !customerService.AnonymousCheckoutAllowed)
                    throw new NopException("Anonymous checkout is not allowed");

                // This is a check to customer email address which is important to be valid.
                if (!CommonHelper.IsValidEmail(customer.Email)) {
                    throw new NopException("Email is not valid");
                }

                if (paymentInfo == null)
                    throw new ArgumentNullException("paymentInfo");

                Order initialOrder = null;
                if (paymentInfo.IsRecurringPayment)
                {
                    initialOrder = GetOrderById(paymentInfo.InitialOrderId);
                    if (initialOrder == null)
                        throw new NopException("Initial order could not be loaded");
                }

                if (!paymentInfo.IsRecurringPayment)
                {
                    if (paymentInfo.BillingAddress == null)
                        throw new NopException("Billing address not provided");

                    // Billing address email is never asked in the first place, so system must not check its validity
                    //if (!CommonHelper.IsValidEmail(paymentInfo.BillingAddress.Email))
                    //{
                    //    throw new NopException("Email is not valid");
                    //}
                }

                if (paymentInfo.IsRecurringPayment)
                {
                    paymentInfo.PaymentMethodId = initialOrder.PaymentMethodId;
                }

                paymentInfo.CreditCardType = CommonHelper.EnsureNotNull(paymentInfo.CreditCardType);
                paymentInfo.CreditCardName = CommonHelper.EnsureNotNull(paymentInfo.CreditCardName);
                paymentInfo.CreditCardName = CommonHelper.EnsureMaximumLength(paymentInfo.CreditCardName, 100);
                paymentInfo.CreditCardName = paymentInfo.CreditCardName.Trim();
                paymentInfo.CreditCardNumber = CommonHelper.EnsureNotNull(paymentInfo.CreditCardNumber);
                paymentInfo.CreditCardNumber = paymentInfo.CreditCardNumber.Trim();
                paymentInfo.CreditCardCvv2 = CommonHelper.EnsureNotNull(paymentInfo.CreditCardCvv2);
                paymentInfo.CreditCardCvv2 = paymentInfo.CreditCardCvv2.Trim();
                paymentInfo.PaypalToken = CommonHelper.EnsureNotNull(paymentInfo.PaypalToken);
                paymentInfo.PaypalPayerId = CommonHelper.EnsureNotNull(paymentInfo.PaypalPayerId);
                paymentInfo.GoogleOrderNumber = CommonHelper.EnsureNotNull(paymentInfo.GoogleOrderNumber);
                paymentInfo.PurchaseOrderNumber = CommonHelper.EnsureNotNull(paymentInfo.PurchaseOrderNumber);

                ShoppingCart cart = null;
                if (!paymentInfo.IsRecurringPayment)
                {
                    cart = shoppingCartService.GetCustomerShoppingCart(customer.CustomerId, ShoppingCartTypeEnum.ShoppingCart);

                    //validate cart
                    var warnings = shoppingCartService.GetShoppingCartWarnings(cart, customer.CheckoutAttributes, true);
                    if (warnings.Count > 0)
                    {
                        StringBuilder warningsSb = new StringBuilder();
                        foreach (string warning in warnings)
                        {
                            warningsSb.Append(warning);
                            warningsSb.Append(";");
                        }
                        throw new NopException(warningsSb.ToString());
                    }

                    //validate individual cart items
                    foreach (var sci in cart)
                    {
                        var sciWarnings = shoppingCartService.GetShoppingCartItemWarnings(sci.ShoppingCartType,
                            sci.ProductVariantId, sci.AttributesXml,
                            sci.CustomerEnteredPrice, sci.Quantity);

                        if (sciWarnings.Count > 0)
                        {
                            var warningsSb = new StringBuilder();
                            foreach (string warning in sciWarnings)
                            {
                                warningsSb.Append(warning);
                                warningsSb.Append(";");
                            }
                            throw new NopException(warningsSb.ToString());
                        }
                    }
                }

                //tax type
                var customerTaxDisplayType = TaxDisplayTypeEnum.IncludingTax;
                if (!paymentInfo.IsRecurringPayment)
                {
                    if (taxService.AllowCustomersToSelectTaxDisplayType)
                        customerTaxDisplayType = customer.TaxDisplayType;
                    else
                        customerTaxDisplayType = taxService.TaxDisplayType;
                }
                else
                {
                    customerTaxDisplayType = initialOrder.CustomerTaxDisplayType;
                }

                //discount usage history
                var appliedDiscounts = new List<Discount>();

                //checkout attributes
                string checkoutAttributeDescription = string.Empty;
                string checkoutAttributesXml = string.Empty;
                if (!paymentInfo.IsRecurringPayment)
                {
                    checkoutAttributeDescription = CheckoutAttributeHelper.FormatAttributes(customer.CheckoutAttributes, customer, "<br />");
                    checkoutAttributesXml = customer.CheckoutAttributes;
                }
                else
                {
                    checkoutAttributeDescription = initialOrder.CheckoutAttributeDescription;
                    checkoutAttributesXml = initialOrder.CheckoutAttributesXml;
                }

                //sub total
                decimal orderSubTotalInclTax = decimal.Zero;
                decimal orderSubTotalExclTax = decimal.Zero;
                decimal orderSubtotalInclTaxInCustomerCurrency = decimal.Zero;
                decimal orderSubtotalExclTaxInCustomerCurrency = decimal.Zero;
                decimal orderSubTotalDiscountInclTax = decimal.Zero;
                decimal orderSubTotalDiscountExclTax = decimal.Zero;
                decimal orderSubTotalDiscountInclTaxInCustomerCurrency = decimal.Zero;
                decimal orderSubTotalDiscountExclTaxInCustomerCurrency = decimal.Zero;
                if (!paymentInfo.IsRecurringPayment)
                {
                    //sub total (incl tax)
                    decimal orderSubTotalDiscountAmount1 = decimal.Zero;
                    Discount orderSubTotalAppliedDiscount1 = null;
                    decimal subTotalWithoutDiscountBase1 = decimal.Zero;
                    decimal subTotalWithDiscountBase1 = decimal.Zero;
                    string subTotalError1 = shoppingCartService.GetShoppingCartSubTotal(cart, customer,
                        true, out orderSubTotalDiscountAmount1, out orderSubTotalAppliedDiscount1,
                        out subTotalWithoutDiscountBase1, out subTotalWithDiscountBase1);
                    orderSubTotalInclTax = subTotalWithoutDiscountBase1;
                    orderSubTotalDiscountInclTax =orderSubTotalDiscountAmount1;

                    //discount history
                    if (orderSubTotalAppliedDiscount1 != null && !appliedDiscounts.ContainsDiscount(orderSubTotalAppliedDiscount1.Name))
                        appliedDiscounts.Add(orderSubTotalAppliedDiscount1);

                    //sub total (excl tax)
                    decimal orderSubTotalDiscountAmount2 = decimal.Zero;
                    Discount orderSubTotalAppliedDiscount2 = null;
                    decimal subTotalWithoutDiscountBase2 = decimal.Zero;
                    decimal subTotalWithDiscountBase2 = decimal.Zero;
                    string subTotalError2 = shoppingCartService.GetShoppingCartSubTotal(cart, customer,
                        false, out orderSubTotalDiscountAmount2, out orderSubTotalAppliedDiscount2,
                        out subTotalWithoutDiscountBase2, out subTotalWithDiscountBase2);
                    orderSubTotalExclTax = subTotalWithoutDiscountBase2;
                    orderSubTotalDiscountExclTax = orderSubTotalDiscountAmount2;

                    if (!String.IsNullOrEmpty(subTotalError1) || !String.IsNullOrEmpty(subTotalError2))
                        throw new NopException("Sub total couldn't be calculated");

                    //in customer currency
                    orderSubtotalInclTaxInCustomerCurrency = currencyService.ConvertCurrency(orderSubTotalInclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                    orderSubtotalExclTaxInCustomerCurrency = currencyService.ConvertCurrency(orderSubTotalExclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                    orderSubTotalDiscountInclTaxInCustomerCurrency = currencyService.ConvertCurrency(orderSubTotalDiscountInclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                    orderSubTotalDiscountExclTaxInCustomerCurrency = currencyService.ConvertCurrency(orderSubTotalDiscountExclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                }
                else
                {
                    orderSubTotalInclTax = initialOrder.OrderSubtotalInclTax;
                    orderSubTotalExclTax = initialOrder.OrderSubtotalExclTax;

                    //in customer currency
                    orderSubtotalInclTaxInCustomerCurrency = initialOrder.OrderSubtotalInclTaxInCustomerCurrency;
                    orderSubtotalExclTaxInCustomerCurrency = initialOrder.OrderSubtotalExclTaxInCustomerCurrency;
                }

                //shipping info
                decimal orderWeight = decimal.Zero;
                bool shoppingCartRequiresShipping = false;
                if (!paymentInfo.IsRecurringPayment)
                {
                    orderWeight = shippingService.GetShoppingCartTotalWeight(cart, customer);
                    shoppingCartRequiresShipping = shippingService.ShoppingCartRequiresShipping(cart);
                    if (shoppingCartRequiresShipping)
                    {
                        if (paymentInfo.ShippingAddress == null)
                            throw new NopException("Shipping address is not provided");

                        // Billing address email is never asked in the first place, so system must not check its validity
                        //if (!CommonHelper.IsValidEmail(paymentInfo.ShippingAddress.Email))
                        //{
                        //    throw new NopException("Email is not valid");
                        //}
                    }
                }
                else
                {
                    orderWeight = initialOrder.OrderWeight;
                    if (initialOrder.ShippingStatus != ShippingStatusEnum.ShippingNotRequired)
                        shoppingCartRequiresShipping = true;
                }

                //shipping total
                decimal? orderShippingTotalInclTax = null;
                decimal? orderShippingTotalExclTax = null;
                decimal orderShippingInclTaxInCustomerCurrency = decimal.Zero;
                decimal orderShippingExclTaxInCustomerCurrency = decimal.Zero;
                if (!paymentInfo.IsRecurringPayment)
                {
                    decimal taxRate = decimal.Zero;
                    string shippingTotalError1 = string.Empty;
                    string shippingTotalError2 = string.Empty;
                    Discount shippingTotalDiscount = null;
                    orderShippingTotalInclTax = shippingService.GetShoppingCartShippingTotal(cart, customer, true, out taxRate, out shippingTotalDiscount, ref shippingTotalError1);
                    orderShippingTotalExclTax = shippingService.GetShoppingCartShippingTotal(cart, customer, false, ref shippingTotalError2);
                    if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue)
                        throw new NopException("Shipping total couldn't be calculated");
                    if (shippingTotalDiscount != null && !appliedDiscounts.ContainsDiscount(shippingTotalDiscount.Name))
                        appliedDiscounts.Add(shippingTotalDiscount);

                    //in customer currency
                    orderShippingInclTaxInCustomerCurrency = currencyService.ConvertCurrency(orderShippingTotalInclTax.Value, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                    orderShippingExclTaxInCustomerCurrency = currencyService.ConvertCurrency(orderShippingTotalExclTax.Value, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);

                }
                else
                {
                    orderShippingTotalInclTax = initialOrder.OrderShippingInclTax;
                    orderShippingTotalExclTax = initialOrder.OrderShippingExclTax;
                    orderShippingInclTaxInCustomerCurrency = initialOrder.OrderShippingInclTaxInCustomerCurrency;
                    orderShippingExclTaxInCustomerCurrency = initialOrder.OrderShippingExclTaxInCustomerCurrency;
                }

                //payment total
                decimal paymentAdditionalFeeInclTax = decimal.Zero;
                decimal paymentAdditionalFeeExclTax = decimal.Zero;
                decimal paymentAdditionalFeeInclTaxInCustomerCurrency = decimal.Zero;
                decimal paymentAdditionalFeeExclTaxInCustomerCurrency = decimal.Zero;
                if (!paymentInfo.IsRecurringPayment)
                {
                    string paymentAdditionalFeeError1 = string.Empty;
                    string paymentAdditionalFeeError2 = string.Empty;
                    decimal paymentAdditionalFee = paymentService.GetAdditionalHandlingFee(paymentInfo.PaymentMethodId);
                    paymentAdditionalFeeInclTax = taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, customer, ref paymentAdditionalFeeError1);
                    paymentAdditionalFeeExclTax = taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, customer, ref paymentAdditionalFeeError2);
                    if (!String.IsNullOrEmpty(paymentAdditionalFeeError1))
                        throw new NopException("Payment method fee couldn't be calculated");
                    if (!String.IsNullOrEmpty(paymentAdditionalFeeError2))
                        throw new NopException("Payment method fee couldn't be calculated");

                    //in customer currency
                    paymentAdditionalFeeInclTaxInCustomerCurrency = currencyService.ConvertCurrency(paymentAdditionalFeeInclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                    paymentAdditionalFeeExclTaxInCustomerCurrency = currencyService.ConvertCurrency(paymentAdditionalFeeExclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                }
                else
                {
                    paymentAdditionalFeeInclTax = initialOrder.PaymentMethodAdditionalFeeInclTax;
                    paymentAdditionalFeeExclTax = initialOrder.PaymentMethodAdditionalFeeExclTax;
                    paymentAdditionalFeeInclTaxInCustomerCurrency = initialOrder.PaymentMethodAdditionalFeeInclTaxInCustomerCurrency;
                    paymentAdditionalFeeExclTaxInCustomerCurrency = initialOrder.PaymentMethodAdditionalFeeExclTaxInCustomerCurrency;
                }

                //tax total
                decimal orderTaxTotal = decimal.Zero;
                decimal orderTaxInCustomerCurrency = decimal.Zero;
                string vatNumber = string.Empty;
                string taxRates = string.Empty;
                string taxRatesInCustomerCurrency = string.Empty;
                if (!paymentInfo.IsRecurringPayment)
                {
                    //tax amount
                    SortedDictionary<decimal, decimal> taxRatesDictionary = null;
                    string taxError = string.Empty;
                    orderTaxTotal = taxService.GetTaxTotal(cart,
                        paymentInfo.PaymentMethodId, customer, out taxRatesDictionary, ref taxError);
                    if (!String.IsNullOrEmpty(taxError))
                        throw new NopException("Tax total couldn't be calculated");

                    //in customer currency
                    orderTaxInCustomerCurrency = currencyService.ConvertCurrency(orderTaxTotal, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);

                    //VAT number
                    if (taxService.EUVatEnabled && customer.VatNumberStatus == VatNumberStatusEnum.Valid)
                    {
                        vatNumber = customer.VatNumber;
                    }

                    //tax rates
                    foreach (var kvp in taxRatesDictionary)
                    {
                        var taxRate = kvp.Key;
                        var taxValue = kvp.Value;

                        var taxValueInCustomerCurrency = currencyService.ConvertCurrency(taxValue, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);

                        taxRates += string.Format("{0}:{1};   ", taxRate.ToString(new CultureInfo("en-US")), taxValue.ToString(new CultureInfo("en-US")));
                        taxRatesInCustomerCurrency += string.Format("{0}:{1};   ", taxRate.ToString(new CultureInfo("en-US")), taxValueInCustomerCurrency.ToString(new CultureInfo("en-US")));
                    }
                }
                else
                {
                    orderTaxTotal = initialOrder.OrderTax;
                    orderTaxInCustomerCurrency = initialOrder.OrderTaxInCustomerCurrency;

                    //VAT number
                    //TODO: Possible BUG: VAT number status may have changed since original order was placed, probably best to recalculate tax or do some checks?
                    vatNumber = initialOrder.VatNumber;
                }

                //order total (and applied discounts, gift cards, reward points)
                decimal? orderTotal = null;
                decimal orderTotalInCustomerCurrency = decimal.Zero;
                decimal orderDiscountAmount = decimal.Zero;
                decimal orderDiscountInCustomerCurrency = decimal.Zero;
                List<AppliedGiftCard> appliedGiftCards = null;
                int redeemedRewardPoints = 0;
                decimal redeemedRewardPointsAmount = decimal.Zero;
                if (!paymentInfo.IsRecurringPayment)
                {
                    Discount orderAppliedDiscount = null;

                    bool useRewardPoints = customer.UseRewardPointsDuringCheckout;

                    orderTotal = shoppingCartService.GetShoppingCartTotal(cart,
                        paymentInfo.PaymentMethodId, customer,
                        out orderDiscountAmount, out orderAppliedDiscount,
                        out appliedGiftCards, useRewardPoints,
                        out redeemedRewardPoints, out redeemedRewardPointsAmount);
                    if (!orderTotal.HasValue)
                        throw new NopException("Order total couldn't be calculated");

                    //discount history
                    if (orderAppliedDiscount != null && !appliedDiscounts.ContainsDiscount(orderAppliedDiscount.Name))
                        appliedDiscounts.Add(orderAppliedDiscount);

                    //in customer currency
                    orderDiscountInCustomerCurrency = currencyService.ConvertCurrency(orderDiscountAmount, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                    orderTotalInCustomerCurrency = currencyService.ConvertCurrency(orderTotal.Value, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                }
                else
                {
                    orderDiscountAmount = initialOrder.OrderDiscount;
                    orderTotal = initialOrder.OrderTotal;

                    orderDiscountInCustomerCurrency = initialOrder.OrderDiscountInCustomerCurrency;
                    orderTotalInCustomerCurrency = initialOrder.OrderTotalInCustomerCurrency;
                }
                paymentInfo.OrderTotal = orderTotal.Value;

                //skip payment workflow if order total equals zero
                bool skipPaymentWorkflow = false;
                if (orderTotal.Value == decimal.Zero)
                {
                    skipPaymentWorkflow = true;
                }
                PaymentMethod paymentMethod = null;
                string paymentMethodName = string.Empty;
                if (!skipPaymentWorkflow)
                {
                    paymentMethod = paymentService.GetPaymentMethodById(paymentInfo.PaymentMethodId);
                    if (paymentMethod == null)
                        throw new NopException("Payment method couldn't be loaded");

                    if (!paymentMethod.IsActive)
                        throw new NopException("Payment method is not active");

                    paymentMethodName = paymentMethod.Name;
                }
                else
                {
                    paymentInfo.PaymentMethodId = 0;
                }

                string customerCurrencyCode = string.Empty;
                if (!paymentInfo.IsRecurringPayment)
                {
                    customerCurrencyCode = paymentInfo.CustomerCurrency.CurrencyCode;
                }
                else
                {
                    customerCurrencyCode = initialOrder.CustomerCurrencyCode;
                }

                //billing info
                string billingFirstName = string.Empty;
                string billingLastName = string.Empty;
                string billingPhoneNumber = string.Empty;
                string billingEmail = string.Empty;
                string billingFaxNumber = string.Empty;
                string billingCompany = string.Empty;
                string billingAddress1 = string.Empty;
                string billingAddress2 = string.Empty;
                string billingCity = string.Empty;
                string billingStateProvince = string.Empty;
                int billingStateProvinceId = 0;
                string billingZipPostalCode = string.Empty;
                string billingCountry = string.Empty;
                int billingCountryId = 0;
                if (!paymentInfo.IsRecurringPayment)
                {
                    var billingAddress = paymentInfo.BillingAddress;
                    billingFirstName = billingAddress.FirstName;
                    billingLastName = billingAddress.LastName;
                    billingPhoneNumber = billingAddress.PhoneNumber;
                    billingEmail = billingAddress.Email;
                    billingFaxNumber = billingAddress.FaxNumber;
                    billingCompany = billingAddress.Company;
                    billingAddress1 = billingAddress.Address1;
                    billingAddress2 = billingAddress.Address2;
                    billingCity = billingAddress.City;
                    if (billingAddress.StateProvince != null)
                    {
                        billingStateProvince = billingAddress.StateProvince.Name;
                        billingStateProvinceId = billingAddress.StateProvince.StateProvinceId;
                    }
                    billingZipPostalCode = billingAddress.ZipPostalCode;
                    if (billingAddress.Country != null)
                    {
                        billingCountry = billingAddress.Country.Name;
                        billingCountryId = billingAddress.Country.CountryId;

                        if (!billingAddress.Country.AllowsBilling)
                        {
                            throw new NopException(string.Format("{0} is not allowed for billing", billingCountry));
                        }
                    }
                }
                else
                {
                    billingFirstName = initialOrder.BillingFirstName;
                    billingLastName = initialOrder.BillingLastName;
                    billingPhoneNumber = initialOrder.BillingPhoneNumber;
                    billingEmail = initialOrder.BillingEmail;
                    billingFaxNumber = initialOrder.BillingFaxNumber;
                    billingCompany = initialOrder.BillingCompany;
                    billingAddress1 = initialOrder.BillingAddress1;
                    billingAddress2 = initialOrder.BillingAddress2;
                    billingCity = initialOrder.BillingCity;
                    billingStateProvince = initialOrder.BillingStateProvince;
                    billingStateProvinceId = initialOrder.BillingStateProvinceId;
                    billingZipPostalCode = initialOrder.BillingZipPostalCode;
                    billingCountry = initialOrder.BillingCountry;
                    billingCountryId = initialOrder.BillingCountryId;
                }

                //shipping info
                string shippingFirstName = string.Empty;
                string shippingLastName = string.Empty;
                string shippingPhoneNumber = string.Empty;
                string shippingEmail = string.Empty;
                string shippingFaxNumber = string.Empty;
                string shippingCompany = string.Empty;
                string shippingAddress1 = string.Empty;
                string shippingAddress2 = string.Empty;
                string shippingCity = string.Empty;
                string shippingStateProvince = string.Empty;
                int shippingStateProvinceId = 0;
                string shippingZipPostalCode = string.Empty;
                string shippingCountry = string.Empty;
                int shippingCountryId = 0;
                string shippingMethodName = string.Empty;
                int shippingRateComputationMethodId = 0;
                if (shoppingCartRequiresShipping)
                {
                    if (!paymentInfo.IsRecurringPayment)
                    {
                        var shippingAddress = paymentInfo.ShippingAddress;
                        if (shippingAddress != null)
                        {
                            shippingFirstName = shippingAddress.FirstName;
                            shippingLastName = shippingAddress.LastName;
                            shippingPhoneNumber = shippingAddress.PhoneNumber;
                            shippingEmail = shippingAddress.Email;
                            shippingFaxNumber = shippingAddress.FaxNumber;
                            shippingCompany = shippingAddress.Company;
                            shippingAddress1 = shippingAddress.Address1;
                            shippingAddress2 = shippingAddress.Address2;
                            shippingCity = shippingAddress.City;
                            if (shippingAddress.StateProvince != null)
                            {
                                shippingStateProvince = shippingAddress.StateProvince.Name;
                                shippingStateProvinceId = shippingAddress.StateProvince.StateProvinceId;
                            }
                            shippingZipPostalCode = shippingAddress.ZipPostalCode;
                            if (shippingAddress.Country != null)
                            {
                                shippingCountry = shippingAddress.Country.Name;
                                shippingCountryId = shippingAddress.Country.CountryId;

                                if (!shippingAddress.Country.AllowsShipping)
                                {
                                    throw new NopException(string.Format("{0} is not allowed for shipping", shippingCountry));
                                }
                            }
                            shippingMethodName = string.Empty;
                            var shippingOption = customer.LastShippingOption;
                            if (shippingOption != null)
                            {
                                shippingMethodName = shippingOption.Name;
                                shippingRateComputationMethodId = shippingOption.ShippingRateComputationMethodId;
                            }
                        }
                    }
                    else
                    {
                        shippingFirstName = initialOrder.ShippingFirstName;
                        shippingLastName = initialOrder.ShippingLastName;
                        shippingPhoneNumber = initialOrder.ShippingPhoneNumber;
                        shippingEmail = initialOrder.ShippingEmail;
                        shippingFaxNumber = initialOrder.ShippingFaxNumber;
                        shippingCompany = initialOrder.ShippingCompany;
                        shippingAddress1 = initialOrder.ShippingAddress1;
                        shippingAddress2 = initialOrder.ShippingAddress2;
                        shippingCity = initialOrder.ShippingCity;
                        shippingStateProvince = initialOrder.ShippingStateProvince;
                        shippingStateProvinceId = initialOrder.ShippingStateProvinceId;
                        shippingZipPostalCode = initialOrder.ShippingZipPostalCode;
                        shippingCountry = initialOrder.ShippingCountry;
                        shippingCountryId = initialOrder.ShippingCountryId;
                        shippingMethodName = initialOrder.ShippingMethod;
                        shippingRateComputationMethodId = initialOrder.ShippingRateComputationMethodId;
                    }
                }

                //customer language
                int customerLanguageId = 0;
                if (!paymentInfo.IsRecurringPayment)
                {
                    customerLanguageId = paymentInfo.CustomerLanguage.LanguageId;
                }
                else
                {
                    customerLanguageId = initialOrder.CustomerLanguageId;
                }

                //recurring or standard shopping cart
                bool isRecurringShoppingCart = false;
                if (!paymentInfo.IsRecurringPayment)
                {
                    isRecurringShoppingCart = cart.IsRecurring;
                    if (isRecurringShoppingCart)
                    {
                        int recurringCycleLength = 0;
                        int recurringCyclePeriod = 0;
                        int recurringTotalCycles = 0;
                        string recurringCyclesError = shoppingCartService.GetReccuringCycleInfo(cart, out recurringCycleLength, out recurringCyclePeriod, out recurringTotalCycles);
                        if (!string.IsNullOrEmpty(recurringCyclesError))
                        {
                            throw new NopException(recurringCyclesError);
                        }
                        paymentInfo.RecurringCycleLength = recurringCycleLength;
                        paymentInfo.RecurringCyclePeriod = recurringCyclePeriod;
                        paymentInfo.RecurringTotalCycles = recurringTotalCycles;
                    }
                }
                else
                {
                    isRecurringShoppingCart = true;
                }

                if (!skipPaymentWorkflow)
                {
                    //process payment
                    if (!paymentInfo.IsRecurringPayment)
                    {
                        if (isRecurringShoppingCart)
                        {
                            //recurring cart
                            var recurringPaymentType = paymentService.SupportRecurringPayments(paymentInfo.PaymentMethodId);
                            switch (recurringPaymentType)
                            {
                                case RecurringPaymentTypeEnum.NotSupported:
                                    throw new NopException("Recurring payments are not supported by selected payment method");
                                case RecurringPaymentTypeEnum.Manual:
                                case RecurringPaymentTypeEnum.Automatic:
                                    paymentService.ProcessRecurringPayment(paymentInfo, customer, orderGuid, ref processPaymentResult);
                                    break;
                                default:
                                    throw new NopException("Not supported recurring payment type");
                            }
                        }
                        else
                        {
                            //standard cart
                            paymentService.ProcessPayment(paymentInfo, customer, orderGuid, ref processPaymentResult);
                        }
                    }
                    else
                    {
                        if (isRecurringShoppingCart)
                        {
                            var recurringPaymentType = paymentService.SupportRecurringPayments(paymentInfo.PaymentMethodId);
                            switch (recurringPaymentType)
                            {
                                case RecurringPaymentTypeEnum.NotSupported:
                                    throw new NopException("Recurring payments are not supported by selected payment method");
                                case RecurringPaymentTypeEnum.Manual:
                                    paymentService.ProcessRecurringPayment(paymentInfo, customer, orderGuid, ref processPaymentResult);
                                    break;
                                case RecurringPaymentTypeEnum.Automatic:
                                    //payment is processed on payment gateway site
                                    break;
                                default:
                                    throw new NopException("Not supported recurring payment type");
                            }
                        }
                        else
                        {
                            throw new NopException("No recurring products");
                        }
                    }
                }
                else
                {
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                }

                //process order
                if (String.IsNullOrEmpty(processPaymentResult.Error))
                {
                    var shippingStatusEnum = ShippingStatusEnum.NotYetShipped;
                    if (!shoppingCartRequiresShipping)
                        shippingStatusEnum = ShippingStatusEnum.ShippingNotRequired;

                    //save order in data storage
                    //uncomment this line to support transactions
                    //using (var scope = new System.Transactions.TransactionScope())
                    {
                        var order = new Order()
                        {
                            OrderGuid = orderGuid,
                            CustomerId = customer.CustomerId,
                            CustomerLanguageId = customerLanguageId,
                            CustomerTaxDisplayTypeId = (int)customerTaxDisplayType,
                            CustomerIP = NopContext.Current.UserHostAddress,
                            OrderSubtotalInclTax = orderSubTotalInclTax,
                            OrderSubtotalExclTax = orderSubTotalExclTax,
                            OrderSubTotalDiscountInclTax = orderSubTotalDiscountInclTax,
                            OrderSubTotalDiscountExclTax = orderSubTotalDiscountExclTax,
                            OrderShippingInclTax = orderShippingTotalInclTax.Value,
                            OrderShippingExclTax = orderShippingTotalExclTax.Value,
                            PaymentMethodAdditionalFeeInclTax = paymentAdditionalFeeInclTax,
                            PaymentMethodAdditionalFeeExclTax = paymentAdditionalFeeExclTax,
                            TaxRates = taxRates,
                            OrderTax = orderTaxTotal,
                            OrderTotal = orderTotal.Value,
                            RefundedAmount = decimal.Zero,
                            OrderDiscount = orderDiscountAmount,
                            OrderSubtotalInclTaxInCustomerCurrency = orderSubtotalInclTaxInCustomerCurrency,
                            OrderSubtotalExclTaxInCustomerCurrency = orderSubtotalExclTaxInCustomerCurrency,
                            OrderSubTotalDiscountInclTaxInCustomerCurrency = orderSubTotalDiscountInclTaxInCustomerCurrency,
                            OrderSubTotalDiscountExclTaxInCustomerCurrency = orderSubTotalDiscountExclTaxInCustomerCurrency,
                            OrderShippingInclTaxInCustomerCurrency = orderShippingInclTaxInCustomerCurrency,
                            OrderShippingExclTaxInCustomerCurrency = orderShippingExclTaxInCustomerCurrency,
                            PaymentMethodAdditionalFeeInclTaxInCustomerCurrency = paymentAdditionalFeeInclTaxInCustomerCurrency,
                            PaymentMethodAdditionalFeeExclTaxInCustomerCurrency = paymentAdditionalFeeExclTaxInCustomerCurrency,
                            TaxRatesInCustomerCurrency = taxRatesInCustomerCurrency,
                            OrderTaxInCustomerCurrency = orderTaxInCustomerCurrency,
                            OrderTotalInCustomerCurrency = orderTotalInCustomerCurrency,
                            OrderDiscountInCustomerCurrency = orderDiscountInCustomerCurrency,
                            CheckoutAttributeDescription = checkoutAttributeDescription,
                            CheckoutAttributesXml = checkoutAttributesXml,
                            CustomerCurrencyCode = customerCurrencyCode,
                            OrderWeight = orderWeight,
                            AffiliateId = customer.AffiliateId,
                            OrderStatusId = (int)OrderStatusEnum.Pending,
                            AllowStoringCreditCardNumber = processPaymentResult.AllowStoringCreditCardNumber,
                            CardType = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Encrypt(paymentInfo.CreditCardType) : string.Empty,
                            CardName = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Encrypt(paymentInfo.CreditCardName) : string.Empty,
                            CardNumber = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Encrypt(paymentInfo.CreditCardNumber) : string.Empty,
                            MaskedCreditCardNumber = SecurityHelper.Encrypt(paymentService.GetMaskedCreditCardNumber(paymentInfo.CreditCardNumber)),
                            CardCvv2 = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Encrypt(paymentInfo.CreditCardCvv2) : string.Empty,
                            CardExpirationMonth = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Encrypt(paymentInfo.CreditCardExpireMonth.ToString()) : string.Empty,
                            CardExpirationYear = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Encrypt(paymentInfo.CreditCardExpireYear.ToString()) : string.Empty,
                            PaymentMethodId = paymentInfo.PaymentMethodId,
                            PaymentMethodName = paymentMethodName,
                            AuthorizationTransactionId = processPaymentResult.AuthorizationTransactionId,
                            AuthorizationTransactionCode = processPaymentResult.AuthorizationTransactionCode,
                            AuthorizationTransactionResult = processPaymentResult.AuthorizationTransactionResult,
                            CaptureTransactionId = processPaymentResult.CaptureTransactionId,
                            CaptureTransactionResult = processPaymentResult.CaptureTransactionResult,
                            SubscriptionTransactionId = processPaymentResult.SubscriptionTransactionId,
                            PurchaseOrderNumber = paymentInfo.PurchaseOrderNumber,
                            PaymentStatusId = (int)processPaymentResult.PaymentStatus,
                            PaidDate = null,
                            BillingFirstName = billingFirstName,
                            BillingLastName = billingLastName,
                            BillingPhoneNumber = billingPhoneNumber,
                            BillingEmail = billingEmail,
                            BillingFaxNumber = billingFaxNumber,
                            BillingCompany = billingCompany,
                            BillingAddress1 = billingAddress1,
                            BillingAddress2 = billingAddress2,
                            BillingCity = billingCity,
                            BillingStateProvince = billingStateProvince,
                            BillingStateProvinceId = billingStateProvinceId,
                            BillingZipPostalCode = billingZipPostalCode,
                            BillingCountry = billingCountry,
                            BillingCountryId = billingCountryId,
                            ShippingStatusId = (int)shippingStatusEnum,
                            ShippingFirstName = shippingFirstName,
                            ShippingLastName = shippingLastName,
                            ShippingPhoneNumber = shippingPhoneNumber,
                            ShippingEmail = shippingEmail,
                            ShippingFaxNumber = shippingFaxNumber,
                            ShippingCompany = shippingCompany,
                            ShippingAddress1 = shippingAddress1,
                            ShippingAddress2 = shippingAddress2,
                            ShippingCity = shippingCity,
                            ShippingStateProvince = shippingStateProvince,
                            ShippingStateProvinceId = shippingStateProvinceId,
                            ShippingZipPostalCode = shippingZipPostalCode,
                            ShippingCountry = shippingCountry,
                            ShippingCountryId = shippingCountryId,
                            ShippingMethod = shippingMethodName,
                            ShippingRateComputationMethodId = shippingRateComputationMethodId,
                            ShippedDate = null,
                            DeliveryDate = null,
                            TrackingNumber = string.Empty,
                            VatNumber = vatNumber,
                            Deleted = false,
                            CreatedOn = DateTime.UtcNow
                        };
                        InsertOrder(order);

                        orderId = order.OrderId;

                        if (!paymentInfo.IsRecurringPayment)
                        {
                            //move shopping cart items to order product variants
                            foreach (var sc in cart)
                            {
                                //prices
                                decimal taxRate = decimal.Zero;
                                decimal scUnitPrice = PriceHelper.GetUnitPrice(sc, customer, true);
                                decimal scSubTotal = PriceHelper.GetSubTotal(sc, customer, true);
                                decimal scUnitPriceInclTax = taxService.GetPrice(sc.ProductVariant, scUnitPrice, true, customer, out taxRate);
                                decimal scUnitPriceExclTax = taxService.GetPrice(sc.ProductVariant, scUnitPrice, false, customer, out taxRate);
                                decimal scSubTotalInclTax = taxService.GetPrice(sc.ProductVariant, scSubTotal, true, customer, out taxRate);
                                decimal scSubTotalExclTax = taxService.GetPrice(sc.ProductVariant, scSubTotal, false, customer, out taxRate);
                                decimal scUnitPriceInclTaxInCustomerCurrency = currencyService.ConvertCurrency(scUnitPriceInclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                                decimal scUnitPriceExclTaxInCustomerCurrency = currencyService.ConvertCurrency(scUnitPriceExclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                                decimal scSubTotalInclTaxInCustomerCurrency = currencyService.ConvertCurrency(scSubTotalInclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                                decimal scSubTotalExclTaxInCustomerCurrency = currencyService.ConvertCurrency(scSubTotalExclTax, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);

                                //discounts
                                Discount scDiscount = null;
                                decimal discountAmount = PriceHelper.GetDiscountAmount(sc, customer, out scDiscount);
                                decimal discountAmountInclTax = taxService.GetPrice(sc.ProductVariant, discountAmount, true, customer, out taxRate);
                                decimal discountAmountExclTax = taxService.GetPrice(sc.ProductVariant, discountAmount, false, customer, out taxRate);
                                if (scDiscount != null && !appliedDiscounts.ContainsDiscount(scDiscount.Name))
                                    appliedDiscounts.Add(scDiscount);

                                //attributes
                                string attributeDescription = ProductAttributeHelper.FormatAttributes(sc.ProductVariant, sc.AttributesXml, customer, "<br />");

                                //save item
                                var opv = new OrderProductVariant()
                                {
                                    OrderProductVariantGuid = Guid.NewGuid(),
                                    OrderId = order.OrderId,
                                    ProductVariantId = sc.ProductVariantId,
                                    UnitPriceInclTax = scUnitPriceInclTax,
                                    UnitPriceExclTax = scUnitPriceExclTax,
                                    PriceInclTax = scSubTotalInclTax,
                                    PriceExclTax = scSubTotalExclTax,
                                    UnitPriceInclTaxInCustomerCurrency = scUnitPriceInclTaxInCustomerCurrency,
                                    UnitPriceExclTaxInCustomerCurrency = scUnitPriceExclTaxInCustomerCurrency,
                                    PriceInclTaxInCustomerCurrency = scSubTotalInclTaxInCustomerCurrency,
                                    PriceExclTaxInCustomerCurrency = scSubTotalExclTaxInCustomerCurrency,
                                    AttributeDescription = attributeDescription,
                                    AttributesXml = sc.AttributesXml,
                                    Quantity = sc.Quantity,
                                    DiscountAmountInclTax = discountAmountInclTax,
                                    DiscountAmountExclTax = discountAmountExclTax,
                                    DownloadCount = 0,
                                    IsDownloadActivated = false,
                                    LicenseDownloadId = 0
                                };
                                InsertOrderProductVariant(opv);

                                //gift cards
                                if (sc.ProductVariant.IsGiftCard)
                                {
                                    string giftCardRecipientName = string.Empty;
                                    string giftCardRecipientEmail = string.Empty;
                                    string giftCardSenderName = string.Empty;
                                    string giftCardSenderEmail = string.Empty;
                                    string giftCardMessage = string.Empty;
                                    ProductAttributeHelper.GetGiftCardAttribute(sc.AttributesXml,
                                        out giftCardRecipientName, out giftCardRecipientEmail,
                                        out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                                    for (int i = 0; i < sc.Quantity; i++)
                                    {
                                        var gc = new GiftCard()
                                        {
                                            PurchasedOrderProductVariantId = opv.OrderProductVariantId,
                                            Amount = scUnitPriceExclTax,
                                            IsGiftCardActivated = false,
                                            GiftCardCouponCode = GiftCardHelper.GenerateGiftCardCode(),
                                            RecipientName = giftCardRecipientName,
                                            RecipientEmail = giftCardRecipientEmail,
                                            SenderName = giftCardSenderName,
                                            SenderEmail = giftCardSenderEmail,
                                            Message = giftCardMessage,
                                            IsRecipientNotified = false,
                                            CreatedOn = DateTime.UtcNow
                                        };
                                        InsertGiftCard(gc);
                                    }
                                }

                                //inventory
                                productService.AdjustInventory(sc.ProductVariantId, true, sc.Quantity, sc.AttributesXml);
                            }

                            //clear shopping cart
                            foreach (var sc in cart)
                            {
                                shoppingCartService.DeleteShoppingCartItem(sc.ShoppingCartItemId, false);
                            }
                        }
                        else
                        {
                            var initialOrderProductVariants = initialOrder.OrderProductVariants;
                            foreach (var opv in initialOrderProductVariants)
                            {
                                //save item
                                var newOpv = new OrderProductVariant()
                                {
                                    OrderProductVariantGuid = Guid.NewGuid(),
                                    OrderId = order.OrderId,
                                    ProductVariantId = opv.ProductVariantId,
                                    UnitPriceInclTax = opv.UnitPriceInclTax,
                                    UnitPriceExclTax = opv.UnitPriceExclTax,
                                    PriceInclTax = opv.PriceInclTax,
                                    PriceExclTax = opv.PriceExclTax,
                                    UnitPriceInclTaxInCustomerCurrency = opv.UnitPriceInclTaxInCustomerCurrency,
                                    UnitPriceExclTaxInCustomerCurrency = opv.UnitPriceExclTaxInCustomerCurrency,
                                    PriceInclTaxInCustomerCurrency =  opv.PriceInclTaxInCustomerCurrency,
                                    PriceExclTaxInCustomerCurrency = opv.PriceExclTaxInCustomerCurrency,
                                    AttributeDescription = opv.AttributeDescription,
                                    AttributesXml = opv.AttributesXml,
                                    Quantity = opv.Quantity,
                                    DiscountAmountInclTax = opv.DiscountAmountInclTax,
                                    DiscountAmountExclTax =  opv.DiscountAmountExclTax,
                                    DownloadCount = 0,
                                    IsDownloadActivated = false,
                                    LicenseDownloadId = 0
                                };

                                InsertOrderProductVariant(newOpv);

                                //gift cards
                                if (opv.ProductVariant.IsGiftCard)
                                {
                                    string giftCardRecipientName = string.Empty;
                                    string giftCardRecipientEmail = string.Empty;
                                    string giftCardSenderName = string.Empty;
                                    string giftCardSenderEmail = string.Empty;
                                    string giftCardMessage = string.Empty;
                                    ProductAttributeHelper.GetGiftCardAttribute(opv.AttributesXml,
                                        out giftCardRecipientName, out giftCardRecipientEmail,
                                        out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                                    for (int i = 0; i < opv.Quantity; i++)
                                    {
                                        var gc = new GiftCard()
                                        {
                                            PurchasedOrderProductVariantId = newOpv.OrderProductVariantId,
                                            Amount = opv.UnitPriceExclTax,
                                            IsGiftCardActivated = false,
                                            GiftCardCouponCode = GiftCardHelper.GenerateGiftCardCode(),
                                            RecipientName = giftCardRecipientName,
                                            RecipientEmail = giftCardRecipientEmail,
                                            SenderName = giftCardSenderName,
                                            SenderEmail = giftCardSenderEmail,
                                            Message = giftCardMessage,
                                            IsRecipientNotified = false,
                                            CreatedOn = DateTime.UtcNow
                                        };
                                        InsertGiftCard(gc);
                                    }
                                }

                                //inventory
                                productService.AdjustInventory(opv.ProductVariantId, true, opv.Quantity, opv.AttributesXml);
                            }
                        }

                        //discount usage history
                        if (!paymentInfo.IsRecurringPayment)
                        {
                            foreach (var discount in appliedDiscounts)
                            {
                                var duh = new DiscountUsageHistory()
                                {
                                    DiscountId = discount.DiscountId,
                                    CustomerId = customer.CustomerId,
                                    OrderId = order.OrderId,
                                    CreatedOn = DateTime.UtcNow
                                };
                                discountService.InsertDiscountUsageHistory(duh);
                            }
                        }

                        //gift card usage history
                        if (!paymentInfo.IsRecurringPayment)
                        {
                            if (appliedGiftCards != null)
                            {
                                foreach (var agc in appliedGiftCards)
                                {
                                    decimal amountUsed = agc.AmountCanBeUsed;
                                    decimal amountUsedInCustomerCurrency = currencyService.ConvertCurrency(amountUsed, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                                    var gcuh = new GiftCardUsageHistory()
                                    {
                                        GiftCardId = agc.GiftCardId,
                                        CustomerId = customer.CustomerId,
                                        OrderId = order.OrderId,
                                        UsedValue = amountUsed,
                                        UsedValueInCustomerCurrency = amountUsedInCustomerCurrency,
                                        CreatedOn = DateTime.UtcNow
                                    };
                                    InsertGiftCardUsageHistory(gcuh);
                                }
                            }
                        }

                        //reward points history
                        if (redeemedRewardPointsAmount > decimal.Zero)
                        {
                            decimal redeemedRewardPointsAmountInCustomerCurrency = currencyService.ConvertCurrency(redeemedRewardPointsAmount, currencyService.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
                            string message = string.Format(localizationManager.GetLocaleResourceString("RewardPoints.Message.RedeemedForOrder", order.CustomerLanguageId), order.OrderId);

                            RewardPointsHistory rph = this.InsertRewardPointsHistory(customer.CustomerId,
                                order.OrderId, -redeemedRewardPoints,
                                redeemedRewardPointsAmount,
                                redeemedRewardPointsAmountInCustomerCurrency,
                                customerCurrencyCode,
                                message,
                                DateTime.UtcNow);
                        }

                        //recurring orders
                        if (!paymentInfo.IsRecurringPayment)
                        {
                            if (isRecurringShoppingCart)
                            {
                                //create recurring payment
                                var rp = new RecurringPayment()
                                {
                                    InitialOrderId = order.OrderId,
                                    CycleLength = paymentInfo.RecurringCycleLength,
                                    CyclePeriod = paymentInfo.RecurringCyclePeriod,
                                    TotalCycles = paymentInfo.RecurringTotalCycles,
                                    StartDate = DateTime.UtcNow,
                                    IsActive = true,
                                    Deleted = false,
                                    CreatedOn = DateTime.UtcNow
                                };
                                InsertRecurringPayment(rp);

                                var recurringPaymentType = paymentService.SupportRecurringPayments(paymentInfo.PaymentMethodId);
                                switch (recurringPaymentType)
                                {
                                    case RecurringPaymentTypeEnum.NotSupported:
                                        {
                                            //not supported
                                        }
                                        break;
                                    case RecurringPaymentTypeEnum.Manual:
                                        {
                                            //first payment
                                            var rph = new RecurringPaymentHistory()
                                            {
                                                RecurringPaymentId = rp.RecurringPaymentId,
                                                OrderId = order.OrderId,
                                                CreatedOn = DateTime.UtcNow
                                            };
                                            InsertRecurringPaymentHistory(rph);
                                        }
                                        break;
                                    case RecurringPaymentTypeEnum.Automatic:
                                        {
                                            //will be created later (process is automated)
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }

                        //notes, messages
                        InsertOrderNote(order.OrderId, string.Format("Order placed"), false, DateTime.UtcNow);

                        int orderPlacedStoreOwnerNotificationQueuedEmailId = messageService.SendOrderPlacedStoreOwnerNotification(order, localizationManager.DefaultAdminLanguage.LanguageId);
                        if (orderPlacedStoreOwnerNotificationQueuedEmailId > 0)
                        {
                            InsertOrderNote(order.OrderId, string.Format("\"Order placed\" email (to store owner) has been queued. Queued email identifier: {0}.", orderPlacedStoreOwnerNotificationQueuedEmailId), false, DateTime.UtcNow);
                        }

                        int orderPlacedCustomerNotificationQueuedEmailId = messageService.SendOrderPlacedCustomerNotification(order, order.CustomerLanguageId);
                        if (orderPlacedCustomerNotificationQueuedEmailId > 0)
                        {
                            InsertOrderNote(order.OrderId, string.Format("\"Order placed\" email (to customer) has been queued. Queued email identifier: {0}.", orderPlacedCustomerNotificationQueuedEmailId), false, DateTime.UtcNow);
                        }

                        smsService.SendOrderPlacedNotification(order);

                        //order status
                        order = CheckOrderStatus(order.OrderId);

                        //reset checkout data
                        if (!paymentInfo.IsRecurringPayment)
                        {
                            customerService.ResetCheckoutData(customer.CustomerId, true);
                        }

                        //log
                        if (!paymentInfo.IsRecurringPayment)
                        {
                            customerActivityService.InsertActivity(
                                "PlaceOrder",
                                localizationManager.GetLocaleResourceString("ActivityLog.PlaceOrder"),
                                order.OrderId);
                        }

                        //uncomment this line to support transactions
                        //scope.Complete();

                        //raise event
                        EventContext.Current.OnOrderPlaced(null,
                            new OrderEventArgs() { Order = order });

                        //raise event
                        if (order.PaymentStatus == PaymentStatusEnum.Paid)
                        {
                            EventContext.Current.OnOrderPaid(null,
                                new OrderEventArgs() { Order = order });
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                processPaymentResult.Error = exc.Message;
                processPaymentResult.FullError = exc.ToString();
            }

            if (!String.IsNullOrEmpty(processPaymentResult.Error))
            {
                logService.InsertLog(LogTypeEnum.OrderError, string.Format("Error while placing order. {0}", processPaymentResult.Error), processPaymentResult.FullError);
            }
            return processPaymentResult.Error;
        }
Esempio n. 9
0
        /// <summary>
        /// Process next recurring psayment
        /// </summary>
        /// <param name="recurringPaymentId">Recurring payment identifier</param>
        public void ProcessNextRecurringPayment(int recurringPaymentId)
        {
            try
            {
                var rp = GetRecurringPaymentById(recurringPaymentId);
                if (rp == null)
                    throw new NopException("Recurring payment could not be loaded");

                if (!rp.IsActive)
                    throw new NopException("Recurring payment is not active");

                var initialOrder = rp.InitialOrder;
                if (initialOrder == null)
                    throw new NopException("Initial order could not be loaded");

                var customer = initialOrder.Customer;
                if (customer == null)
                    throw new NopException("Customer could not be loaded");

                var nextPaymentDate = rp.NextPaymentDate;
                if (!nextPaymentDate.HasValue)
                    throw new NopException("Next payment date could not be calculated");

                //payment info
                var paymentInfo = new PaymentInfo();
                paymentInfo.IsRecurringPayment = true;
                paymentInfo.InitialOrderId = initialOrder.OrderId;
                paymentInfo.RecurringCycleLength = rp.CycleLength;
                paymentInfo.RecurringCyclePeriod = rp.CyclePeriod;
                paymentInfo.RecurringTotalCycles = rp.TotalCycles;

                //place new order
                int newOrderId = 0;
                string result = this.PlaceOrder(paymentInfo, customer,
                    Guid.NewGuid(), out newOrderId);
                if (!String.IsNullOrEmpty(result))
                {
                    throw new NopException(result);
                }
                else
                {
                    var rph = new RecurringPaymentHistory()
                    {
                        RecurringPaymentId = rp.RecurringPaymentId,
                        OrderId = newOrderId,
                        CreatedOn = DateTime.UtcNow
                    };
                    InsertRecurringPaymentHistory(rph);
                }
            }
            catch (Exception exc)
            {
                IoC.Resolve<ILogService>().InsertLog(LogTypeEnum.OrderError, string.Format("Error while processing recurring order. {0}", exc.Message), exc);
                throw;
            }
        }
Esempio n. 10
0
        protected void btnNextStep_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    var paymentInfo = this.PaymentInfo;
                    if (paymentInfo == null)
                    {
                        var args1 = new CheckoutStepEventArgs() { OrderConfirmed = false };
                        OnCheckoutStepChanged(args1);
                        if (!this.OnePageCheckout)
                        {
                            Response.Redirect("~/checkoutpaymentinfo.aspx");
                        }
                        else
                        {
                            return;
                        }
                    }
                    paymentInfo.BillingAddress = NopContext.Current.User.BillingAddress;
                    paymentInfo.ShippingAddress = NopContext.Current.User.ShippingAddress;
                    paymentInfo.CustomerLanguage = NopContext.Current.WorkingLanguage;
                    paymentInfo.CustomerCurrency = NopContext.Current.WorkingCurrency;

                    int orderId = 0;
                    string result = OrderManager.PlaceOrder(paymentInfo, NopContext.Current.User, out orderId);
                    this.PaymentInfo = null;
                    var order = OrderManager.GetOrderById(orderId);
                    if (!String.IsNullOrEmpty(result))
                    {
                        lConfirmOrderError.Text = Server.HtmlEncode(result);
                        return;
                    }
                    else
                    {
                        PaymentManager.PostProcessPayment(order);
                    }
                    var args2 = new CheckoutStepEventArgs() { OrderConfirmed = true };
                    OnCheckoutStepChanged(args2);
                    if (!this.OnePageCheckout)
                        Response.Redirect("~/checkoutcompleted.aspx");
                }
                catch (Exception exc)
                {
                    LogManager.InsertLog(LogTypeEnum.OrderError, exc.Message, exc);
                    lConfirmOrderError.Text = Server.HtmlEncode(exc.ToString());
                }
            }
        }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            WebClient webClient = new WebClient();
            NameValueCollection form = new NameValueCollection();
            form.Add("x_login", loginID);
            form.Add("x_tran_key", transactionKey);
            if (useSandBox)
                form.Add("x_test_request", "TRUE");
            else
                form.Add("x_test_request", "FALSE");

            form.Add("x_delim_data", "TRUE");
            form.Add("x_delim_char", "|");
            form.Add("x_encap_char", "");
            form.Add("x_version", APIVersion);
            form.Add("x_relay_response", "FALSE");
            form.Add("x_method", "CC");
            form.Add("x_currency_code", IoC.Resolve<ICurrencyService>().PrimaryStoreCurrency.CurrencyCode);
            if (transactionMode == TransactMode.Authorize)
                form.Add("x_type", "AUTH_ONLY");
            else if (transactionMode == TransactMode.AuthorizeAndCapture)
                form.Add("x_type", "AUTH_CAPTURE");
            else
                throw new NopException("Not supported transaction mode");

            form.Add("x_amount", paymentInfo.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            form.Add("x_card_num", paymentInfo.CreditCardNumber);
            form.Add("x_exp_date", paymentInfo.CreditCardExpireMonth.ToString("D2") + paymentInfo.CreditCardExpireYear.ToString());
            form.Add("x_card_code", paymentInfo.CreditCardCvv2);
            form.Add("x_first_name", paymentInfo.BillingAddress.FirstName);
            form.Add("x_last_name", paymentInfo.BillingAddress.LastName);
            if (string.IsNullOrEmpty(paymentInfo.BillingAddress.Company))
                form.Add("x_company", paymentInfo.BillingAddress.Company);
            form.Add("x_address", paymentInfo.BillingAddress.Address1);
            form.Add("x_city", paymentInfo.BillingAddress.City);
            if (paymentInfo.BillingAddress.StateProvince != null)
                form.Add("x_state", paymentInfo.BillingAddress.StateProvince.Abbreviation);
            form.Add("x_zip", paymentInfo.BillingAddress.ZipPostalCode);
            if (paymentInfo.BillingAddress.Country != null)
                form.Add("x_country", paymentInfo.BillingAddress.Country.TwoLetterIsoCode);
            //20 chars maximum
            form.Add("x_invoice_num", orderGuid.ToString().Substring(0,20));
            form.Add("x_customer_ip",NopContext.Current.UserHostAddress);

            string reply = null;
            Byte[] responseData = webClient.UploadValues(GetAuthorizeNETUrl(), form);
            reply = Encoding.ASCII.GetString(responseData);

            if (!String.IsNullOrEmpty(reply))
            {
                string[] responseFields = reply.Split('|');
                switch (responseFields[0])
                {
                    case "1":
                        processPaymentResult.AuthorizationTransactionCode = string.Format("{0},{1}", responseFields[6], responseFields[4]);
                        processPaymentResult.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", responseFields[2], responseFields[3]);
                        processPaymentResult.AVSResult = responseFields[5];
                        //responseFields[38];
                        if (transactionMode == TransactMode.Authorize)
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                        }
                        else
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                        }
                        break;
                    case "2":
                        processPaymentResult.Error = string.Format("Declined ({0}: {1})", responseFields[2], responseFields[3]);
                        processPaymentResult.FullError = string.Format("Declined ({0}: {1})", responseFields[2], responseFields[3]);
                        break;
                    case "3":
                        processPaymentResult.Error = string.Format("Error: {0}", reply);
                        processPaymentResult.FullError = string.Format("Error: {0}", reply);
                        break;

                }
            }
            else
            {
                processPaymentResult.Error = "Authorize.NET unknown error";
                processPaymentResult.FullError = "Authorize.NET unknown error";
            }
        }
        /// <summary>
        /// Do paypal express checkout
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void DoExpressCheckout(PaymentInfo paymentInfo, 
            Guid orderGuid,  ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            DoExpressCheckoutPaymentReq req = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType();
            req.DoExpressCheckoutPaymentRequest = request;
            request.Version = this.APIVersion;
            DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType();
            request.DoExpressCheckoutPaymentRequestDetails = details;
            if (transactionMode == TransactMode.Authorize)
                details.PaymentAction = PaymentActionCodeType.Authorization;
            else
                details.PaymentAction = PaymentActionCodeType.Sale;
            details.PaymentActionSpecified = true;
            details.Token = paymentInfo.PaypalToken;
            details.PayerID = paymentInfo.PaypalPayerId;

            details.PaymentDetails = new PaymentDetailsType[1];
            PaymentDetailsType paymentDetails1 = new PaymentDetailsType();
            details.PaymentDetails[0] = paymentDetails1;
            paymentDetails1.OrderTotal = new BasicAmountType();
            paymentDetails1.OrderTotal.Value = paymentInfo.OrderTotal.ToString("N", new CultureInfo("en-us"));
            paymentDetails1.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(IoC.Resolve<ICurrencyService>().PrimaryStoreCurrency);
            paymentDetails1.Custom = orderGuid.ToString();
            paymentDetails1.ButtonSource = "nopCommerceCart";

            DoExpressCheckoutPaymentResponseType response = service2.DoExpressCheckoutPayment(req);
            string error;
            if (!PaypalHelper.CheckSuccess(response, out error))
                throw new NopException(error);

            if (response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null &&
                response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0] != null)
            {
                processPaymentResult.AuthorizationTransactionId = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
                processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();

                if (transactionMode == TransactMode.Authorize)
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                else
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
            }
            else
            {
                throw new NopException("response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo is null");
            }
        }
Esempio n. 13
0
 public PaymentInfo GetPaymentInfo()
 {
     PaymentInfo paymentInfo = new PaymentInfo();
     paymentInfo.PurchaseOrderNumber = this.txtPONumber.Text;
     return paymentInfo;
 }
Esempio n. 14
0
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();

            GatewayConnector eWAYgateway = new GatewayConnector();
            GatewayRequest eWAYRequest = new GatewayRequest();
            if (useSandBox)
                eWAYRequest.EwayCustomerID = ewayTestCustomerID;
            else
                eWAYRequest.EwayCustomerID = ewayLiveCustomerID;

            eWAYRequest.CardNumber = paymentInfo.CreditCardNumber;
            eWAYRequest.CardExpiryMonth = paymentInfo.CreditCardExpireMonth.ToString("D2");
            eWAYRequest.CardExpiryYear = paymentInfo.CreditCardExpireYear.ToString();
            eWAYRequest.CardHolderName = paymentInfo.CreditCardName;
            //Integer
            eWAYRequest.InvoiceAmount = Convert.ToInt32(paymentInfo.OrderTotal * 100);
            eWAYRequest.PurchaserFirstName = paymentInfo.BillingAddress.FirstName;
            eWAYRequest.PurchaserLastName = paymentInfo.BillingAddress.LastName;
            eWAYRequest.PurchaserEmailAddress = paymentInfo.BillingAddress.Email;
            eWAYRequest.PurchaserAddress = paymentInfo.BillingAddress.Address1;
            eWAYRequest.PurchaserPostalCode = paymentInfo.BillingAddress.ZipPostalCode;
            eWAYRequest.InvoiceReference = orderGuid.ToString();
            eWAYRequest.InvoiceDescription = SettingManager.GetSettingValue("Common.StoreName") + ". Order #" + orderGuid.ToString();
            eWAYRequest.TransactionNumber = orderGuid.ToString();
            eWAYRequest.CVN = paymentInfo.CreditCardCvv2;
            eWAYRequest.EwayOption1 = string.Empty;
            eWAYRequest.EwayOption2 = string.Empty;
            eWAYRequest.EwayOption3 = string.Empty;

            // Do the payment, send XML doc containing information gathered
            eWAYgateway.Uri = GeteWayUrl();
            GatewayResponse eWAYResponse = eWAYgateway.ProcessRequest(eWAYRequest);
            if (eWAYResponse != null)
            {
                // Payment succeeded get values returned
                if (eWAYResponse.Status && (eWAYResponse.Error.StartsWith(APPROVED_RESPONSE) || eWAYResponse.Error.StartsWith(HONOUR_RESPONSE)))
                {
                    processPaymentResult.AuthorizationTransactionCode = eWAYResponse.AuthorisationCode;
                    processPaymentResult.AuthorizationTransactionResult = eWAYResponse.InvoiceReference;
                    processPaymentResult.AuthorizationTransactionId = eWAYResponse.TransactionNumber;
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                    //processPaymentResult.AuthorizationDate = DateTime.UtcNow;
                }
                else
                {
                    processPaymentResult.Error = "An invalid response was recieved from the payment gateway." + eWAYResponse.Error;
                    processPaymentResult.FullError = "An invalid response was recieved from the payment gateway." + eWAYRequest.ToXml().ToString() + ". " + eWAYResponse.Error;
                }
            }
            else
            {
                // invalid response recieved from server.
                processPaymentResult.Error = "An invalid response was recieved from the payment gateway.";
                processPaymentResult.FullError = "An invalid response was recieved from the payment gateway." + eWAYRequest.ToXml().ToString();
            }
        }
 /// <summary>
 /// Process recurring payment
 /// </summary>
 /// <param name="paymentInfo">Payment info required for an order processing</param>
 /// <param name="customer">Customer</param>
 /// <param name="orderGuid">Unique order identifier</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void ProcessRecurringPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            string transactionModeStr = string.Empty;
            if (transactionMode == TransactMode.Authorize)
                transactionModeStr = "AUTHORIZATION";
            else if (transactionMode == TransactMode.AuthorizeAndCapture)
                transactionModeStr = "AUTHORIZATION_CAPTURE";
            else
                throw new NopException("Not supported transaction mode");

            // This is the standard information that is needed to connect to PayJunction
            string server = GetUrl();
            int port = 443;
            SslStream stream = null;

            // Encode Data Values
            string encodedPJLogin = Encode("dc_logon", pjlogon);
            string encodedPJPassword = Encode("dc_password", pjpassword);
            string encodedFirstname = Encode("dc_first_name", paymentInfo.BillingAddress.FirstName);
            string encodedLastname = Encode("dc_last_name", paymentInfo.BillingAddress.LastName);
            string encodedCCNumber = Encode("dc_number", paymentInfo.CreditCardNumber);
            string encodedExpMonth = Encode("dc_expiration_month", paymentInfo.CreditCardExpireMonth.ToString("D2"));
            string encodedExpYear = Encode("dc_expiration_year", paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2));
            string encodedCVVCode = Encode("dc_verification_number", paymentInfo.CreditCardCvv2);
            string encodedAddress = Encode("dc_address", paymentInfo.BillingAddress.Address1);
            string encodedCity = Encode("dc_city", paymentInfo.BillingAddress.City);
            string encodedZipCode = Encode("dc_zipcode", paymentInfo.BillingAddress.ZipPostalCode);
            string encodedTransType = Encode("dc_transaction_type", transactionModeStr);
            string encodedAmount = Encode("dc_transaction_amount", paymentInfo.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            string encodedVersion = Encode("dc_version", "1.2");

            // Concatenate Encoded Transaction String
            string transactioninfo = "POST /quick_link?" + encodedPJLogin + "&" + encodedPJPassword + "&" + encodedFirstname + "&" + encodedLastname + "&" + encodedCCNumber + "&" + encodedExpMonth + "&" + encodedExpYear + "&" + encodedCCNumber + "&" + encodedAddress + "&" + encodedCity + "&" + encodedZipCode + "&" + encodedTransType + "&" + encodedAmount + "&" + encodedVersion + " \r\n\r\n";

            try
            {
                // Instantiate a TcpClient with the server and port
                TcpClient client = new TcpClient(server, port);
                // Convert the data to send into a byte array
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(transactioninfo);
                // Specify the callback function that will act as the validation delegate.
                RemoteCertificateValidationCallback callback = new
                    // This lets you inspect the certificate to see if it meets your validation requirements.
                RemoteCertificateValidationCallback(OnCertificateValidation);
                // Instantiate an SslStream with the NetworkStream returned from the TcpClient.
                stream = new SslStream(client.GetStream(), false, callback);
                // As a client, you can authenticate the server and validate the results using the SslStream.
                // This is the host name of the server you are connecting to, which may or may not be the name used to connect to the server when TcpClient is instantiated.
                stream.AuthenticateAsClient(server);
                // Send the message to the server.
                stream.Write(data, 0, data.Length);
                // Buffer to hold data returned from the server.
                data = new Byte[2048];
                // Read the response from the server up to the size of the buffer.
                int bytes = stream.Read(data, 0, data.Length);
                Console.WriteLine(bytes);
                // Convert the received bytes into a string
                string responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                // Create an Array "keyValue" that contains the response
                string[] keyValue = responseData.Split(Convert.ToChar(28));
                Dictionary<string, string> keyValueDic = new Dictionary<string, string>();
                foreach (string key in keyValue)
                {
                    string str1 = key.Split(new char[] { '=' })[0];
                    string str2 = key.Split(new char[] { '=' })[1];
                    keyValueDic.Add(str1, str2);
                }

                string dc_response_code = string.Empty;
                if (keyValueDic.ContainsKey("dc_response_code"))
                {
                    dc_response_code = keyValueDic["dc_response_code"];
                }
                string dc_response_message = string.Empty;
                if (keyValueDic.ContainsKey("dc_response_message"))
                {
                    dc_response_message = keyValueDic["dc_response_message"];
                }

                if (dc_response_code == "00" || dc_response_code == "85")
                {
                    string dc_transaction_id = string.Empty;
                    if (keyValueDic.ContainsKey("dc_transaction_id"))
                    {
                        dc_transaction_id = keyValueDic["dc_transaction_id"];
                    }
                    if (transactionMode == TransactMode.Authorize)
                    {
                        processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                        processPaymentResult.AuthorizationTransactionId = dc_transaction_id;
                    }
                    else
                    {
                        processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                        processPaymentResult.CaptureTransactionId = dc_transaction_id;
                    }
                }
                else
                {
                    processPaymentResult.Error = string.Format("Error: {0}. {1}", dc_response_message, dc_response_code);
                    processPaymentResult.FullError = string.Format("Error: {0}. {1}", dc_response_message, dc_response_code);
                }
            }
            catch (Exception exc)
            {
                processPaymentResult.Error = string.Format("Error: {0}", exc.Message);
                processPaymentResult.FullError = string.Format("Error: {0}", exc.ToString());
            }
            finally
            {
                // Make sure that the SslStream is closed.
                if (stream != null)
                    stream.Close();
            }
        }
        private void processNewOrderNotification(string xmlData)
        {
            try
            {
                NewOrderNotification newOrderNotification = (NewOrderNotification)EncodeHelper.Deserialize(xmlData, typeof(NewOrderNotification));
                string googleOrderNumber = newOrderNotification.googleordernumber;

                XmlNode CustomerInfo = newOrderNotification.shoppingcart.merchantprivatedata.Any[0];
                int CustomerID = Convert.ToInt32(CustomerInfo.Attributes["CustomerID"].Value);
                int CustomerLanguageID = Convert.ToInt32(CustomerInfo.Attributes["CustomerLanguageID"].Value);
                int CustomerCurrencyID = Convert.ToInt32(CustomerInfo.Attributes["CustomerCurrencyID"].Value);
                Customer customer = CustomerManager.GetCustomerByID(CustomerID);

                NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCart Cart = ShoppingCartManager.GetCustomerShoppingCart(customer.CustomerID, ShoppingCartTypeEnum.ShoppingCart);

                if (customer == null)
                {
                    logMessage("Could not load a customer");
                    return;
                }

                NopContext.Current.User = customer;

                if (Cart.Count == 0)
                {
                    logMessage("Cart is empty");
                    return;
                }

                //validate cart
                foreach (NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCartItem sci in Cart)
                {
                    bool ok = false;
                    foreach (Item item in newOrderNotification.shoppingcart.items)
                    {
                        if (!String.IsNullOrEmpty(item.merchantitemid))
                        {
                            if ((Convert.ToInt32(item.merchantitemid) == sci.ShoppingCartItemID) && (item.quantity == sci.Quantity))
                            {
                                ok = true;
                                break;
                            }
                        }
                    }

                    if (!ok)
                    {
                        logMessage(string.Format("Shopping Cart item has been changed. {0}. {1}", sci.ShoppingCartItemID, sci.Quantity));
                        return;
                    }
                }


                string[] billingFullname = newOrderNotification.buyerbillingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                string billingFirstName = billingFullname[0];
                string billingLastName = string.Empty;
                if (billingFullname.Length > 1)
                    billingLastName = billingFullname[1];
                string billingEmail = newOrderNotification.buyerbillingaddress.email.Trim();
                string billingAddress1 = newOrderNotification.buyerbillingaddress.address1.Trim();
                string billingAddress2 = newOrderNotification.buyerbillingaddress.address2.Trim();
                string billingPhoneNumber = newOrderNotification.buyerbillingaddress.phone.Trim();
                string billingCity = newOrderNotification.buyerbillingaddress.city.Trim();
                int billingStateProvinceID = 0;
                StateProvince billingStateProvince = StateProvinceManager.GetStateProvinceByAbbreviation(newOrderNotification.buyerbillingaddress.region.Trim());
                if (billingStateProvince != null)
                    billingStateProvinceID = billingStateProvince.StateProvinceID;
                string billingZipPostalCode = newOrderNotification.buyerbillingaddress.postalcode.Trim();
                int billingCountryID = 0;
                Country billingCountry = CountryManager.GetCountryByTwoLetterISOCode(newOrderNotification.buyerbillingaddress.countrycode.Trim());
                if (billingCountry != null)
                    billingCountryID = billingCountry.CountryID;

                NopSolutions.NopCommerce.BusinessLogic.CustomerManagement.Address BillingAddress = customer.BillingAddresses.FindAddress(
                    billingFirstName, billingLastName, billingPhoneNumber,
                    billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity,
                    billingStateProvinceID, billingZipPostalCode, billingCountryID);

                if (BillingAddress == null)
                {
                    BillingAddress = CustomerManager.InsertAddress(CustomerID, true,
                        billingFirstName, billingLastName, billingPhoneNumber, billingEmail,
                        string.Empty, string.Empty, billingAddress1,
                        billingAddress2, billingCity,
                        billingStateProvinceID, billingZipPostalCode,
                        billingCountryID, DateTime.Now, DateTime.Now);
                }
                customer = CustomerManager.SetDefaultBillingAddress(customer.CustomerID, BillingAddress.AddressID);

                NopSolutions.NopCommerce.BusinessLogic.CustomerManagement.Address ShippingAddress = null;
                customer.LastShippingOption = null;
                bool shoppingCartRequiresShipping = ShippingManager.ShoppingCartRequiresShipping(Cart);
                if (shoppingCartRequiresShipping)
                {
                    string[] shippingFullname = newOrderNotification.buyershippingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    string shippingFirstName = shippingFullname[0];
                    string shippingLastName = string.Empty;
                    if (shippingFullname.Length > 1)
                        shippingLastName = shippingFullname[1];
                    string shippingEmail = newOrderNotification.buyershippingaddress.email.Trim();
                    string shippingAddress1 = newOrderNotification.buyershippingaddress.address1.Trim();
                    string shippingAddress2 = newOrderNotification.buyershippingaddress.address2.Trim();
                    string shippingPhoneNumber = newOrderNotification.buyershippingaddress.phone.Trim();
                    string shippingCity = newOrderNotification.buyershippingaddress.city.Trim();
                    int shippingStateProvinceID = 0;
                    StateProvince shippingStateProvince = StateProvinceManager.GetStateProvinceByAbbreviation(newOrderNotification.buyershippingaddress.region.Trim());
                    if (shippingStateProvince != null)
                        shippingStateProvinceID = shippingStateProvince.StateProvinceID;
                    int shippingCountryID = 0;
                    string shippingZipPostalCode = newOrderNotification.buyershippingaddress.postalcode.Trim();
                    Country shippingCountry = CountryManager.GetCountryByTwoLetterISOCode(newOrderNotification.buyershippingaddress.countrycode.Trim());
                    if (shippingCountry != null)
                        shippingCountryID = shippingCountry.CountryID;

                    ShippingAddress = customer.ShippingAddresses.FindAddress(
                        shippingFirstName, shippingLastName, shippingPhoneNumber,
                        shippingEmail, string.Empty, string.Empty, 
                        shippingAddress1, shippingAddress2, shippingCity,
                        shippingStateProvinceID, shippingZipPostalCode, shippingCountryID);
                    if (ShippingAddress == null)
                    {
                        ShippingAddress = CustomerManager.InsertAddress(CustomerID, false,
                             shippingFirstName, shippingLastName, shippingPhoneNumber, shippingEmail,
                             string.Empty, string.Empty, shippingAddress1,
                             shippingAddress2, shippingCity, shippingStateProvinceID,
                             shippingZipPostalCode, shippingCountryID,
                             DateTime.Now, DateTime.Now);
                    }

                    customer = CustomerManager.SetDefaultShippingAddress(customer.CustomerID, ShippingAddress.AddressID);

                    string shippingMethod = string.Empty;
                    decimal shippingCost = decimal.Zero;
                    if (newOrderNotification.orderadjustment != null &&
                        newOrderNotification.orderadjustment.shipping != null &&
                        newOrderNotification.orderadjustment.shipping.Item != null)
                    {
                        FlatRateShippingAdjustment ShippingMethod = (FlatRateShippingAdjustment)newOrderNotification.orderadjustment.shipping.Item;
                        shippingMethod = ShippingMethod.shippingname;
                        shippingCost = ShippingMethod.shippingcost.Value;


                        ShippingOption shippingOption = new ShippingOption();
                        shippingOption.Name = shippingMethod;
                        shippingOption.Rate = shippingCost;
                        customer.LastShippingOption = shippingOption;
                    }
                }

                //customer.LastCalculatedTax = decimal.Zero;

                PaymentMethod googleCheckoutPaymentMethod = PaymentMethodManager.GetPaymentMethodBySystemKeyword("GoogleCheckout");

                PaymentInfo paymentInfo = new PaymentInfo();
                paymentInfo.PaymentMethodID = googleCheckoutPaymentMethod.PaymentMethodID;
                paymentInfo.BillingAddress = BillingAddress;
                paymentInfo.ShippingAddress = ShippingAddress;
                paymentInfo.CustomerLanguage = LanguageManager.GetLanguageByID(CustomerLanguageID);
                paymentInfo.CustomerCurrency = CurrencyManager.GetCurrencyByID(CustomerCurrencyID);
                paymentInfo.GoogleOrderNumber = googleOrderNumber;
                int orderID = 0;
                string result = OrderManager.PlaceOrder(paymentInfo, customer, out orderID);
                if (!String.IsNullOrEmpty(result))
                {
                    logMessage("new-order-notification received. CreateOrder() error: Order Number " + orderID + ". " + result);
                    return;
                }

                Order order = OrderManager.GetOrderByID(orderID);
                logMessage("new-order-notification received and saved: Order Number " + orderID);

            }
            catch (Exception exc)
            {
                logMessage("processNewOrderNotification Exception: " + exc.Message + ": " + exc.StackTrace);
            }
        }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="OrderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid OrderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            processPaymentResult.PaymentStatus = PaymentStatusEnum.Pending;
            processPaymentResult.AuthorizationTransactionID = paymentInfo.GoogleOrderNumber;

        }
Esempio n. 19
0
		/// <summary>
		/// Places an order
		/// </summary>
		/// <param name="paymentInfo">Payment info</param>
		/// <param name="customer">Customer</param>
		/// <param name="OrderGuid">Order GUID to use</param>
		/// <param name="OrderID">Order identifier</param>
		/// <returns>The error status, or String.Empty if no errors</returns>
		public static string PlaceOrder(PaymentInfo paymentInfo, Customer customer, Guid OrderGuid,
			out int OrderID)
		{
			OrderID = 0;
			ProcessPaymentResult processPaymentResult = new ProcessPaymentResult();
			try
			{
				if (customer == null)
					throw new ArgumentNullException("customer");

				if (customer.IsGuest && !CustomerManager.AnonymousCheckoutAllowed)
					throw new NopException("Anonymous checkout is not allowed");


				paymentInfo.BillingAddress.Email = customer.Email;

				//if (!CommonHelper.IsValidEmail(customer.Email))
				//{
				//    throw new NopException("Email is not valid");
				//}

				if (paymentInfo == null)
					throw new ArgumentNullException("paymentInfo");

				if (paymentInfo.BillingAddress == null)
					throw new NopException("Billing address not provided");

				//if (!CommonHelper.IsValidEmail(paymentInfo.BillingAddress.Email))
				//{
				//    throw new NopException("Email is not valid");
				//}

                PaymentMethod paymentMethod = PaymentMethodManager.GetPaymentMethodByID(paymentInfo.PaymentMethodID);
                if (paymentMethod == null)
                    throw new NopException("Payment method couldn't be loaded");

                if (!paymentMethod.IsActive)
                    throw new NopException("Payment method is not active");

				if (paymentInfo.CreditCardCVV2 == null)
					paymentInfo.CreditCardCVV2 = string.Empty;

				if (paymentInfo.CreditCardName == null)
					paymentInfo.CreditCardName = string.Empty;

				if (paymentInfo.CreditCardNumber == null)
					paymentInfo.CreditCardNumber = string.Empty;

				if (paymentInfo.CreditCardType == null)
					paymentInfo.CreditCardType = string.Empty;

				if (paymentInfo.PurchaseOrderNumber == null)
					paymentInfo.PurchaseOrderNumber = string.Empty;

				ShoppingCart cart = ShoppingCartManager.GetCustomerShoppingCart(customer.CustomerID, ShoppingCartTypeEnum.ShoppingCart);

				foreach (ShoppingCartItem sci in cart)
				{
					List<string> sciWarnings = ShoppingCartManager.GetShoppingCartItemWarnings(sci.ShoppingCartType,
						sci.ProductVariantID, sci.AttributesXML, sci.Quantity);

					if (sciWarnings.Count > 0)
					{
						StringBuilder warningsSb = new StringBuilder();
						foreach (string warning in sciWarnings)
						{
							warningsSb.Append(warning);
							warningsSb.Append(";");
						}
						throw new NopException(warningsSb.ToString());
					}
				}

				TaxDisplayTypeEnum customerTaxDisplayType = TaxDisplayTypeEnum.IncludingTax;
				if (TaxManager.AllowCustomersToSelectTaxDisplayType)
					customerTaxDisplayType = customer.TaxDisplayType;
				else
					customerTaxDisplayType = TaxManager.TaxDisplayType;

				decimal orderSubTotalDiscount;
				string SubTotalError1 = string.Empty;
				string SubTotalError2 = string.Empty;
				decimal orderSubTotalInclTax = ShoppingCartManager.GetShoppingCartSubTotal(cart, customer, out orderSubTotalDiscount, true, ref SubTotalError1);
				decimal orderSubTotalExclTax = ShoppingCartManager.GetShoppingCartSubTotal(cart, customer, out orderSubTotalDiscount, false, ref SubTotalError2);
				if (!String.IsNullOrEmpty(SubTotalError1) || !String.IsNullOrEmpty(SubTotalError2))
					throw new NopException("Sub total couldn't be calculated");

				decimal orderWeight = ShippingManager.GetShoppingCartTotalWeigth(cart);
				bool shoppingCartRequiresShipping = ShippingManager.ShoppingCartRequiresShipping(cart);
				//if (shoppingCartRequiresShipping)
				//{
				//    if (paymentInfo.ShippingAddress == null)
				//        throw new NopException("Shipping address is not provided");

				//    if (!CommonHelper.IsValidEmail(paymentInfo.ShippingAddress.Email))
				//    {
				//        throw new NopException("Email is not valid");
				//    }
				//}

				string ShippingTotalError1 = string.Empty;
				string ShippingTotalError2 = string.Empty;
				decimal? orderShippingTotalInclTax = ShippingManager.GetShoppingCartShippingTotal(cart, customer, true, ref ShippingTotalError1);
				decimal? orderShippingTotalExclTax = ShippingManager.GetShoppingCartShippingTotal(cart, customer, false, ref ShippingTotalError2);
				if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue)
					throw new NopException("Shipping total couldn't be calculated");

				string PaymentAdditionalFeeError1 = string.Empty;
				string PaymentAdditionalFeeError2 = string.Empty;
				decimal paymentAdditionalFee = PaymentManager.GetAdditionalHandlingFee(paymentInfo.PaymentMethodID);
				decimal paymentAdditionalFeeInclTax = TaxManager.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, customer, ref PaymentAdditionalFeeError1);
				decimal paymentAdditionalFeeExclTax = TaxManager.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, customer, ref PaymentAdditionalFeeError2);
				if (!String.IsNullOrEmpty(PaymentAdditionalFeeError1))
					throw new NopException("Payment method fee couldn't be calculated");
				if (!String.IsNullOrEmpty(PaymentAdditionalFeeError2))
					throw new NopException("Payment method fee couldn't be calculated");

				string TaxError = string.Empty;
				decimal orderTaxTotal = TaxManager.GetTaxTotal(cart, paymentInfo.PaymentMethodID, customer, ref TaxError);
				if (!String.IsNullOrEmpty(TaxError))
					throw new NopException("Tax total couldn't be calculated");

				decimal? orderTotal = ShoppingCartManager.GetShoppingCartTotal(cart, paymentInfo.PaymentMethodID, customer);
				if (!orderTotal.HasValue)
					throw new NopException("Order total couldn't be calculated");
				paymentInfo.OrderTotal = orderTotal.Value;

				decimal orderSubtotalInclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(orderSubTotalInclTax, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
				decimal orderSubtotalExclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(orderSubTotalExclTax, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
				decimal orderShippingInclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(orderShippingTotalInclTax.Value, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
				decimal orderShippingExclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(orderShippingTotalExclTax.Value, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
				decimal paymentAdditionalFeeInclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(paymentAdditionalFeeInclTax, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
				decimal paymentAdditionalFeeExclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(paymentAdditionalFeeExclTax, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
				decimal orderTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(orderTaxTotal, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
				decimal orderTotalInCustomerCurrency = CurrencyManager.ConvertCurrency(orderTotal.Value, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
				string customerCurrencyCode = paymentInfo.CustomerCurrency.CurrencyCode;

				string billingStateProvince = string.Empty;
				int billingStateProvinceID = 0;
				string billingCountry = string.Empty;
				int billingCountryID = 0;
				if (paymentInfo.BillingAddress.StateProvince != null)
				{
					billingStateProvince = paymentInfo.BillingAddress.StateProvince.Name;
					billingStateProvinceID = paymentInfo.BillingAddress.StateProvince.StateProvinceID;
				}
				if (paymentInfo.BillingAddress.Country != null)
				{
					billingCountry = paymentInfo.BillingAddress.Country.Name;
					billingCountryID = paymentInfo.BillingAddress.Country.CountryID;

					if (!paymentInfo.BillingAddress.Country.AllowsBilling)
					{
						throw new NopException(string.Format("{0} is not allowed for billing", billingCountry));
					}
				}
				string shippingFirstName = string.Empty;
				string shippingLastName = string.Empty;
				string shippingPhoneNumber = string.Empty;
				string shippingEmail = string.Empty;
				string shippingFaxNumber = string.Empty;
				string shippingCompany = string.Empty;
				string shippingAddress1 = string.Empty;
				string shippingAddress2 = string.Empty;
				string shippingCity = string.Empty;
				string shippingStateProvince = string.Empty;
				int shippingStateProvinceID = 0;
				string shippingZipPostalCode = string.Empty;
				string shippingCountry = string.Empty;
				int shippingCountryID = 0;
				string shippingMethodName = string.Empty;
				if (shoppingCartRequiresShipping)
				{
					Address shippingAddress = paymentInfo.ShippingAddress;
					if (shippingAddress != null)
					{
						shippingFirstName = shippingAddress.FirstName;
						shippingLastName = shippingAddress.LastName;
						shippingPhoneNumber = shippingAddress.PhoneNumber;
						shippingEmail = shippingAddress.Email;
						shippingFaxNumber = shippingAddress.FaxNumber;
						shippingCompany = shippingAddress.Company;
						shippingAddress1 = shippingAddress.Address1;
						shippingAddress2 = shippingAddress.Address2;
						shippingCity = shippingAddress.City;
						if (shippingAddress.StateProvince != null)
						{
							shippingStateProvince = shippingAddress.StateProvince.Name;
							shippingStateProvinceID = shippingAddress.StateProvince.StateProvinceID;
						}
						shippingZipPostalCode = shippingAddress.ZipPostalCode;
						if (shippingAddress.Country != null)
						{
							shippingCountry = shippingAddress.Country.Name;
							shippingCountryID = shippingAddress.Country.CountryID;

							if (!shippingAddress.Country.AllowsShipping)
							{
								throw new NopException(string.Format("{0} is not allowed for shipping", shippingCountry));
							}
						}
						shippingMethodName = string.Empty;
						ShippingOption shippingOption = customer.LastShippingOption;
						if (shippingOption != null)
							shippingMethodName = shippingOption.Name;
					}
				}

				int activeShippingRateComputationMethodID = 0;
				ShippingRateComputationMethod activeShippingRateComputationMethod = ShippingManager.ActiveShippingRateComputationMethod;
				if (activeShippingRateComputationMethod != null)
				{
					activeShippingRateComputationMethodID = activeShippingRateComputationMethod.ShippingRateComputationMethodID;
				}

				//PaymentManager.ProcessPayment(paymentInfo, customer, OrderGuid, ref processPaymentResult);

				int customerLanguageID = paymentInfo.CustomerLanguage.LanguageID;
				if (String.IsNullOrEmpty(processPaymentResult.Error))
				{
					ShippingStatusEnum shippingStatusEnum = ShippingStatusEnum.NotYetShipped;
					if (!shoppingCartRequiresShipping)
						shippingStatusEnum = ShippingStatusEnum.ShippingNotRequired;

					Order order = InsertOrder(OrderGuid,
						 customer.CustomerID,
						 customerLanguageID,
						 customerTaxDisplayType,
						 orderSubTotalInclTax,
						 orderSubTotalExclTax,
						 orderShippingTotalInclTax.Value,
						 orderShippingTotalExclTax.Value,
						 paymentAdditionalFeeInclTax,
						 paymentAdditionalFeeExclTax,
						 orderTaxTotal,
						 orderTotal.Value,
						 orderSubTotalDiscount,
						 orderSubtotalInclTaxInCustomerCurrency,
						 orderSubtotalExclTaxInCustomerCurrency,
						 orderShippingInclTaxInCustomerCurrency,
						 orderShippingExclTaxInCustomerCurrency,
						 paymentAdditionalFeeInclTaxInCustomerCurrency,
						 paymentAdditionalFeeExclTaxInCustomerCurrency,
						 orderTaxInCustomerCurrency,
						 orderTotalInCustomerCurrency,
						 customerCurrencyCode,
						 orderWeight,
						 customer.AffiliateID,
						 OrderStatusEnum.Pending,
						 processPaymentResult.AllowStoringCreditCardNumber,
						 SecurityHelper.Encrypt(paymentInfo.CreditCardType),
						 SecurityHelper.Encrypt(paymentInfo.CreditCardName),
						 SecurityHelper.Encrypt(paymentInfo.CreditCardNumber),
						 SecurityHelper.Encrypt(PaymentManager.GetMaskedCreditCardNumber(paymentInfo.CreditCardNumber)),
						 processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Encrypt(paymentInfo.CreditCardCVV2) : string.Empty,
						 SecurityHelper.Encrypt(paymentInfo.CreditCardExpireMonth.ToString()),
						 SecurityHelper.Encrypt(paymentInfo.CreditCardExpireYear.ToString()),
						 paymentMethod.PaymentMethodID,
						 paymentMethod.Name,
						 processPaymentResult.AuthorizationTransactionID,
						 processPaymentResult.AuthorizationTransactionCode,
						 processPaymentResult.AuthorizationTransactionResult,
						 processPaymentResult.CaptureTransactionID,
						 processPaymentResult.CaptureTransactionResult,
						 paymentInfo.PurchaseOrderNumber,
						 processPaymentResult.PaymentStatus,
						 paymentInfo.BillingAddress.FirstName,
						 paymentInfo.BillingAddress.LastName,
						 paymentInfo.BillingAddress.PhoneNumber,
						 paymentInfo.BillingAddress.Email,
						 paymentInfo.BillingAddress.FaxNumber,
						 paymentInfo.BillingAddress.Company,
						 paymentInfo.BillingAddress.Address1,
						 paymentInfo.BillingAddress.Address2,
						 paymentInfo.BillingAddress.City,
						 billingStateProvince,
						 billingStateProvinceID,
						 paymentInfo.BillingAddress.ZipPostalCode,
						 billingCountry,
						 billingCountryID,
						 shippingStatusEnum,
						 shippingFirstName,
						 shippingLastName,
						 shippingPhoneNumber,
						 shippingEmail,
						 shippingFaxNumber,
						 shippingCompany,
						 shippingAddress1,
						 shippingAddress2,
						 shippingCity,
						 shippingStateProvince,
						 shippingStateProvinceID,
						 shippingZipPostalCode,
						 shippingCountry,
						 shippingCountryID,
						 shippingMethodName,
						 activeShippingRateComputationMethodID,
						 null,
						 false,
						 DateTime.Now);

					OrderID = order.OrderID;

					foreach (ShoppingCartItem sc in cart)
					{
						decimal scUnitPriceInclTax = TaxManager.GetPrice(sc.ProductVariant, PriceHelper.GetUnitPrice(sc, customer, true), true, customer);
						decimal scUnitPriceExclTax = TaxManager.GetPrice(sc.ProductVariant, PriceHelper.GetUnitPrice(sc, customer, true), false, customer);
						decimal scSubTotalInclTax = TaxManager.GetPrice(sc.ProductVariant, PriceHelper.GetSubTotal(sc, customer, true), true, customer);
						decimal scSubTotalExclTax = TaxManager.GetPrice(sc.ProductVariant, PriceHelper.GetSubTotal(sc, customer, true), false, customer);
						decimal scUnitPriceInclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(scUnitPriceInclTax, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
						decimal scUnitPriceExclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(scUnitPriceExclTax, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
						decimal scSubTotalInclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(scSubTotalInclTax, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);
						decimal scSubTotalExclTaxInCustomerCurrency = CurrencyManager.ConvertCurrency(scSubTotalExclTax, CurrencyManager.PrimaryStoreCurrency, paymentInfo.CustomerCurrency);

						decimal discountAmountInclTax = TaxManager.GetPrice(sc.ProductVariant, PriceHelper.GetDiscountAmount(sc, customer), true, customer);
						decimal discountAmountExclTax = TaxManager.GetPrice(sc.ProductVariant, PriceHelper.GetDiscountAmount(sc, customer), false, customer);

						string attributeDescription = ProductAttributeHelper.FormatAttributes(sc.ProductVariant, sc.AttributesXML);

						InsertOrderProductVariant(order.OrderID,
							sc.ProductVariantID, scUnitPriceInclTax, scUnitPriceExclTax, scSubTotalInclTax, scSubTotalExclTax,
							scUnitPriceInclTaxInCustomerCurrency, scUnitPriceExclTaxInCustomerCurrency,
							scSubTotalInclTaxInCustomerCurrency, scSubTotalExclTaxInCustomerCurrency,
							attributeDescription, sc.Quantity, discountAmountInclTax, discountAmountExclTax, 0);

						ProductManager.AdjustInventory(sc.ProductVariantID, true, sc.Quantity);
					}

					InsertOrderNote(OrderID, string.Format("Order placed"), DateTime.Now);

					//int orderPlacedStoreOwnerNotificationQueuedEmailID = MessageManager.SendOrderPlacedStoreOwnerNotification(order, LocalizationManager.DefaultAdminLanguage.LanguageID);
					//InsertOrderNote(OrderID, string.Format("\"Order placed\" email (to store owner) has been queued. Queued email identifier: {0}.", orderPlacedStoreOwnerNotificationQueuedEmailID), DateTime.Now);

					//int orderPlacedCustomerNotificationQueuedEmailID = MessageManager.SendOrderPlacedCustomerNotification(order, order.CustomerLanguageID);
					//InsertOrderNote(OrderID, string.Format("\"Order placed\" email (to customer) has been queued. Queued email identifier: {0}.", orderPlacedCustomerNotificationQueuedEmailID), DateTime.Now);

					order = CheckOrderStatus(order.OrderID);

					CustomerManager.ResetCheckoutData(customer.CustomerID, true);
				}
			}
			catch (Exception exc)
			{
				processPaymentResult.Error = exc.Message;
				processPaymentResult.FullError = exc.ToString();
			}

			if (!String.IsNullOrEmpty(processPaymentResult.Error))
			{
				LogManager.InsertLog(LogTypeEnum.OrderError, string.Format("Error while placing order. {0}", processPaymentResult.Error), processPaymentResult.FullError);
			}
			return processPaymentResult.Error;
		}
 /// <summary>
 /// Process payment
 /// </summary>
 /// <param name="paymentInfo">Payment info required for an order processing</param>
 /// <param name="customer">Customer</param>
 /// <param name="orderGuid">Unique order identifier</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     processPaymentResult.PaymentStatus = PaymentStatusEnum.Pending;
 }
        protected void btnNextStep_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    var paymentInfo = this.PaymentInfo;

                    if (paymentInfo == null)
                    {
                        var args1 = new CheckoutStepEventArgs() { OrderConfirmed = false };
                        OnCheckoutStepChanged(args1);
                        if (!this.OnePageCheckout)
                        {
                            Response.Redirect("~/checkoutpaymentinfo.aspx");
                        }
                        else
                        {
                            return;
                        }
                    }
                    paymentInfo.BillingAddress = NopContext.Current.User.BillingAddress;
                    paymentInfo.ShippingAddress = NopContext.Current.User.ShippingAddress;
                    paymentInfo.CustomerLanguage = NopContext.Current.WorkingLanguage;
                    paymentInfo.CustomerCurrency = NopContext.Current.WorkingCurrency;

                    int orderId = 0;
                    string orderNote = txtNoteToSeller.Value.Trim().Length > 0 ? txtNoteToSeller.Value.Trim() : string.Empty;

                    string result = this.OrderService.PlaceOrder(paymentInfo, NopContext.Current.User, _vendorId, orderNote, out orderId);

                    this.PaymentInfo = null;
                    var order = this.OrderService.GetOrderById(orderId);

                    //if (txtNoteToSeller.Value.Trim().Length > 0) {
                    //    OrderService.InsertOrderNote(orderId, txtNoteToSeller.Value.Trim(), true, DateTime.Now);
                    //}

                    if (!String.IsNullOrEmpty(result))
                    {
                        lConfirmOrderError.Text = Server.HtmlEncode(result);
                        return;
                    }
                    else
                    {
                        hidPaypalURL.Value = this.PaymentService.PostProcessPayment(order);
                    }

                    var args2 = new CheckoutStepEventArgs() { OrderConfirmed = true };
                    if (hidPaypalURL.Value != String.Empty)
                    {
                        //redirect via javascript, directly into the frame.
                        //Response.Redirect(hidPaypalURL.Value, false);
                    }
                    else
                    {
                        OnCheckoutStepChanged(args2);
                    }

                    if (!this.OnePageCheckout)
                        Response.Redirect("~/checkoutcompleted.aspx");
                }
                catch (Exception exc)
                {
                    this.LogService.InsertLog(LogTypeEnum.OrderError, exc.Message, exc);
                    lConfirmOrderError.Text = Server.HtmlEncode(exc.ToString());
                }
            }
            else
            {
                foreach (System.Web.UI.IValidator poo in Page.Validators)
                {
                    if (!poo.IsValid) {
                        if (lConfirmOrderError.Text == String.Empty)
                        {
                            lConfirmOrderError.Text = poo.ErrorMessage;
                        }
                        else
                        {
                            lConfirmOrderError.Text += poo.ErrorMessage;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessRecurringPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            MerchantAuthenticationType authentication = PopulateMerchantAuthentication();
            if (!paymentInfo.IsRecurringPayment)
            {
                ARBSubscriptionType subscription = new ARBSubscriptionType();
                NopSolutions.NopCommerce.Payment.Methods.AuthorizeNet.net.authorize.api.CreditCardType creditCard = new NopSolutions.NopCommerce.Payment.Methods.AuthorizeNet.net.authorize.api.CreditCardType();

                subscription.name = orderGuid.ToString();

                creditCard.cardNumber = paymentInfo.CreditCardNumber;
                creditCard.expirationDate = paymentInfo.CreditCardExpireYear + "-" + paymentInfo.CreditCardExpireMonth; // required format for API is YYYY-MM
                creditCard.cardCode = paymentInfo.CreditCardCvv2;

                subscription.payment = new PaymentType();
                subscription.payment.Item = creditCard;

                subscription.billTo = new NameAndAddressType();
                subscription.billTo.firstName = paymentInfo.BillingAddress.FirstName;
                subscription.billTo.lastName = paymentInfo.BillingAddress.LastName;
                subscription.billTo.address = paymentInfo.BillingAddress.Address1 + " " + paymentInfo.BillingAddress.Address2;
                subscription.billTo.city = paymentInfo.BillingAddress.City;
                if (paymentInfo.BillingAddress.StateProvince != null)
                {
                    subscription.billTo.state = paymentInfo.BillingAddress.StateProvince.Abbreviation;
                }
                subscription.billTo.zip = paymentInfo.BillingAddress.ZipPostalCode;

                if (paymentInfo.ShippingAddress != null)
                {
                    subscription.shipTo = new NameAndAddressType();
                    subscription.shipTo.firstName = paymentInfo.ShippingAddress.FirstName;
                    subscription.shipTo.lastName = paymentInfo.ShippingAddress.LastName;
                    subscription.shipTo.address = paymentInfo.ShippingAddress.Address1 + " " + paymentInfo.ShippingAddress.Address2;
                    subscription.shipTo.city = paymentInfo.ShippingAddress.City;
                    if (paymentInfo.ShippingAddress.StateProvince != null)
                    {
                        subscription.shipTo.state = paymentInfo.ShippingAddress.StateProvince.Abbreviation;
                    }
                    subscription.shipTo.zip = paymentInfo.ShippingAddress.ZipPostalCode;

                }

                subscription.customer = new CustomerType();
                subscription.customer.email = customer.BillingAddress.Email;
                subscription.customer.phoneNumber = customer.BillingAddress.PhoneNumber;

                subscription.order = new OrderType();
                subscription.order.description = string.Format("{0} {1}", IoC.Resolve<ISettingManager>().StoreName, "Recurring payment");

                // Create a subscription that is leng of specified occurrences and interval is amount of days ad runs

                subscription.paymentSchedule = new PaymentScheduleType();
                DateTime dtNow = DateTime.UtcNow;
                subscription.paymentSchedule.startDate = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day);
                subscription.paymentSchedule.startDateSpecified = true;

                subscription.paymentSchedule.totalOccurrences = Convert.ToInt16(paymentInfo.RecurringTotalCycles);
                subscription.paymentSchedule.totalOccurrencesSpecified = true;

                subscription.amount = paymentInfo.OrderTotal;
                subscription.amountSpecified = true;

                // Interval can't be updated once a subscription is created.
                subscription.paymentSchedule.interval = new PaymentScheduleTypeInterval();
                switch (paymentInfo.RecurringCyclePeriod)
                {
                    case (int)RecurringProductCyclePeriodEnum.Days:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(paymentInfo.RecurringCycleLength);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.days;
                        break;
                    case (int)RecurringProductCyclePeriodEnum.Weeks:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(paymentInfo.RecurringCycleLength * 7);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.days;
                        break;
                    case (int)RecurringProductCyclePeriodEnum.Months:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(paymentInfo.RecurringCycleLength);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.months;
                        break;
                    case (int)RecurringProductCyclePeriodEnum.Years:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(paymentInfo.RecurringCycleLength * 12);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.months;
                        break;
                    default:
                        throw new NopException("Not supported cycle period");
                }

                ARBCreateSubscriptionResponseType response = webService.ARBCreateSubscription(authentication, subscription);

                if (response.resultCode == MessageTypeEnum.Ok)
                {
                    processPaymentResult.SubscriptionTransactionId = response.subscriptionId.ToString();
                    processPaymentResult.AuthorizationTransactionCode = response.resultCode.ToString();
                    processPaymentResult.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.resultCode.ToString(), response.subscriptionId.ToString());
                }
                else
                {
                    processPaymentResult.Error = string.Format("Error processing recurring payment. {0}", GetErrors(response));
                    processPaymentResult.FullError = string.Format("Error processing recurring payment. {0}", GetErrors(response));
                }
            }
        }
 /// <summary>
 /// Process payment
 /// </summary>
 /// <param name="paymentInfo">Payment info required for an order processing</param>
 /// <param name="customer">Customer</param>
 /// <param name="orderGuid">Unique order identifier</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     DoExpressCheckout(paymentInfo, orderGuid, processPaymentResult);
 }
Esempio n. 24
0
 public PaymentInfo GetPaymentInfo()
 {
     PaymentInfo paymentInfo = new PaymentInfo();
     return paymentInfo;
 }
 /// <summary>
 /// Process recurring payment
 /// </summary>
 /// <param name="paymentInfo">Payment info required for an order processing</param>
 /// <param name="customer">Customer</param>
 /// <param name="orderGuid">Unique order identifier</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void ProcessRecurringPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     throw new NopException("Recurring payments not supported");
 }
 /// <summary>
 /// Process payment
 /// </summary>
 /// <param name="paymentInfo">Payment info required for an order processing</param>
 /// <param name="customer">Customer</param>
 /// <param name="orderGuid">Unique order identifier</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     processPaymentResult.AllowStoringCreditCardNumber = true;
     TransactMode transactionMode = GetCurrentTransactionMode();
     switch (transactionMode)
     {
         case TransactMode.Pending:
             processPaymentResult.PaymentStatus = PaymentStatusEnum.Pending;
             break;
         case TransactMode.Authorize:
             processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
             break;
         case TransactMode.AuthorizeAndCapture:
             processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
             break;
         default:
             throw new NopException("Not supported transact type");
     }
 }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="OrderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid OrderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            //little hack here
            CultureInfo userCulture = Thread.CurrentThread.CurrentCulture;
            NopContext.Current.SetCulture(new CultureInfo("en-US"));
            try
            {
                BillTo to = new BillTo();
                to.FirstName = paymentInfo.BillingAddress.FirstName;
                to.LastName = paymentInfo.BillingAddress.LastName;
                to.Street = paymentInfo.BillingAddress.Address1;
                to.City = paymentInfo.BillingAddress.City;
                to.Zip = paymentInfo.BillingAddress.ZipPostalCode;
                if (paymentInfo.BillingAddress.StateProvince != null)
                    to.State = paymentInfo.BillingAddress.StateProvince.Abbreviation;
                ShipTo to2 = new ShipTo();
                to2.ShipToFirstName = paymentInfo.ShippingAddress.FirstName;
                to2.ShipToLastName = paymentInfo.ShippingAddress.LastName;
                to2.ShipToStreet = paymentInfo.ShippingAddress.Address1;
                to2.ShipToCity = paymentInfo.ShippingAddress.City;
                to2.ShipToZip = paymentInfo.ShippingAddress.ZipPostalCode;
                if (paymentInfo.ShippingAddress.StateProvince != null)
                    to2.ShipToState = paymentInfo.ShippingAddress.StateProvince.Abbreviation;

                Invoice invoice = new Invoice();
                invoice.BillTo = to;
                invoice.ShipTo = to2;
                invoice.InvNum = OrderGuid.ToString();
                //For values which have more than two decimal places 
                //Currency Amt = new Currency(new decimal(25.1214));
                //Amt.NoOfDecimalDigits = 2;
                //If the NoOfDecimalDigits property is used then it is mandatory to set one of the following properties to true.
                //Amt.Round = true;
                //Amt.Truncate = true;
                //Inv.Amt = Amt;
                decimal orderTotal = Math.Round(paymentInfo.OrderTotal, 2);
                //UNDONE USD only
                invoice.Amt = new PayPal.Payments.DataObjects.Currency(orderTotal, CurrencyManager.PrimaryStoreCurrency.CurrencyCode);

                string creditCardExp = string.Empty;
                if (paymentInfo.CreditCardExpireMonth < 10)
                {
                    creditCardExp = "0" + paymentInfo.CreditCardExpireMonth.ToString();
                }
                else
                {
                    creditCardExp = paymentInfo.CreditCardExpireMonth.ToString();
                }
                creditCardExp = creditCardExp + paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2);
                CreditCard credCard = new CreditCard(paymentInfo.CreditCardNumber, creditCardExp);
                credCard.Cvv2 = paymentInfo.CreditCardCVV2;
                CardTender tender = new CardTender(credCard);
                // <vendor> = your merchant (login id)  
                // <user> = <vendor> unless you created a separate <user> for Payflow Pro
                // partner = paypal
                UserInfo userInfo = new UserInfo(user, vendor, partner, password);
                string url = GetPaypalUrl();
                PayflowConnectionData payflowConnectionData = new PayflowConnectionData(url, 443, null, 0, null, null);

                Response response = null;
                if (transactionMode == TransactMode.Authorize)
                {
                    response = new AuthorizationTransaction(userInfo, payflowConnectionData, invoice, tender, PayflowUtility.RequestId).SubmitTransaction();
                }
                else
                {
                    response = new SaleTransaction(userInfo, payflowConnectionData, invoice, tender, PayflowUtility.RequestId).SubmitTransaction();
                }

                if (response.TransactionResponse != null)
                {
                    if (response.TransactionResponse.Result == 0)
                    {
                        processPaymentResult.AuthorizationTransactionID = response.TransactionResponse.Pnref;
                        processPaymentResult.AuthorizationTransactionResult = response.TransactionResponse.RespMsg;

                        if (transactionMode == TransactMode.Authorize)
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                        }
                        else
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                        }
                    }
                    else
                    {
                        processPaymentResult.Error = string.Format("{0} - {1}", response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
                        processPaymentResult.FullError = string.Format("Response Code : {0}. Response Description : {1}", response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
                    }
                }
                else
                {
                    processPaymentResult.Error = "Error during checkout";
                    processPaymentResult.FullError = "Error during checkout";
                }
            }
            catch (Exception exc)
            {
                throw;
            }
            finally
            {
                NopContext.Current.SetCulture(userCulture);
            }
        }
        public void ExecutePayStatus(string paykey, string strmaxAmount)
        {
            StringBuilder dataToSend = new StringBuilder();
            string strRequest = null;
            strRequest = strRequest + "requestEnvelope.errorLanguage=" + NopContext.Current.WorkingLanguage.LanguageCulture;
            strRequest = strRequest + "&requestEnvelope.detailLevel=ReturnAll";
            strRequest = strRequest + "&payKey=" + paykey;
            strRequest = strRequest + "&returnUrl=" + ConfigurationManager.AppSettings["returnUrl"];// "https://localhost:8091/SewbieDemo/PaypalAPRedirect.aspx";
            dataToSend.Append(strRequest);
            string Execute_strEndpointURL = ConfigurationManager.AppSettings["ExecuteDetails_strEndpointURL"];
            try
            {
                string strResponse = this.GetResponce(dataToSend, Execute_strEndpointURL);
                string[] strSplited = strResponse.Split('&');
                string strPayKey = null;
                string strTmp = strSplited[1];
                strTmp = strTmp.Substring(21, 7);
                if (strTmp == "Success")
                {
                    strPayKey = strSplited[4];
                    strPayKey = strPayKey.Substring(7, 20);
                    int j = 0;
                    string strTransactionIds = "";
                    string strStatus = "";
                    for (int i = 0; i < strSplited.Length; i++)
                    {
                        if (strSplited[i].Contains("paymentInfoList.paymentInfo(" + j.ToString() + ").senderTransactionId="))
                        {
                            if (string.IsNullOrEmpty(strTransactionIds))
                                strTransactionIds = strSplited[i].Split('=')[1].ToString();
                            else
                                strTransactionIds += "," + strSplited[i].Split('=')[1].ToString();
                            j++;
                        }
                        if (strSplited[i].Contains("status="))
                            strStatus = strSplited[i].Split('=')[1].ToString();
                    }
                    if (strStatus == "CREATED")
                    {
                        Response.Redirect(ConfigurationManager.AppSettings["PayPalSuccessReturnUrl"] + strmaxAmount + "&strTransactionIds=" + strTransactionIds + "&strStatus=" + strStatus);
                    }
                    var paymentInfo = this.PaymentInfo;
                    paymentInfo = new BusinessLogic.Payment.PaymentInfo();
                    paymentInfo.BillingAddress = NopContext.Current.User.BillingAddress;
                    paymentInfo.ShippingAddress = NopContext.Current.User.ShippingAddress;
                    paymentInfo.CustomerLanguage = NopContext.Current.WorkingLanguage;
                    paymentInfo.CustomerCurrency = NopContext.Current.WorkingCurrency;
                    paymentInfo.PaymentMethodId = 43;
                    int orderId = 0;

                    string result = this.OrderService.PlaceOrder(paymentInfo, NopContext.Current.User, out orderId);

                    this.PaymentInfo = null;
                    var order = this.OrderService.GetOrderById(orderId);

                    if (txtNoteToSeller.Value.Trim().Length > 0)
                    {
                        OrderService.InsertOrderNote(orderId, txtNoteToSeller.Value.Trim(), DateTime.Now);
                    }

                    if (!String.IsNullOrEmpty(result))
                    {
                        lConfirmOrderError.Text = Server.HtmlEncode(result);
                        return;
                    }
                    else
                    {
                       // hidPaypalURL.Value = this.PaymentService.PostProcessPayment(order);
                    }

                    var args2 = new CheckoutStepEventArgs() { OrderConfirmed = true };
                    if (hidPaypalURL.Value != String.Empty)
                    {
                        //redirect via javascript, directly into the frame.
                        //Response.Redirect(hidPaypalURL.Value, false);
                    }
                    else
                    {
                        OnCheckoutStepChanged(args2);
                    }

                    Response.Redirect(ConfigurationManager.AppSettings["PayPalSuccessReturnUrl"] + strmaxAmount + "&strTransactionIds=" + strTransactionIds + "&strStatus=" + strStatus);
                }
            }
            catch (Exception ex)
            {
                Response.Redirect(ConfigurationManager.AppSettings["PayPalSuccessReturnUrl"] + strmaxAmount + "&strStatus=Failed" + "&strTransactionIds=");
            }
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessRecurringPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            processPaymentResult.AllowStoringCreditCardNumber = true;
            TransactMode transactionMode = GetCurrentTransactionMode();
            switch (transactionMode)
            {
                case TransactMode.Pending:
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Pending;
                    break;
                case TransactMode.Authorize:
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                    break;
                case TransactMode.AuthorizeAndCapture:
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                    break;
                default:
                    throw new NopException("Not supported transact type");
            }

            //restore credit cart info
            if (paymentInfo.IsRecurringPayment)
            {
                Order initialOrder = OrderManager.GetOrderById(paymentInfo.InitialOrderId);
                if (initialOrder != null)
                {
                    paymentInfo.CreditCardType = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Decrypt(initialOrder.CardType) : string.Empty;
                    paymentInfo.CreditCardName = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Decrypt(initialOrder.CardName) : string.Empty;
                    paymentInfo.CreditCardNumber = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Decrypt(initialOrder.CardNumber) : string.Empty;
                    paymentInfo.CreditCardCvv2 = processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Decrypt(initialOrder.CardCvv2) : string.Empty;
                    try
                    {
                        paymentInfo.CreditCardExpireMonth = Convert.ToInt32(processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Decrypt(initialOrder.CardExpirationMonth) : "0");
                        paymentInfo.CreditCardExpireYear = Convert.ToInt32(processPaymentResult.AllowStoringCreditCardNumber ? SecurityHelper.Decrypt(initialOrder.CardExpirationYear) : "0");
                    }
                    catch
                    {
                    }
                }
            }
        }
Esempio n. 30
0
 /// <summary>
 /// Places an order
 /// </summary>
 /// <param name="paymentInfo">Payment info</param>
 /// <param name="customer">Customer</param>
 /// <param name="orderId">Order identifier</param>
 /// <returns>The error status, or String.Empty if no errors</returns>
 public string PlaceOrder(PaymentInfo paymentInfo, Customer customer, 
     out int orderId)
 {
     var orderGuid = Guid.NewGuid();
     return PlaceOrder(paymentInfo, customer, orderGuid, out orderId);
 }