/// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AllowStoringCreditCardNumber = true;
            switch (_manualPaymentSettings.TransactMode)
            {
                case TransactMode.Pending:
                    result.NewPaymentStatus = PaymentStatus.Pending;
                    break;
                case TransactMode.Authorize:
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                    break;
                case TransactMode.AuthorizeAndCapture:
                    result.NewPaymentStatus = PaymentStatus.Paid;
                    break;
                default:
                    {
                        result.AddError("Not supported transaction type");
                        return result;
                    }
            }

            return result;
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var orderGuid = processPaymentRequest.OrderGuid;


            if (orderGuid == Guid.NewGuid())
            {
                result.AddError("SagePay Server transaction code does not exist!");
                return result;
            }

            var transx = _sagePayServerTransactionService.GetSagePayServerTransactionByVendorTxCode(orderGuid.ToString());

            if (transx == null)
            {
                result.AddError(String.Format("SagePay Server transaction code {0} does not exist.", orderGuid.ToString()));
                return result;
            }

            if ((transx.Status == "OK") || (transx.Status == "AUTHENTICATED") || (transx.Status == "REGISTERED"))
            {
                if (_sagePayServerPaymentSettings.TransactType == SagePayServerPaymentSettings.TransactTypeValues.PAYMENT)
                    result.NewPaymentStatus = PaymentStatus.Paid;
                else if (_sagePayServerPaymentSettings.TransactType == SagePayServerPaymentSettings.TransactTypeValues.DEFERRED)
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                else
                    result.NewPaymentStatus = PaymentStatus.Pending;
                result.AuthorizationTransactionId = transx.Id.ToString();
                result.AuthorizationTransactionCode = transx.VPSTxId;
                result.AuthorizationTransactionResult = transx.ToString();
            }
            else
            {
                result.AddError(transx.StatusDetail);
            }


            return result;

        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            var req = new CreateRecurringPaymentsProfileReq();
            req.CreateRecurringPaymentsProfileRequest = new CreateRecurringPaymentsProfileRequestType();
            req.CreateRecurringPaymentsProfileRequest.Version = GetApiVersion();
            var details = new CreateRecurringPaymentsProfileRequestDetailsType();
            req.CreateRecurringPaymentsProfileRequest.CreateRecurringPaymentsProfileRequestDetails = details;

            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();

            var country = EngineContext.Current.Resolve<ICountryService>().GetCountryById(customer.BillingAddress.CountryId);
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(country);

            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvinceId != 0)
            {
                var state = EngineContext.Current.Resolve<IStateProvinceService>().GetStateProvinceById(customer.BillingAddress.StateProvinceId);
                details.CreditCard.CardOwner.Address.StateOrProvince = state.Abbreviation;
            }
            else
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName;

            //start date
            details.RecurringPaymentsProfileDetails = new RecurringPaymentsProfileDetailsType();
            details.RecurringPaymentsProfileDetails.BillingStartDate = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture);
            details.RecurringPaymentsProfileDetails.ProfileReference = processPaymentRequest.OrderGuid.ToString();

            //schedule
            details.ScheduleDetails = new ScheduleDetailsType();
            details.ScheduleDetails.Description = "Recurring payment";
            details.ScheduleDetails.PaymentPeriod = new BillingPeriodDetailsType();
            details.ScheduleDetails.PaymentPeriod.Amount = new BasicAmountType();
            details.ScheduleDetails.PaymentPeriod.Amount.value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.ScheduleDetails.PaymentPeriod.Amount.currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
            details.ScheduleDetails.PaymentPeriod.BillingFrequency = processPaymentRequest.RecurringCycleLength;
            switch (processPaymentRequest.RecurringCyclePeriod)
            {
                case RecurringProductCyclePeriod.Days:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.DAY;
                    break;
                case RecurringProductCyclePeriod.Weeks:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.WEEK;
                    break;
                case RecurringProductCyclePeriod.Months:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.MONTH;
                    break;
                case RecurringProductCyclePeriod.Years:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.YEAR;
                    break;
                default:
                    throw new NopException("Not supported cycle period");
            }
            details.ScheduleDetails.PaymentPeriod.TotalBillingCycles = processPaymentRequest.RecurringTotalCycles;

            var service = GetService();
            CreateRecurringPaymentsProfileResponseType response = service.CreateRecurringPaymentsProfile(req);

            string error;
            bool success = PaypalHelper.CheckSuccess(response, out error);
            if (success)
            {
                result.NewPaymentStatus = PaymentStatus.Pending;
                if (response.CreateRecurringPaymentsProfileResponseDetails != null)
                {
                    result.SubscriptionTransactionId = response.CreateRecurringPaymentsProfileResponseDetails.ProfileID;
                }
            }
            else
            {
                result.AddError(error);
            }
            return result;
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            var req = new CreateRecurringPaymentsProfileReq();
            req.CreateRecurringPaymentsProfileRequest = new CreateRecurringPaymentsProfileRequestType();
            req.CreateRecurringPaymentsProfileRequest.Version = GetApiVersion();
            var details = new CreateRecurringPaymentsProfileRequestDetailsType();
            req.CreateRecurringPaymentsProfileRequest.CreateRecurringPaymentsProfileRequestDetails = details;

            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified = true;
            details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;

            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            else
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName;

            //start date
            details.RecurringPaymentsProfileDetails = new RecurringPaymentsProfileDetailsType();
            details.RecurringPaymentsProfileDetails.BillingStartDate = DateTime.UtcNow;
            details.RecurringPaymentsProfileDetails.ProfileReference = processPaymentRequest.OrderGuid.ToString();

            //schedule
            details.ScheduleDetails = new ScheduleDetailsType();
            details.ScheduleDetails.Description = "Recurring payment";
            details.ScheduleDetails.PaymentPeriod = new BillingPeriodDetailsType();
            details.ScheduleDetails.PaymentPeriod.Amount = new BasicAmountType();
            details.ScheduleDetails.PaymentPeriod.Amount.Value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.ScheduleDetails.PaymentPeriod.Amount.currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
            details.ScheduleDetails.PaymentPeriod.BillingFrequency = processPaymentRequest.RecurringCycleLength;
            switch (processPaymentRequest.RecurringCyclePeriod)
            {
                case RecurringProductCyclePeriod.Days:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Day;
                    break;
                case RecurringProductCyclePeriod.Weeks:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Week;
                    break;
                case RecurringProductCyclePeriod.Months:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Month;
                    break;
                case RecurringProductCyclePeriod.Years:
                    details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Year;
                    break;
                default:
                    throw new NopException("Not supported cycle period");
            }
            details.ScheduleDetails.PaymentPeriod.TotalBillingCycles = processPaymentRequest.RecurringTotalCycles;
            details.ScheduleDetails.PaymentPeriod.TotalBillingCyclesSpecified = true;



            using (var service2 = new PayPalAPIAASoapBinding())
            {
                if (!_paypalDirectPaymentSettings.UseSandbox)
                    service2.Url = "https://api-3t.paypal.com/2.0/";
                else
                    service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";

                service2.RequesterCredentials = new CustomSecurityHeaderType();
                service2.RequesterCredentials.Credentials = new UserIdPasswordType();
                service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
                service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
                service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
                service2.RequesterCredentials.Credentials.Subject = "";

                CreateRecurringPaymentsProfileResponseType response = service2.CreateRecurringPaymentsProfile(req);

                string error = "";
                bool success = PaypalHelper.CheckSuccess(response, out error);
                if (success)
                {
                    result.NewPaymentStatus = PaymentStatus.Pending;
                    if (response.CreateRecurringPaymentsProfileResponseDetails != null)
                    {
                        result.SubscriptionTransactionId = response.CreateRecurringPaymentsProfileResponseDetails.ProfileID;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }

            return result;
        }
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            if (customer == null)
                throw new Exception("Customer cannot be loaded");

            var req = new DoDirectPaymentReq();
            req.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress() ?? "";
            if (authorizeOnly)
                details.PaymentAction = PaymentActionCodeType.Authorization;
            else
                details.PaymentAction = PaymentActionCodeType.Sale;
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified = true;
            details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;
            //billing address
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            else
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
            details.PaymentDetails = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource = "nopCommerceCart";
            //pass product names and totals to PayPal
            //if (_paypalDirectPaymentSettings.PassProductNamesAndTotals)
            //{
            //    //individual items
                //var cart = customer.ShoppingCartItems
                //    .Where(x=>x.ShoppingCartType == ShoppingCartType.ShoppingCart)
                //    .LimitPerStore(processPaymentRequest.StoreId)
                //    .ToList();
            //    var cartItems = new PaymentDetailsItemType[cart.Count];
            //    for (int i = 0; i < cart.Count; i++)
            //    {
            //        var sc = cart[i];
            //        decimal taxRate = decimal.Zero;
            //        var customer = processPaymentRequest.Customer;
            //        decimal scUnitPrice = _priceCalculationService.GetUnitPrice(sc, true);
            //        decimal scSubTotal = _priceCalculationService.GetSubTotal(sc, true);
            //        decimal scUnitPriceInclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, true, customer, out taxRate);
            //        decimal scUnitPriceExclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, false, customer, out taxRate);
            //        //decimal scSubTotalInclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, true, customer, out taxRate);
            //        //decimal scSubTotalExclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, false, customer, out taxRate);
            //        cartItems[i] = new PaymentDetailsItemType()
            //        {
            //            Name = sc.ProductVariant.FullProductName,
            //            Number = sc.ProductVariant.Id.ToString(),
            //            Quantity = sc.Quantity.ToString(),
            //            Amount = new BasicAmountType()
            //            {
            //                currencyID = payPalCurrency,
            //                Value = scUnitPriceExclTax.ToString("N", new CultureInfo("en-us")),
            //            },
            //            Tax = new BasicAmountType()
            //            {
            //                currencyID = payPalCurrency,
            //                Value = (scUnitPriceInclTax - scUnitPriceExclTax).ToString("N", new CultureInfo("en-us")),
            //            },
            //        };
            //    };
            //    details.PaymentDetails.PaymentDetailsItem = cartItems;
            //    //other totals (undone)
            //    details.PaymentDetails.ItemTotal = null;
            //    details.PaymentDetails.ShippingTotal = null;
            //    details.PaymentDetails.TaxTotal = null;
            //    details.PaymentDetails.HandlingTotal = null;
            //}
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
                {
                    var shippingAddress = new AddressType();
                    shippingAddress.Name = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1 = customer.ShippingAddress.Address1;
                    shippingAddress.CityName = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince = customer.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
                    shippingAddress.CountrySpecified = true;
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            using (var service2 = new PayPalAPIAASoapBinding())
            {
                if (!_paypalDirectPaymentSettings.UseSandbox)
                    service2.Url = "https://api-3t.paypal.com/2.0/";
                else
                    service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";

                service2.RequesterCredentials = new CustomSecurityHeaderType();
                service2.RequesterCredentials.Credentials = new UserIdPasswordType();
                service2.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName;
                service2.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword;
                service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
                service2.RequesterCredentials.Credentials.Subject = "";

                DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

                string error = "";
                bool success = PaypalHelper.CheckSuccess(response, out error);
                if (success)
                {
                    result.AvsResult = response.AVSCode;
                    result.AuthorizationTransactionCode = response.CVV2Code;
                    if (authorizeOnly)
                    {
                        result.AuthorizationTransactionId = response.TransactionID;
                        result.AuthorizationTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Authorized;
                    }
                    else
                    {
                        result.CaptureTransactionId = response.TransactionID;
                        result.CaptureTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Paid;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }
            return result;
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            if (!processPaymentRequest.IsRecurringPayment)
            {
                var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

                var subscription = new ARBSubscriptionType();
                var creditCard = new net.authorize.api.CreditCardType();

                subscription.name = processPaymentRequest.OrderGuid.ToString();

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

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

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

                if (customer.ShippingAddress != null)
                {
                    subscription.shipTo = new NameAndAddressType();
                    subscription.shipTo.firstName = customer.ShippingAddress.FirstName;
                    subscription.shipTo.lastName = customer.ShippingAddress.LastName;
                    subscription.shipTo.address = customer.ShippingAddress.Address1;
                    //subscription.shipTo.address = customer.ShippingAddress.Address1 + " " + customer.ShippingAddress.Address2;
                    subscription.shipTo.city = customer.ShippingAddress.City;
                    if (customer.ShippingAddress.StateProvince != null)
                    {
                        subscription.shipTo.state = customer.ShippingAddress.StateProvince.Abbreviation;
                    }
                    subscription.shipTo.zip = customer.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 = "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(processPaymentRequest.RecurringTotalCycles);
                subscription.paymentSchedule.totalOccurrencesSpecified = true;

                var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);
                subscription.amount = orderTotal;
                subscription.amountSpecified = true;

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

                using (var webService = new net.authorize.api.Service())
                {
                    if (_authorizeNetPaymentSettings.UseSandbox)
                        webService.Url = "https://apitest.authorize.net/soap/v1/Service.asmx";
                    else
                        webService.Url = "https://api.authorize.net/soap/v1/Service.asmx";

                    var authentication = PopulateMerchantAuthentication();
                    var response = webService.ARBCreateSubscription(authentication, subscription);

                    if (response.resultCode == MessageTypeEnum.Ok)
                    {
                        result.SubscriptionTransactionId = response.subscriptionId.ToString();
                        result.AuthorizationTransactionCode = response.resultCode.ToString();
                        result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.resultCode.ToString(), response.subscriptionId.ToString());

                        if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize)
                        {
                            result.NewPaymentStatus = PaymentStatus.Authorized;
                        }
                        else
                        {
                            result.NewPaymentStatus = PaymentStatus.Paid;
                        }
                    }
                    else
                    {
                        result.AddError(string.Format("Error processing recurring payment. {0}", GetErrors(response)));
                    }
                }
            }

            return result;
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            var webClient = new WebClient();
            var form = new NameValueCollection();
            form.Add("x_login", _authorizeNetPaymentSettings.LoginId);
            form.Add("x_tran_key", _authorizeNetPaymentSettings.TransactionKey);

            //we should not send "x_test_request" parameter. otherwise, the transaction won't be logged in the sandbox
            //if (_authorizeNetPaymentSettings.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", GetApiVersion());
            form.Add("x_relay_response", "FALSE");
            form.Add("x_method", "CC");
            form.Add("x_currency_code", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);
            if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize)
                form.Add("x_type", "AUTH_ONLY");
            else if (_authorizeNetPaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture)
                form.Add("x_type", "AUTH_CAPTURE");
            else
                throw new NopException("Not supported transaction mode");

            var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);
            form.Add("x_amount", orderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            form.Add("x_card_num", processPaymentRequest.CreditCardNumber);
            form.Add("x_exp_date", processPaymentRequest.CreditCardExpireMonth.ToString("D2") + processPaymentRequest.CreditCardExpireYear.ToString());
            form.Add("x_card_code", processPaymentRequest.CreditCardCvv2);
            form.Add("x_first_name", customer.BillingAddress.FirstName);
            form.Add("x_last_name", customer.BillingAddress.LastName);
            form.Add("x_email", customer.BillingAddress.Email);
            if (!string.IsNullOrEmpty(customer.BillingAddress.Company))
                form.Add("x_company", customer.BillingAddress.Company);
            form.Add("x_address", customer.BillingAddress.Address1);
            form.Add("x_city", customer.BillingAddress.City);
            if (customer.BillingAddress.StateProvince != null)
                form.Add("x_state", customer.BillingAddress.StateProvince.Abbreviation);
            form.Add("x_zip", customer.BillingAddress.ZipPostalCode);
            if (customer.BillingAddress.Country != null)
                form.Add("x_country", customer.BillingAddress.Country.TwoLetterIsoCode);
            //x_invoice_num is 20 chars maximum. hece we also pass x_description
            form.Add("x_invoice_num", processPaymentRequest.OrderGuid.ToString().Substring(0, 20));
            form.Add("x_description", string.Format("Full order #{0}", processPaymentRequest.OrderGuid));
            form.Add("x_customer_ip", _webHelper.GetCurrentIpAddress());

            var responseData = webClient.UploadValues(GetAuthorizeNetUrl(), form);
            var reply = Encoding.ASCII.GetString(responseData);

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

                }
            }
            else
            {
                result.AddError("Authorize.NET unknown error");
            }

            return result;
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();
            
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            //var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);

            StripeCreditCardInfo cc = new StripeCreditCardInfo();
            cc.CVC = processPaymentRequest.CreditCardCvv2;
            cc.FullName = customer.BillingAddress.FirstName + " " + customer.BillingAddress.LastName;
            
            cc.Number = processPaymentRequest.CreditCardNumber;
            cc.ExpirationMonth = processPaymentRequest.CreditCardExpireMonth;
            cc.ExpirationYear = processPaymentRequest.CreditCardExpireYear;
            cc.AddressLine1 = customer.BillingAddress.Address1;
            cc.AddressLine2 = customer.BillingAddress.Address2;
            if (customer.BillingAddress.Country.TwoLetterIsoCode.ToLower() == "us")
            {
                cc.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                cc.StateOrProvince = "ot";
            }

            cc.ZipCode = customer.BillingAddress.ZipPostalCode;
            
            cc.Country = customer.BillingAddress.Country.TwoLetterIsoCode;
            
            StripePayment payment = new StripePayment(_stripePaymentSettings.TransactionKey);
            
            try
            {
                StripeCharge charge = payment.Charge((int)(processPaymentRequest.OrderTotal * 100),
                    _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode.ToLower(), 
                    cc, string.Format("charge for {0} - {1}",
                    cc.FullName, processPaymentRequest.PurchaseOrderNumber));
            
                if (charge != null)
                {
                    result.NewPaymentStatus = PaymentStatus.Paid;
                    _stripePaymentSettings.TransactMode = TransactMode.AuthorizeAndCapture;
                    result.AuthorizationTransactionId = charge.ID;
                    result.AuthorizationTransactionResult = StripeChargeStatus.SUCCESS;
                    //need this for refund
                    result.AuthorizationTransactionCode = _stripePaymentSettings.TransactionKey;
                }
            }
            catch (StripeException stripeException)
            {
                result.AuthorizationTransactionResult = stripeException.StripeError.Message;
                result.AuthorizationTransactionCode = stripeException.StripeError.Code;
                result.AuthorizationTransactionId = "-1";
                result.AddError(string.Format("Declined ({0}: {1} - {2})", result.AuthorizationTransactionCode,
                    result.AuthorizationTransactionResult, _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode));
            }

            return result;
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();
            try
            {
                result.AllowStoringCreditCardNumber = false;
                var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
                var order = _orderService.GetOrderByGuid(processPaymentRequest.OrderGuid);
                string currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
                PaymentModel pm = new PaymentModel();
                pm = getPayment("?token=" + processPaymentRequest.CustomValues["paymenttoken"]);
                string paymentid = pm.id;
                string amount = processPaymentRequest.OrderTotal.ToString();
                amount = Regex.Replace(amount, @"[^\d]", "");

                //string urlappend = "?payment=" + payment + "&amount=" + amount + "&currency=" + currency + "&description=" + description;
                string urlbuilder = "?payment=" + paymentid + "&amount=" + amount + "&currency=" + currency + "&description=Order from Store ID: " + processPaymentRequest.StoreId.ToString() + " PaymentID: " + pm.id;
                TransactionModel trans = new TransactionModel();
                //_logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "url for transaction", urlbuilder);
                trans = getTransaction(urlbuilder, pm);
                string responsecode = trans.response_code;
                string transactionid = trans.id;
                //set the transaction variables
                if (responsecode == "20000")
                {
                    //successful response
                    result.AuthorizationTransactionCode = transactionid;
                    result.AuthorizationTransactionResult = responsecode;
                    result.NewPaymentStatus = PaymentStatus.Paid;
                    //_logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "success at paymill proceessorder" + responsecode + urlbuilder + paymentid, trans.status + urlbuilder + paymentid, null);
                }
                else
                {
                    //failed transaction
                    _logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "failure at paymill proceessorder" + responsecode, trans.status, null);
                    result.AddError(getErrorcodes(responsecode, trans.status));
                }
            }
            catch (Exception ex)
            {
                _logger.InsertLog(Core.Domain.Logging.LogLevel.Error, ex.Message, ex.ToString());
                result.AddError(ex.ToString());
            }
            return result;
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();
            var token = (string)processPaymentRequest.CustomValues["token_value"];

            var config = new HpsServicesConfig();
            config.SecretApiKey = _secureSubmitPaymentSettings.SecretApiKey;
            config.DeveloperId = "002914";
            config.VersionNumber = "1513";

            var creditService = new HpsCreditService(config);
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            var cardHolder = new HpsCardHolder();
            cardHolder.Address = new HpsAddress();
            cardHolder.Address.Address = customer.BillingAddress.Address1;
            cardHolder.Address.City = customer.BillingAddress.City;
            cardHolder.Address.State = customer.BillingAddress.StateProvince.Abbreviation;
            cardHolder.Address.Zip = customer.BillingAddress.ZipPostalCode.Replace("-", "");
            cardHolder.Address.Country = customer.BillingAddress.Country.ThreeLetterIsoCode;

            HpsAuthorization response = null;

            try
            {
                if (_secureSubmitPaymentSettings.TransactMode == TransactMode.Authorize)
                {
                    // auth
                    response = creditService.Authorize(
                        processPaymentRequest.OrderTotal,
                        _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode,
                        token,
                        cardHolder,
                        false);

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                    result.AuthorizationTransactionCode = response.AuthorizationCode;
                    result.AuthorizationTransactionId = response.TransactionId.ToString();
                }
                else
                {
                    //capture
                    response = creditService.Charge(
                        processPaymentRequest.OrderTotal,
                        _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode,
                        token,
                        cardHolder,
                        false);

                    result.NewPaymentStatus = PaymentStatus.Paid;
                    result.CaptureTransactionId = response.TransactionId.ToString();
                    result.CaptureTransactionResult = response.ResponseText;
                }
            }
            catch (HpsException ex)
            {
                result.AddError(ex.Message);
            }

            return result;
        }
示例#11
0
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            TransactionResponse TransactionResponse = null;
            var authorizeNetPaymentSettings = _settingService.LoadSetting<BridgePaySettings>();
            var twoDigitMonth = processPaymentRequest.CreditCardExpireMonth.ToString("00");
            var twoDigitYear = processPaymentRequest.CreditCardExpireYear.ToString().Substring(2, 2);

            string serviceUrl = string.Format(authorizeNetPaymentSettings.GatewayUrl + "?" +
                "UserName="******"&" +
                "Password="******"&" +
                "TransType=Sale&"+
                "CardNum=" + processPaymentRequest.CreditCardNumber + "&"+
                "ExpDate=" + twoDigitMonth + twoDigitYear + "&"+
                "MagData=data&" +
                "NameOnCard=" + processPaymentRequest.CreditCardName + "&" +
                "Amount=" + processPaymentRequest.OrderTotal + "&" +
                "InvNum=1&" +
                "PNRef=1&" +
                "Zip=43600&" +
                "Street=Kamra&" +
                "CVNum=" + processPaymentRequest.CreditCardCvv2 + "&" +
                "ExtData=ext-data");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl);
            try
            {
                var httpResponse = (HttpWebResponse)request.GetResponse();
                //Receipt Receipt = null;
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var responstText = streamReader.ReadToEnd();
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(responstText);
                    if (doc.ChildNodes[1].Name == "Response")
                    {
                        var responseNode = doc.ChildNodes[1];
                        var responseNodes = responseNode.Cast<XmlNode>().ToArray();
                        var res = responseNodes.SingleOrDefault(n => n.Name == "Result");
                        string jsonText = JsonConvert.SerializeXmlNode(node: responseNode, formatting: Newtonsoft.Json.Formatting.None, omitRootObject: true);

                        // parse json to anonymous object
                        var Response = new
                        {
                            Result = 0,
                            RespMSG = string.Empty,
                            ExtData = string.Empty
                        };
                        Response = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(jsonText, Response);

                        // parse json to class object
                        TransactionResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<TransactionResponse>(jsonText);
                        
                    }
                }
            }
            catch (Exception)
            { }

            var result = new ProcessPaymentResult();
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            if (TransactionResponse != null)
            {
                switch (TransactionResponse.Result)
                {
                    case 0:
                        result.AuthorizationTransactionCode = string.Format("{0}", TransactionResponse.AuthCode);
                        result.AuthorizationTransactionResult = string.Format("Approved {0})", TransactionResponse.Message1);
                        result.AvsResult = TransactionResponse.GetAVSResult;
                        //responseFields[38];
                        //if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize)
                        //{
                        //    result.NewPaymentStatus = PaymentStatus.Authorized;
                        //}
                        //else
                        //{
                        //    result.NewPaymentStatus = PaymentStatus.Paid;
                        //}
                        break;
                    case 24:
                        result.AddError(string.Format("Error: {0}", TransactionResponse.Message));
                        break;
                    case 110:
                        result.AddError(string.Format("Error: {0}", TransactionResponse.RespMSG));
                        break;

                }
            }
            else
            {
                result.AddError("BridgePay unknown error");
            }

            /////////////////////////////////////////////////////////////////////////////////////////////////
            
            //var webClient = new WebClient();
            //var form = new NameValueCollection();
            //form.Add("x_login", _authorizeNetPaymentSettings.LoginId);
            //form.Add("x_tran_key", _authorizeNetPaymentSettings.TransactionKey);
            
            ////we should not send "x_test_request" parameter. otherwise, the transaction won't be logged in the sandbox
            ////if (_authorizeNetPaymentSettings.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", GetApiVersion());
            //form.Add("x_relay_response", "FALSE");
            //form.Add("x_method", "CC");
            //form.Add("x_currency_code", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);
            //if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize)
            //    form.Add("x_type", "AUTH_ONLY");
            //else if (_authorizeNetPaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture)
            //    form.Add("x_type", "AUTH_CAPTURE");
            //else
            //    throw new NopException("Not supported transaction mode");

            //var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);
            //form.Add("x_amount", orderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            //form.Add("x_card_num", processPaymentRequest.CreditCardNumber);
            //form.Add("x_exp_date", processPaymentRequest.CreditCardExpireMonth.ToString("D2") + processPaymentRequest.CreditCardExpireYear.ToString());
            //form.Add("x_card_code", processPaymentRequest.CreditCardCvv2);
            //form.Add("x_first_name", customer.BillingAddress.FirstName);
            //form.Add("x_last_name", customer.BillingAddress.LastName);
            //form.Add("x_email", customer.BillingAddress.Email);
            //if (!string.IsNullOrEmpty(customer.BillingAddress.Company))
            //    form.Add("x_company", customer.BillingAddress.Company);
            //form.Add("x_address", customer.BillingAddress.Address1);
            //form.Add("x_city", customer.BillingAddress.City);
            //if (customer.BillingAddress.StateProvince != null)
            //    form.Add("x_state", customer.BillingAddress.StateProvince.Abbreviation);
            //form.Add("x_zip", customer.BillingAddress.ZipPostalCode);
            //if (customer.BillingAddress.Country != null)
            //    form.Add("x_country", customer.BillingAddress.Country.TwoLetterIsoCode);
            ////x_invoice_num is 20 chars maximum. hece we also pass x_description
            //form.Add("x_invoice_num", processPaymentRequest.OrderGuid.ToString().Substring(0, 20));
            //form.Add("x_description", string.Format("Full order #{0}", processPaymentRequest.OrderGuid));
            //form.Add("x_customer_ip", _webHelper.GetCurrentIpAddress());

            //var responseData = webClient.UploadValues(GetAuthorizeNetUrl(), form);
            //var reply = Encoding.ASCII.GetString(responseData);

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

            //    }
            //}
            //else
            //{
            //    result.AddError("Authorize.NET unknown error");
            //}

            return result;
        }
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            // Credit Card Info
            PayfirmaCreditCard cc = new PayfirmaCreditCard()
            {
                Number = processPaymentRequest.CreditCardNumber,
                ExpMonth = processPaymentRequest.CreditCardExpireMonth,
                ExpYear = processPaymentRequest.CreditCardExpireYear,
                CVV2 = processPaymentRequest.CreditCardCvv2
            };

            // Extra Meta Data
            PayfirmaMetaData payfirmaMeta = new PayfirmaMetaData();
            payfirmaMeta.Firstname = customer.BillingAddress.FirstName;
            payfirmaMeta.Lastname = customer.BillingAddress.LastName;
            if (!String.IsNullOrEmpty(customer.BillingAddress.Company)) { payfirmaMeta.Company = customer.BillingAddress.Company; }
            payfirmaMeta.Address1 = customer.BillingAddress.Address1;
            if (!String.IsNullOrEmpty(customer.BillingAddress.Address2)) { payfirmaMeta.Address2 = customer.BillingAddress.Address2; }
            payfirmaMeta.City = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
            {
                payfirmaMeta.Province = customer.BillingAddress.StateProvince.Name;
            }
            payfirmaMeta.PostalCode = customer.BillingAddress.ZipPostalCode;
            if (customer.BillingAddress.Country != null)
            {
                payfirmaMeta.Country = customer.BillingAddress.Country.Name;
            }
            payfirmaMeta.Email = customer.BillingAddress.Email;

            String currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
            payfirmaMeta.Currency = "CA$";
            if (currencyCode == "USD") { payfirmaMeta.Currency = "US$"; }
            payfirmaMeta.OrderId = processPaymentRequest.OrderGuid.ToString();
            if (!String.IsNullOrEmpty(customer.BillingAddress.PhoneNumber)) { payfirmaMeta.Telephone = customer.BillingAddress.PhoneNumber;  }
            payfirmaMeta.Description = "Payment via nopCommerce.";

            PayfirmaTransaction payfirma = new PayfirmaTransaction();
            PayfirmaTransactionResponse payfirmaResponse;
            if (_payfirmaPaymentSettings.TransactMode == TransactMode.Authorize)
            {
                payfirmaResponse = payfirma.ProcessAuthorize(this.PopulateMerchantCredentials(), cc, payfirmaMeta,
                    Convert.ToDouble(processPaymentRequest.OrderTotal), _payfirmaPaymentSettings.IsTest);
            }
            else
            {
                payfirmaResponse = payfirma.ProcessSale(this.PopulateMerchantCredentials(), cc, payfirmaMeta,
                   Convert.ToDouble(processPaymentRequest.OrderTotal), _payfirmaPaymentSettings.IsTest);
            }

            if (!String.IsNullOrEmpty(payfirmaResponse.Error))
            {
                result.AddError(payfirmaResponse.Error);
            }
            else if (!payfirmaResponse.Result)
            {
                result.AddError(payfirmaResponse.ResultMessage);
            } else {
                result.AvsResult = payfirmaResponse.AVS;
                result.AuthorizationTransactionCode = payfirmaResponse.AuthCode;
                result.AuthorizationTransactionId = payfirmaResponse.TransactionId;
                result.AuthorizationTransactionResult = payfirmaResponse.ResultMessage;

                if (_payfirmaPaymentSettings.TransactMode == TransactMode.Authorize)
                {
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
            }

            return result;
        }
示例#13
0
 public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
 {
     var result = new ProcessPaymentResult();
     result.AddError("Ежемесячная оплата не поддерживается.");
     return result;
 }
        /// <summary>
        /// Process a payment right after order is created
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var transx = _sagePayServerTransactionService.GetSagePayServerTransactionByVendorTxCode(processPaymentRequest.OrderGuid.ToString());

            if (transx == null)
            {
                result.AddError(String.Format("SagePay Server transaction code {0} does not exist.", processPaymentRequest.OrderGuid));
                return result;
            }

            if ((transx.Status == "OK") || (transx.Status == "AUTHENTICATED") || (transx.Status == "REGISTERED"))
            {
                switch (_sagePayServerPaymentSettings.TransactType)
                {
                    case TransactTypeValues.Payment:
                        var releaseResult = _sagePayServerWorkflowService.ReleaseTransaction(processPaymentRequest.OrderGuid.ToString(), processPaymentRequest.OrderTotal);

                        if (releaseResult.Success)
                        {
                            result.NewPaymentStatus = PaymentStatus.Paid;
                            result.CaptureTransactionResult = releaseResult.Message;
                        }
                        else
                        {
                            result.AddError(releaseResult.Message);
                        }

                        break;
                    case TransactTypeValues.Deferred:
                        result.NewPaymentStatus = PaymentStatus.Authorized;
                        break;
                    default:
                        result.NewPaymentStatus = PaymentStatus.Pending;
                        break;
                }

                result.AuthorizationTransactionId = transx.Id.ToString(CultureInfo.InvariantCulture);
                result.AuthorizationTransactionCode = transx.VpsTxId;
                result.AuthorizationTransactionResult = transx.ToString();
            }
            else
            {
                result.AddError(transx.StatusDetail);
            }

            return result;
        }
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            if (customer == null)
                throw new Exception("Customer cannot be loaded");

            var req = new DoDirectPaymentReq();
            req.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress() ?? "";
            if (authorizeOnly)
                details.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            else
                details.PaymentAction = PaymentActionCodeType.SALE;
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonth = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYear = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2 = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            var country = EngineContext.Current.Resolve<ICountryService>().GetCountryById(customer.BillingAddress.CountryId);
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(country);
            //billing address
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.Street1 = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2 = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvinceId != 0)
            {
                var state = EngineContext.Current.Resolve<IStateProvinceService>().GetStateProvinceById(customer.BillingAddress.StateProvinceId);
                details.CreditCard.CardOwner.Address.StateOrProvince = state.Abbreviation;
            }
            else
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            details.CreditCard.CardOwner.Address.Country = GetPaypalCountryCodeType(country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
            details.PaymentDetails = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource = "nopCommerceCart";
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvinceId != 0 && customer.ShippingAddress.CountryId != 0)
                {
                    var state = EngineContext.Current.Resolve<IStateProvinceService>().GetStateProvinceById(customer.ShippingAddress.StateProvinceId);
                    var countryshipping = EngineContext.Current.Resolve<ICountryService>().GetCountryById(customer.ShippingAddress.CountryId);

                    var shippingAddress = new AddressType();
                    shippingAddress.Name = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1 = customer.ShippingAddress.Address1;
                    shippingAddress.Street2 = customer.ShippingAddress.Address2;
                    shippingAddress.CityName = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince = state.Abbreviation;
                    shippingAddress.PostalCode = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), countryshipping.TwoLetterIsoCode, true);
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            var service = GetService();
            DoDirectPaymentResponseType response = service.DoDirectPayment(req);

            string error;
            bool success = PaypalHelper.CheckSuccess(response, out error);
            if (success)
            {
                result.AvsResult = response.AVSCode;
                result.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    result.AuthorizationTransactionId = response.TransactionID;
                    result.AuthorizationTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.CaptureTransactionId = response.TransactionID;
                    result.CaptureTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
            }
            else
            {
                result.AddError(error);
            }
            return result;
        }
 /// <summary>
 /// Process recurring payment
 /// </summary>
 /// <param name="processPaymentRequest">Payment info required for an order processing</param>
 /// <returns>Process payment result</returns>
 public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
 {
     var result = new ProcessPaymentResult();
     result.AddError("Recurring payment not supported");
     return result;
 }
示例#17
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            result.AllowStoringCreditCardNumber = true;
            switch (_manualPaymentSettings.TransactMode)
            {
                case TransactMode.Pending:
                    result.NewPaymentStatus = PaymentStatus.Pending;
                    break;
                case TransactMode.Authorize:
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                    break;
                case TransactMode.AuthorizeAndCapture:
                    result.NewPaymentStatus = PaymentStatus.Paid;
                    break;
                default:
                    {
                        result.AddError("Not supported transaction type");
                        return result;
                    }
            }

                    C_Posnet objYKB = new C_Posnet();

                    //Test parametreleri
                    objYKB.SetMid("6706598320");
                    objYKB.SetTid("67011009");
                    objYKB.SetURL("http://setmpos.ykb.com/PosnetWebService/XML");

                    //test card : 4506347011448053  2002/000

                    string orderBankUniqueID = ("123456" + DateTime.Now.ToString("yyyyMMddHHmmssfff")).PadLeft(24, '0');

                    bool return_value = objYKB.DoSaleTran( processPaymentRequest.CreditCardNumber,
                                             processPaymentRequest.CreditCardExpireYear.ToString() + processPaymentRequest.CreditCardExpireMonth.ToString(),
                                             processPaymentRequest.CreditCardCvv2, orderBankUniqueID, String.Format("{0:0.##}", processPaymentRequest.OrderTotal),
                                             "TL", "00", "00", "000000");
                    bool _IsConnectionOk, _IsOperationSuccessful = false;
                    string _ResponseErrorCode,_ResponseErrorMessage;
                    // Baðlantý Baþarýlý
                    if (return_value)
                    {
                        _IsConnectionOk = true;

                        string app_code = objYKB.GetApprovedCode();

                        if (app_code == "1" || app_code == "2")
                        {
                            _IsOperationSuccessful = true;
                        }
                        else if (app_code == "0")
                        {
                            _IsOperationSuccessful = false;
                        }

                        //test için heo  false dönsün
                        //_IsOperationSuccessful = false;

                        result.SubscriptionTransactionId  = objYKB.GetHostlogkey() + "|" + objYKB.GetAuthcode();
                        _ResponseErrorCode = objYKB.GetResponseCode();
                        if (_IsOperationSuccessful)
                        {
                            //_ResponseErrorMessage += "Banka Onay Kodu : " + _PaymentBankTransactionID;
                        }
                        else
                        {
                            _ResponseErrorMessage = objYKB.GetResponseText();
                        }
                    }

                    // Baðlantý Baþarýsýz
                    else
                    {
                        _IsOperationSuccessful = false;
                        _ResponseErrorCode = "-100";
                        _ResponseErrorMessage = "Banka Baðlantýsý Baþarýsýz. (BankResponseCode:" + return_value + ")";
                    }
                    objYKB = null;

                    //result.Success = _IsOperationSuccessful;

                return result;
        }