Ejemplo n.º 1
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);
     }
 }
		/// <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();
			
			WebClient webClient = new WebClient();
			NameValueCollection form = new NameValueCollection();
			form.Add("gwlogin", loginID);
			if (!string.IsNullOrEmpty(RestrictKey))
				form.Add("RestrictKey", RestrictKey);
			form.Add("trans_method", "CC");
			form.Add("CVVtype", "1");
            form.Add("Dsep", "|");
			form.Add("MAXMIND", "1");

			form.Add("amount", paymentInfo.OrderTotal.ToString("####.00", new CultureInfo("en-US", false).NumberFormat));
			form.Add("ccnum", paymentInfo.CreditCardNumber);
			form.Add("ccmo", paymentInfo.CreditCardExpireMonth.ToString("D2"));
			form.Add("ccyr", paymentInfo.CreditCardExpireYear.ToString());
			form.Add("CVV2", paymentInfo.CreditCardCVV2);

			form.Add("FNAME", paymentInfo.BillingAddress.FirstName);
			form.Add("LNAME", paymentInfo.BillingAddress.LastName);

			if (string.IsNullOrEmpty(paymentInfo.BillingAddress.Company))
				form.Add("company", paymentInfo.BillingAddress.Company);

			form.Add("BADDR1", paymentInfo.BillingAddress.Address1);
			form.Add("BCITY", paymentInfo.BillingAddress.City);
			if (paymentInfo.BillingAddress.StateProvince != null)
				form.Add("BSTATE", paymentInfo.BillingAddress.StateProvince.Name);
			form.Add("BZIP1", paymentInfo.BillingAddress.ZipPostalCode);
			if (paymentInfo.BillingAddress.Country != null)
				form.Add("BCOUNTRY", paymentInfo.BillingAddress.Country.TwoLetterISOCode);
			form.Add("invoice_num", OrderGuid.ToString());
			form.Add("customer_ip", HttpContext.Current.Request.UserHostAddress);
			form.Add("BCUST_EMAIL", paymentInfo.BillingAddress.Email);


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

			if (null != reply)
			{
				processPaymentResult.AuthorizationTransactionResult = reply;

				string[] responseFields = reply.Split('|');
				switch (responseFields[0])
				{
					case "\"APPROVED\"":
						processPaymentResult.AuthorizationTransactionCode = responseFields[1];
						processPaymentResult.AVSResult = "AVRResponse: " + responseFields[3] + " Max Score:" + responseFields[5];
						processPaymentResult.AuthorizationTransactionID = responseFields[2]; //responseFields[38];
						processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
						break;
					case "\"DECLINED\"":
						processPaymentResult.Error = responseFields[6];
						processPaymentResult.FullError = responseFields[7] + " " + responseFields[6];
						break;
				}
			}
			else
			{
				processPaymentResult.Error = "CDGcommerce unknown error";
				processPaymentResult.FullError = "CDGcommerce unknown error";
			}
		}
Ejemplo n.º 3
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)
 {
     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 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)
 {
     DoExpressCheckout(paymentInfo, orderGuid, processPaymentResult);
 }
        /// <summary>
        /// Captures payment
        /// </summary>
        /// <param name="order">Order</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void Capture(Order order, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();

            string authorizationID = processPaymentResult.AuthorizationTransactionId;
            DoCaptureReq req = new DoCaptureReq();
            req.DoCaptureRequest = new DoCaptureRequestType();
            req.DoCaptureRequest.Version = this.APIVersion;
            req.DoCaptureRequest.AuthorizationID = authorizationID;
            req.DoCaptureRequest.Amount = new BasicAmountType();
            req.DoCaptureRequest.Amount.Value = order.OrderTotal.ToString("N", new CultureInfo("en-us"));
            req.DoCaptureRequest.Amount.currencyID = PaypalHelper.GetPaypalCurrency(IoC.Resolve<ICurrencyService>().PrimaryStoreCurrency);
            req.DoCaptureRequest.CompleteType = CompleteCodeType.Complete;
            DoCaptureResponseType response = service2.DoCapture(req);

            string error = string.Empty;
            bool Success = PaypalHelper.CheckSuccess(response, out error);
            if (Success)
            {
                processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                processPaymentResult.CaptureTransactionId = response.DoCaptureResponseDetails.PaymentInfo.TransactionID;
                processPaymentResult.CaptureTransactionResult = response.Ack.ToString();
            }
            else
            {
                processPaymentResult.Error = error;
            }
        }
Ejemplo n.º 7
0
		/// <summary>
		/// Captures order (from admin panel)
		/// </summary>
		/// <param name="OrderID">Order identifier</param>
		/// <param name="Error">Error</param>
		/// <returns>Captured order</returns>
		public static Order Capture(int OrderID, ref string Error)
		{
			Order order = GetOrderByID(OrderID);
			if (order == null)
				return order;

			if (!CanCapture(order))
				throw new NopException("Can not do capture for order.");

			ProcessPaymentResult processPaymentResult = new ProcessPaymentResult();
			try
			{
				//old info from placing order
				processPaymentResult.AuthorizationTransactionID = order.AuthorizationTransactionID;
				processPaymentResult.AuthorizationTransactionCode = order.AuthorizationTransactionCode;
				processPaymentResult.AuthorizationTransactionResult = order.AuthorizationTransactionResult;
				processPaymentResult.CaptureTransactionID = order.CaptureTransactionID;
				processPaymentResult.CaptureTransactionResult = order.CaptureTransactionResult;
				processPaymentResult.PaymentStatus = order.PaymentStatus;

				PaymentManager.Capture(order, ref processPaymentResult);

				if (String.IsNullOrEmpty(processPaymentResult.Error))
				{
					InsertOrderNote(order.OrderID, string.Format("Order has been captured"), DateTime.Now);

					order = UpdateOrder(order.OrderID, order.OrderGUID, order.CustomerID, order.CustomerLanguageID,
						order.CustomerTaxDisplayType, order.OrderSubtotalInclTax, order.OrderSubtotalExclTax, order.OrderShippingInclTax,
						order.OrderShippingExclTax, order.PaymentMethodAdditionalFeeInclTax, order.PaymentMethodAdditionalFeeExclTax,
						order.OrderTax, order.OrderTotal, order.OrderDiscount,
						order.OrderSubtotalInclTaxInCustomerCurrency, order.OrderSubtotalExclTaxInCustomerCurrency,
						order.OrderShippingInclTaxInCustomerCurrency, order.OrderShippingExclTaxInCustomerCurrency,
						order.PaymentMethodAdditionalFeeInclTaxInCustomerCurrency, order.PaymentMethodAdditionalFeeExclTaxInCustomerCurrency,
						order.OrderTaxInCustomerCurrency, order.OrderTotalInCustomerCurrency, order.CustomerCurrencyCode, order.OrderWeight,
						order.AffiliateID, order.OrderStatus, order.AllowStoringCreditCardNumber,
						order.CardType, order.CardName, order.CardNumber, order.MaskedCreditCardNumber,
						order.CardCVV2, order.CardExpirationMonth, order.CardExpirationYear,
						order.PaymentMethodID, order.PaymentMethodName,
						processPaymentResult.AuthorizationTransactionID,
						processPaymentResult.AuthorizationTransactionCode,
						processPaymentResult.AuthorizationTransactionResult,
						processPaymentResult.CaptureTransactionID,
						processPaymentResult.CaptureTransactionResult,
						order.PurchaseOrderNumber,
						processPaymentResult.PaymentStatus,
						order.BillingFirstName, order.BillingLastName, order.BillingPhoneNumber,
						order.BillingEmail, order.BillingFaxNumber, order.BillingCompany, order.BillingAddress1,
						order.BillingAddress2, order.BillingCity,
						order.BillingStateProvince, order.BillingStateProvinceID, order.BillingZipPostalCode,
						order.BillingCountry, order.BillingCountryID, order.ShippingStatus,
						order.ShippingFirstName, order.ShippingLastName, order.ShippingPhoneNumber,
						order.ShippingEmail, order.ShippingFaxNumber, order.ShippingCompany,
						order.ShippingAddress1, order.ShippingAddress2, order.ShippingCity,
						order.ShippingStateProvince, order.ShippingStateProvinceID, order.ShippingZipPostalCode,
						order.ShippingCountry, order.ShippingCountryID,
						order.ShippingMethod, order.ShippingRateComputationMethodID, order.ShippedDate, order.Deleted,
						order.CreatedOn);
				}
				else
				{
					InsertOrderNote(order.OrderID, string.Format("Unable to capture order. Error: {0}", processPaymentResult.Error), DateTime.Now);

				}
				order = CheckOrderStatus(order.OrderID);
			}
			catch (Exception exc)
			{
				processPaymentResult.Error = exc.Message;
				processPaymentResult.FullError = exc.ToString();
			}

			if (!String.IsNullOrEmpty(processPaymentResult.Error))
			{
				Error = processPaymentResult.Error;
				LogManager.InsertLog(LogTypeEnum.OrderError, string.Format("Error capturing order. {0}", processPaymentResult.Error), processPaymentResult.FullError);
			}
			return order;
		}
Ejemplo 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;
        }
        /// <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)
        {
            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>
        /// Captures payment
        /// </summary>
        /// <param name="order">Order</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void Capture(Order order, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();

            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);
            form.Add("x_type", "PRIOR_AUTH_CAPTURE");

            form.Add("x_amount", order.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            string[] codes = processPaymentResult.AuthorizationTransactionCode.Split(',');
            //x_trans_id. When x_test_request (sandbox) is set to a positive response,
            //or when Test mode is enabled on the payment gateway, this value will be "0".
            form.Add("x_trans_id", codes[0]);

            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];
                        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";
            }
        }
Ejemplo n.º 12
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)
        {
            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;
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Captures payment (from admin panel)
        /// </summary>
        /// <param name="order">Order</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void Capture(Order order, 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 = "";

            success = sxml.processAdvice(order.OrderTotal,order.OrderGuid.ToString(),processPaymentResult.AuthorizationTransactionCode);

            code = sxml["response_code"];

            if (!success)
            {
                processPaymentResult.Error = String.Format("Declined ({0})", code);
                processPaymentResult.FullError = sxml.Error;
            }
            else
            {
                processPaymentResult.CaptureTransactionId = sxml["transaction_id"];
                processPaymentResult.CaptureTransactionResult = String.Format("Approved ({0})", code);

                processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
            }
        }
 /// <summary>
 /// Captures payment (from admin panel)
 /// </summary>
 /// <param name="order">Order</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void Capture(Order order, ref ProcessPaymentResult processPaymentResult)
 {
     //TODO implement capture from admin panel using CaptureTransaction object
     throw new NopException("Capture method 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)
        {
            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);
            }
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Captures payment (from admin panel)
 /// </summary>
 /// <param name="order">Order</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public static void Capture(Order order, ref ProcessPaymentResult processPaymentResult)
 {
     PaymentMethod paymentMethod = PaymentMethodManager.GetPaymentMethodByID(order.PaymentMethodID);
     if (paymentMethod == null)
         throw new NopException("Payment method couldn't be loaded");
     IPaymentMethod iPaymentMethod = Activator.CreateInstance(Type.GetType(paymentMethod.ClassName)) as IPaymentMethod;
     iPaymentMethod.Capture(order, ref processPaymentResult);
 }
        /// <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;

        }
 /// <summary>
 /// Captures payment (from admin panel)
 /// </summary>
 /// <param name="order">Order</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void Capture(Order order, ref ProcessPaymentResult processPaymentResult)
 {
     string googleOrderNumber = processPaymentResult.AuthorizationTransactionID;
     GCheckout.OrderProcessing.ChargeOrderRequest chargeOrderRequest = new GCheckout.OrderProcessing.ChargeOrderRequest(googleOrderNumber);
     GCheckoutResponse chargeOrderResponse = chargeOrderRequest.Send();
     if (chargeOrderResponse.IsGood)
     {
         processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
         processPaymentResult.CaptureTransactionResult = chargeOrderResponse.ResponseXml;
     }
     else
     {
         processPaymentResult.Error = chargeOrderResponse.ErrorMessage;
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Captures order (from admin panel)
        /// </summary>
        /// <param name="orderId">Order identifier</param>
        /// <param name="error">Error</param>
        /// <returns>Captured order</returns>
        public Order Capture(int orderId, ref string error)
        {
            var order = GetOrderById(orderId);
            if (order == null)
                return order;

            if (!CanCapture(order))
                throw new NopException("Can not do capture for order.");

            var processPaymentResult = new ProcessPaymentResult();
            try
            {
                //old info from placing order
                processPaymentResult.AuthorizationTransactionId = order.AuthorizationTransactionId;
                processPaymentResult.AuthorizationTransactionCode = order.AuthorizationTransactionCode;
                processPaymentResult.AuthorizationTransactionResult = order.AuthorizationTransactionResult;
                processPaymentResult.CaptureTransactionId = order.CaptureTransactionId;
                processPaymentResult.CaptureTransactionResult = order.CaptureTransactionResult;
                processPaymentResult.SubscriptionTransactionId = order.SubscriptionTransactionId;
                processPaymentResult.PaymentStatus = order.PaymentStatus;

                IoC.Resolve<IPaymentService>().Capture(order, ref processPaymentResult);

                if (String.IsNullOrEmpty(processPaymentResult.Error))
                {
                    var paidDate = order.PaidDate;
                    var paymentStatus = processPaymentResult.PaymentStatus;
                    if (paymentStatus == PaymentStatusEnum.Paid)
                        paidDate = DateTime.UtcNow;

                    order.AuthorizationTransactionId = processPaymentResult.AuthorizationTransactionId;
                    order.AuthorizationTransactionCode = processPaymentResult.AuthorizationTransactionCode;
                    order.AuthorizationTransactionResult = processPaymentResult.AuthorizationTransactionResult;
                    order.CaptureTransactionId = processPaymentResult.CaptureTransactionId;
                    order.CaptureTransactionResult = processPaymentResult.CaptureTransactionResult;
                    order.SubscriptionTransactionId = processPaymentResult.SubscriptionTransactionId;
                    order.PaymentStatusId = (int)paymentStatus;
                    order.PaidDate = paidDate;

                    UpdateOrder(order);

                    InsertOrderNote(order.OrderId, string.Format("Order has been captured"), false, DateTime.UtcNow);
                }
                else
                {
                    InsertOrderNote(order.OrderId, string.Format("Unable to capture order. Error: {0}", processPaymentResult.Error), false, DateTime.UtcNow);

                }
                order = CheckOrderStatus(order.OrderId);

                //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))
            {
                error = processPaymentResult.Error;
                IoC.Resolve<ILogService>().InsertLog(LogTypeEnum.OrderError, string.Format("Error capturing order. {0}", processPaymentResult.Error), processPaymentResult.FullError);
            }
            return order;
        }
        /// <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();
            }
        }
Ejemplo n.º 21
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;
		}
Ejemplo n.º 22
0
        /// <summary>
        /// Captures order (from admin panel)
        /// </summary>
        /// <param name="orderId">Order identifier</param>
        /// <param name="error">Error</param>
        /// <returns>Captured order</returns>
        public static Order Capture(int orderId, ref string error)
        {
            var order = GetOrderById(orderId);
            if (order == null)
                return order;

            if (!CanCapture(order))
                throw new NopException("Can not do capture for order.");

            var processPaymentResult = new ProcessPaymentResult();
            try
            {
                //old info from placing order
                processPaymentResult.AuthorizationTransactionId = order.AuthorizationTransactionId;
                processPaymentResult.AuthorizationTransactionCode = order.AuthorizationTransactionCode;
                processPaymentResult.AuthorizationTransactionResult = order.AuthorizationTransactionResult;
                processPaymentResult.CaptureTransactionId = order.CaptureTransactionId;
                processPaymentResult.CaptureTransactionResult = order.CaptureTransactionResult;
                processPaymentResult.SubscriptionTransactionId = order.SubscriptionTransactionId;
                processPaymentResult.PaymentStatus = order.PaymentStatus;

                PaymentManager.Capture(order, ref processPaymentResult);

                if (String.IsNullOrEmpty(processPaymentResult.Error))
                {
                    var paidDate = order.PaidDate;
                    var paymentStatus = processPaymentResult.PaymentStatus;
                    if (paymentStatus == PaymentStatusEnum.Paid)
                        paidDate = DateTime.UtcNow;
                    order = UpdateOrder(order.OrderId, order.OrderGuid, order.CustomerId, order.CustomerLanguageId,
                        order.CustomerTaxDisplayType, order.CustomerIP, order.OrderSubtotalInclTax, order.OrderSubtotalExclTax, order.OrderShippingInclTax,
                        order.OrderShippingExclTax, order.PaymentMethodAdditionalFeeInclTax, order.PaymentMethodAdditionalFeeExclTax,
                        order.TaxRates, order.OrderTax, order.OrderTotal,
                        order.RefundedAmount, order.OrderDiscount,
                        order.OrderSubtotalInclTaxInCustomerCurrency, order.OrderSubtotalExclTaxInCustomerCurrency,
                        order.OrderShippingInclTaxInCustomerCurrency, order.OrderShippingExclTaxInCustomerCurrency,
                        order.PaymentMethodAdditionalFeeInclTaxInCustomerCurrency, order.PaymentMethodAdditionalFeeExclTaxInCustomerCurrency,
                        order.TaxRatesInCustomerCurrency, order.OrderTaxInCustomerCurrency,
                        order.OrderTotalInCustomerCurrency,
                        order.OrderDiscountInCustomerCurrency,
                        order.CheckoutAttributeDescription, order.CheckoutAttributesXml,
                        order.CustomerCurrencyCode, order.OrderWeight,
                        order.AffiliateId, order.OrderStatus, order.AllowStoringCreditCardNumber,
                        order.CardType, order.CardName, order.CardNumber, order.MaskedCreditCardNumber,
                        order.CardCvv2, order.CardExpirationMonth, order.CardExpirationYear,
                        order.PaymentMethodId, order.PaymentMethodName,
                        processPaymentResult.AuthorizationTransactionId,
                        processPaymentResult.AuthorizationTransactionCode,
                        processPaymentResult.AuthorizationTransactionResult,
                        processPaymentResult.CaptureTransactionId,
                        processPaymentResult.CaptureTransactionResult,
                        processPaymentResult.SubscriptionTransactionId,
                        order.PurchaseOrderNumber, paymentStatus, paidDate,
                        order.BillingFirstName, order.BillingLastName, order.BillingPhoneNumber,
                        order.BillingEmail, order.BillingFaxNumber, order.BillingCompany, order.BillingAddress1,
                        order.BillingAddress2, order.BillingCity,
                        order.BillingStateProvince, order.BillingStateProvinceId, order.BillingZipPostalCode,
                        order.BillingCountry, order.BillingCountryId, order.ShippingStatus,
                        order.ShippingFirstName, order.ShippingLastName, order.ShippingPhoneNumber,
                        order.ShippingEmail, order.ShippingFaxNumber, order.ShippingCompany,
                        order.ShippingAddress1, order.ShippingAddress2, order.ShippingCity,
                        order.ShippingStateProvince, order.ShippingStateProvinceId, order.ShippingZipPostalCode,
                        order.ShippingCountry, order.ShippingCountryId,
                        order.ShippingMethod, order.ShippingRateComputationMethodId,
                        order.ShippedDate, order.DeliveryDate,
                        order.TrackingNumber, order.VatNumber, order.Deleted, order.CreatedOn);

                    InsertOrderNote(order.OrderId, string.Format("Order has been captured"), false, DateTime.UtcNow);

                }
                else
                {
                    InsertOrderNote(order.OrderId, string.Format("Unable to capture order. Error: {0}", processPaymentResult.Error), false, DateTime.UtcNow);

                }
                order = CheckOrderStatus(order.OrderId);
            }
            catch (Exception exc)
            {
                processPaymentResult.Error = exc.Message;
                processPaymentResult.FullError = exc.ToString();
            }

            if (!String.IsNullOrEmpty(processPaymentResult.Error))
            {
                error = processPaymentResult.Error;
                LogManager.InsertLog(LogTypeEnum.OrderError, string.Format("Error capturing order. {0}", processPaymentResult.Error), processPaymentResult.FullError);
            }
            return order;
        }
        /// <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");
            }
        }
Ejemplo n.º 24
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 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;
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Captures payment
 /// </summary>
 /// <param name="order">Order</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void Capture(Order order, ref ProcessPaymentResult processPaymentResult)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Captures payment
 /// </summary>
 /// <param name="order">Order</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void Capture(Order order, ref ProcessPaymentResult processPaymentResult)
 {
     throw new NopException("Capture method not supported");
 }
Ejemplo n.º 28
0
 /// <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();
 }
Ejemplo n.º 29
0
        /// <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
                    {
                    }
                }
            }
        }
        /// <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();

            StringBuilder builder = new StringBuilder();
            builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            builder.Append("<Order>");
            builder.Append("<StoreID>" +XmlHelper.XmlEncode(storeID) + "</StoreID>");
            builder.Append("<Passphrase>" + XmlHelper.XmlEncode(passphrase) + "</Passphrase>");
            builder.Append("<Bname>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.FirstName) + "</Bname>");
            builder.Append("<Bcompany>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.Company) + "</Bcompany>");
            builder.Append("<Baddress1>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.Address1) + "</Baddress1>");
            builder.Append("<Baddress2>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.Address2) + "</Baddress2>");
            builder.Append("<Bcity>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.City) + "</Bcity>");
            if (paymentInfo.BillingAddress.StateProvince != null)
                builder.Append("<Bprovince>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.StateProvince.Abbreviation) + "</Bprovince>");
            builder.Append("<Bpostalcode>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.ZipPostalCode) + "</Bpostalcode>");
            if (paymentInfo.BillingAddress.Country != null)
                builder.Append("<Bcountry>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.Country.TwoLetterIsoCode) + "</Bcountry>");
            builder.Append("<Phone>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.PhoneNumber) + "</Phone>");
            builder.Append("<Fax>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.FaxNumber) + "</Fax>");
            builder.Append("<Email>" + XmlHelper.XmlEncode(paymentInfo.BillingAddress.Email) + "</Email>");
            builder.Append("<Comments> </Comments>");
            builder.Append("<CustomerIP>" + XmlHelper.XmlEncode(HttpContext.Current.Request.UserHostAddress) + "</CustomerIP>");
            builder.Append("<Subtotal>" + XmlHelper.XmlEncode(paymentInfo.OrderTotal.ToString("N2", new CultureInfo("en-US", false).NumberFormat)) + "</Subtotal>");
            builder.Append("<PaymentType>CC</PaymentType>");
            builder.Append("<CardAction>0</CardAction>");
            builder.Append("<CardNumber>" + XmlHelper.XmlEncode(paymentInfo.CreditCardNumber) + "</CardNumber>");
            string cardExpMonth = string.Empty;
            if (paymentInfo.CreditCardExpireMonth < 10)
            {
                cardExpMonth = "0" + paymentInfo.CreditCardExpireMonth.ToString();
            }
            else
            {
                cardExpMonth = paymentInfo.CreditCardExpireMonth.ToString();
            }
            builder.Append("<CardExpMonth>" + XmlHelper.XmlEncode(cardExpMonth) + "</CardExpMonth>");
            builder.Append("<CardExpYear>" + XmlHelper.XmlEncode(paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2)) + "</CardExpYear>");
            builder.Append("<CardIDNumber>" + XmlHelper.XmlEncode(paymentInfo.CreditCardCvv2) + "</CardIDNumber>");
            builder.Append("</Order>");
            string orderInfo = builder.ToString();

            byte[] bytes = Encoding.ASCII.GetBytes(orderInfo);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetPSIGateUrl());
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "application/xml; charset=UTF-8";
            request.KeepAlive = false;

            using (Stream str0 = request.GetRequestStream())
                str0.Write(bytes, 0, bytes.Length);

            string xmlResponse = string.Empty;
            try
            {
                using (HttpWebResponse resp1 = (HttpWebResponse)request.GetResponse())
                using (Stream str1 = resp1.GetResponseStream())
                using (StreamReader reader = new StreamReader(str1))
                    xmlResponse = reader.ReadToEnd();
            }
            catch (WebException exc)
            {
                if (exc.Response != null)
                    using (HttpWebResponse resp2 = (HttpWebResponse)exc.Response)
                    using (StreamReader rdr2 = new StreamReader(resp2.GetResponseStream()))
                        xmlResponse = rdr2.ReadToEnd();
            }
            StringReader input = new StringReader(xmlResponse);
            XmlTextReader rdr3 = new XmlTextReader(input);

            Label_1:
            while (rdr3.Read())
            {
                if (!(rdr3.IsStartElement() & (rdr3.Name == "Result")))
                {
                    continue;
                }
                while (rdr3.Read())
                {
                    if ((rdr3.NodeType == XmlNodeType.Element) && (rdr3.Name == "OrderID"))
                    {
                        processPaymentResult.AuthorizationTransactionId = rdr3.ReadElementString("OrderID");
                    }
                    else
                    {
                        if ((rdr3.NodeType == XmlNodeType.Element) && (rdr3.Name == "Approved"))
                        {
                            string approvedString = rdr3.ReadElementString("Approved");
                            if (approvedString == "APPROVED")
                                processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;

                            continue;
                        }
                        if ((rdr3.NodeType == XmlNodeType.Element) && (rdr3.Name == "ReturnCode"))
                        {
                            processPaymentResult.AuthorizationTransactionCode = rdr3.ReadElementString("ReturnCode");
                            continue;
                        }
                        if ((rdr3.NodeType == XmlNodeType.Element) && (rdr3.Name == "ErrMsg"))
                        {
                            processPaymentResult.Error = rdr3.ReadElementString("ErrMsg");
                            continue;
                        }
                        if ((rdr3.Name == "Result") & (rdr3.NodeType == XmlNodeType.EndElement))
                        {
                            goto Label_1;
                        }
                    }
                }
            }

            if (processPaymentResult.PaymentStatus != PaymentStatusEnum.Paid && string.IsNullOrEmpty(processPaymentResult.Error))
                processPaymentResult.Error = "Unknown PSI Gate error";
        }