public ProcessPaymentResult Process(ProcessPaymentRequest request)
        {
            var method = _paymentMethodService.GetById(request.Payment.PaymentMethod.Id);
            var settings = AuthorizeNetConfig.Deserialize(method.PaymentProcessorData);

            var authRequest = CreateGatewayRequest(settings, request);
            var gateway = new Gateway(settings.LoginId, settings.TransactionKey, settings.SandboxMode);
            var response = gateway.Send(authRequest, request.Payment.Description);

            var result = new ProcessPaymentResult();

            if (response.Approved)
            {
                result.PaymentStatus = PaymentStatus.Success;
            }
            else
            {
                result.PaymentStatus = PaymentStatus.Failed;
                result.Message = response.ResponseCode + ": " + response.Message;
            }

            result.ThirdPartyTransactionId = response.TransactionID;

            return result;
        }
        public ProcessPaymentResult Process(ProcessPaymentRequest request)
        {
            if (String.IsNullOrEmpty(request.CurrencyCode))
            {
                var storeSettings = _settingsService.Get<StoreSettings>(StoreSettings.Key) ?? new StoreSettings();
                request.CurrencyCode = storeSettings.CurrencyISOCode;
            }

            var paymentMethod = _paymentMethodService.GetById(request.Payment.PaymentMethod.Id);
            var settings = PayPalConfig.Deserialize(paymentMethod.PaymentProcessorData);

            var result = CreatePayPalPayment(request, settings);
            var paymentStatus = PaymentStatus.Failed;

            if (result.state == "approved")
            {
                paymentStatus = PaymentStatus.Success;
            }
            else if (result.state == "canceled")
            {
                paymentStatus = PaymentStatus.Cancelled;
            }
            else // expired, failed
            {
                paymentStatus = PaymentStatus.Failed;
            }

            return new ProcessPaymentResult
            {
                PaymentStatus = paymentStatus,
                ThirdPartyTransactionId = result.id
            };
        }
        private GatewayRequest CreateGatewayRequest(AuthorizeNetConfig settings, ProcessPaymentRequest paymentRequest)
        {
            var request = new CardPresentAuthorizeAndCaptureRequest(
                    paymentRequest.Amount,
                    paymentRequest.Parameters[AuthorizeNetConstants.CreditCardNumber],
                    paymentRequest.Parameters[AuthorizeNetConstants.CreditCardExpireMonth],
                    paymentRequest.Parameters[AuthorizeNetConstants.CreditCardExpireYear]
            );

            request.AddCardCode(paymentRequest.Parameters[AuthorizeNetConstants.CreditCardCvv2]);

            return request;
        }
Beispiel #4
0
        public ProcessPaymentResponse ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            if (processPaymentRequest.OrderTotal == decimal.Zero)
            {
                var result = new ProcessPaymentResponse
                {
                    NewPaymentStatus = PaymentStatus.Paid
                };
                return result;
            }

            //We should strip out any white space or dash in the CC number entered.
            if (!string.IsNullOrWhiteSpace(processPaymentRequest.CreditCardNumber))
            {
                processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace(" ", "");
                processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace("-", "");
            }
            var paymentMethod = GetPaymentMethodByKey(processPaymentRequest.PaymentMethodName);
            return paymentMethod.ProcessPayment(processPaymentRequest);
        }
        public ProcessPaymentResult Process(ProcessPaymentRequest request)
        {
            var method = _paymentMethodService.GetById(request.Payment.PaymentMethod.Id);
            var settings = BuckarooConfig.Deserialize(method.PaymentProcessorData);

            var serviceId = request.Parameters[BuckarooConstants.Parameters.ServiceId];

            var parameters = new NameValueCollection();

            parameters.Add("Brq_websitekey", settings.WebsiteKey);
            parameters.Add("Brq_amount", request.Amount.ToString("f2", CultureInfo.InvariantCulture));
            parameters.Add("Brq_invoicenumber", request.Payment.Id.ToString());
            parameters.Add("Brq_currency", request.CurrencyCode);
            parameters.Add("Brq_description", "#" + request.Payment.Description);
            parameters.Add("brq_culture", "en-US");

            parameters.Add("Brq_return", GetCallbackUrl("Return", request));
            parameters.Add("Brq_push", GetCallbackUrl("Push", request));

            parameters.Add("Brq_payment_method", serviceId);
            parameters.Add("Brq_service_" + serviceId + "_action", "Pay");

            parameters.Add("add_paymentId", request.Payment.Id.ToString());

            if (serviceId == BuckarooConstants.Services.SimpleSEPADirectDebit)
            {
                parameters.Add("brq_service_" + serviceId + "_customeraccountname", request.Parameters[BuckarooConstants.Parameters.SEPA_CustomerAccountName]);
                parameters.Add("brq_service_" + serviceId + "_CustomerBIC", request.Parameters[BuckarooConstants.Parameters.SEPA_CustomerBIC]);
                parameters.Add("brq_service_" + serviceId + "_CustomerIBAN", request.Parameters[BuckarooConstants.Parameters.SEPA_CustomerIBAN]);
                parameters.Add("brq_service_" + serviceId + "_MandateReference", settings.CreditDebitMandateReference);
                parameters.Add("brq_service_" + serviceId + "_MandateDate", settings.CreditDebitMandateDate);
            }

            parameters.Add("Brq_signature", BuckarooUtil.GetSignature(parameters, settings.SecretKey));

            // TODO: Check documentation and see how to do this without redirect
            throw new NotImplementedException();
        }
        private CreditCard CreateCreditCard(ProcessPaymentRequest request)
        {
            var card = new CreditCard
            {
                number = request.Parameters[PayPalConstants.CreditCardNumber],
                type = request.Parameters[PayPalConstants.CreditCardType],
                expire_month = Convert.ToInt32(request.Parameters[PayPalConstants.CreditCardExpireMonth]),
                expire_year = Convert.ToInt32(request.Parameters[PayPalConstants.CreditCardExpireYear]),
                cvv2 = request.Parameters[PayPalConstants.CreditCardCvv2]
            };

            // If the website don't pass in customer info,
            // then we try to fill these info automatically
            if (request.Payment.PaymentTarget.Type == PaymentTargetTypes.Order)
            {
                var orderId = Convert.ToInt32(request.Payment.PaymentTarget.Id);
                var order = _orderService.GetById(orderId);

                card.first_name = order.Customer.FirstName;
                card.last_name = order.Customer.LastName;

                // TODO: Add billing address
            }

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

            result.AllowStoringCreditCardNumber = false;
            switch (_codPaymentSettings.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;
        }
Beispiel #8
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();

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

            if (customer == null)
            {
                throw new Exception("Customer cannot be loaded");
            }

            try
            {
                var apiContext = PaypalHelper.GetApiContext(_paypalDirectPaymentSettings);
                var currency   = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
                var payment    = new Payment()
                {
                    #region payer

                    payer = new Payer()
                    {
                        payment_method = "credit_card",

                        #region credit card info

                        funding_instruments = new List <FundingInstrument>
                        {
                            new FundingInstrument
                            {
                                credit_card = new CreditCard
                                {
                                    type         = processPaymentRequest.CreditCardType.ToLowerInvariant(),
                                    number       = processPaymentRequest.CreditCardNumber,
                                    cvv2         = processPaymentRequest.CreditCardCvv2,
                                    expire_month = processPaymentRequest.CreditCardExpireMonth,
                                    expire_year  = processPaymentRequest.CreditCardExpireYear
                                }
                            }
                        },

                        #endregion

                        #region payer info

                        payer_info = new PayerInfo
                        {
                            #region billing address

                            billing_address = customer.BillingAddress == null ? null : new Address
                            {
                                country_code = customer.BillingAddress.Country != null ? customer.BillingAddress.Country.TwoLetterIsoCode : null,
                                state        = customer.BillingAddress.StateProvince != null ? customer.BillingAddress.StateProvince.Abbreviation : null,
                                city         = customer.BillingAddress.City,
                                line1        = customer.BillingAddress.Address1,
                                line2        = customer.BillingAddress.Address2,
                                phone        = customer.BillingAddress.PhoneNumber,
                                postal_code  = customer.BillingAddress.ZipPostalCode
                            },

                            #endregion

                            email      = customer.BillingAddress != null ? customer.BillingAddress.Email : null,
                            first_name = customer.BillingAddress != null ? customer.BillingAddress.FirstName : null,
                            last_name  = customer.BillingAddress != null ? customer.BillingAddress.LastName : null
                        }

                        #endregion
                    },

                    #endregion

                    #region transaction

                    transactions = new List <Transaction>()
                    {
                        new Transaction
                        {
                            #region amount

                            amount = new Amount
                            {
                                total    = processPaymentRequest.OrderTotal.ToString("N", new CultureInfo("en-US")),
                                currency = currency != null ? currency.CurrencyCode : null
                            },

                            #endregion

                            #region shipping address

                            item_list = customer.ShippingAddress == null ? null : new ItemList
                            {
                                shipping_address = new ShippingAddress
                                {
                                    country_code   = customer.ShippingAddress.Country != null ? customer.ShippingAddress.Country.TwoLetterIsoCode : null,
                                    state          = customer.ShippingAddress.StateProvince != null ? customer.ShippingAddress.StateProvince.Abbreviation : null,
                                    city           = customer.ShippingAddress.City,
                                    line1          = customer.ShippingAddress.Address1,
                                    line2          = customer.ShippingAddress.Address2,
                                    phone          = customer.ShippingAddress.PhoneNumber,
                                    postal_code    = customer.ShippingAddress.ZipPostalCode,
                                    recipient_name = string.Format("{0} {1}", customer.ShippingAddress.FirstName, customer.ShippingAddress.LastName)
                                }
                            },

                            #endregion

                            invoice_number = processPaymentRequest.OrderGuid != Guid.Empty ? processPaymentRequest.OrderGuid.ToString() : null
                        }
                    },

                    #endregion

                    intent = _paypalDirectPaymentSettings.TransactMode == TransactMode.Authorize ? "authorize" : "sale",
                }.Create(apiContext);

                if (payment.transactions[0].related_resources.Any() && payment.transactions[0].related_resources[0] != null)
                {
                    if (_paypalDirectPaymentSettings.TransactMode == TransactMode.Authorize)
                    {
                        var authorization = payment.transactions[0].related_resources[0].authorization;
                        if (authorization != null)
                        {
                            result.AuthorizationTransactionId     = authorization.id;
                            result.AuthorizationTransactionResult = authorization.state;
                            result.NewPaymentStatus = GetPaymentStatus(authorization.state);
                        }
                    }
                    else
                    {
                        var sale = payment.transactions[0].related_resources[0].sale;
                        if (sale != null)
                        {
                            result.CaptureTransactionId     = sale.id;
                            result.CaptureTransactionResult = sale.state;
                            result.AvsResult        = sale.processor_response != null ? sale.processor_response.avs_code : string.Empty;
                            result.NewPaymentStatus = GetPaymentStatus(sale.state);
                        }
                    }
                }
                else
                {
                    result.AddError("PayPal error");
                }
            }
            catch (PayPal.PayPalException exc)
            {
                if (exc is PayPal.ConnectionException)
                {
                    var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response);
                    if (error != null)
                    {
                        result.AddError(string.Format("PayPal error: {0} ({1})", error.message, error.name));
                        if (error.details != null)
                        {
                            error.details.ForEach(x => result.AddError(string.Format("{0} {1}", x.field, x.issue)));
                        }
                    }
                }

                //if there are not the specific errors add exception message
                if (result.Success)
                {
                    result.AddError(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                }
            }

            return(result);
        }
Beispiel #9
0
        public override ProcessPaymentRequest GetPaymentInfo(FormCollection form)
        {
            var paymentInfo = new ProcessPaymentRequest();

            return(paymentInfo);
        }
 /// <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)
 {
     return(new ProcessPaymentResult());
 }
Beispiel #11
0
 public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
 {
     return(new ProcessPaymentResult {
         NewPaymentStatus = PaymentStatus.Pending
     });
 }
Beispiel #12
0
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var authentication = PopulateMerchantAuthentication();

            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 + " " + 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 + " " + 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 = string.Format("{0} {1}", "Authorize.NET", "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 SmartException("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 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);
        }
Beispiel #13
0
        private void ProcessNewOrderNotification(string xmlData)
        {
            try
            {
                var    newOrderNotification = (NewOrderNotification)EncodeHelper.Deserialize(xmlData, typeof(NewOrderNotification));
                string googleOrderNumber    = newOrderNotification.googleordernumber;

                XmlNode customerInfo = newOrderNotification.shoppingcart.merchantprivatedata.Any[0];
                int     customerId   = Convert.ToInt32(customerInfo.Attributes["CustomerID"].Value);
                //int customerLanguageId = Convert.ToInt32(customerInfo.Attributes["CustomerLanguageID"].Value);
                //int customerCurrencyId = Convert.ToInt32(customerInfo.Attributes["CustomerCurrencyID"].Value);
                var customer = _customerService.GetCustomerById(customerId);

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

                var cart = customer.ShoppingCartItems
                           .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                           .Where(sci => sci.StoreId == _storeContext.CurrentStore.Id)
                           .ToList();

                _workContext.CurrentCustomer = customer;

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

                //validate cart
                foreach (var sci in cart)
                {
                    bool ok = false;
                    foreach (Item item in newOrderNotification.shoppingcart.items)
                    {
                        if (!String.IsNullOrEmpty(item.merchantitemid))
                        {
                            if ((Convert.ToInt32(item.merchantitemid) == sci.Id) && (item.quantity == sci.Quantity))
                            {
                                ok = true;
                                break;
                            }
                        }
                    }

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


                string[] billingFullname  = newOrderNotification.buyerbillingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                string   billingFirstName = billingFullname[0];
                string   billingLastName  = string.Empty;
                if (billingFullname.Length > 1)
                {
                    billingLastName = billingFullname[1];
                }
                string billingEmail           = newOrderNotification.buyerbillingaddress.email.Trim();
                string billingAddress1        = newOrderNotification.buyerbillingaddress.address1.Trim();
                string billingAddress2        = newOrderNotification.buyerbillingaddress.address2.Trim();
                string billingPhoneNumber     = newOrderNotification.buyerbillingaddress.phone.Trim();
                string billingCity            = newOrderNotification.buyerbillingaddress.city.Trim();
                int?   billingStateProvinceId = null;
                var    billingStateProvince   = _stateProvinceService.GetStateProvinceByAbbreviation(newOrderNotification.buyerbillingaddress.region.Trim());
                if (billingStateProvince != null)
                {
                    billingStateProvinceId = billingStateProvince.Id;
                }
                string billingZipPostalCode = newOrderNotification.buyerbillingaddress.postalcode.Trim();
                int?   billingCountryId     = null;
                var    billingCountry       = _countryService.GetCountryByTwoLetterIsoCode(newOrderNotification.buyerbillingaddress.countrycode.Trim());
                if (billingCountry != null)
                {
                    billingCountryId = billingCountry.Id;
                }

                var billingAddress = customer.Addresses.ToList().FindAddress(
                    billingFirstName, billingLastName, billingPhoneNumber,
                    billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity,
                    billingStateProvinceId, billingZipPostalCode, billingCountryId);

                if (billingAddress == null)
                {
                    billingAddress = new Core.Domain.Common.Address()
                    {
                        FirstName       = billingFirstName,
                        LastName        = billingLastName,
                        PhoneNumber     = billingPhoneNumber,
                        Email           = billingEmail,
                        Address1        = billingAddress1,
                        Address2        = billingAddress2,
                        City            = billingCity,
                        StateProvinceId = billingStateProvinceId,
                        ZipPostalCode   = billingZipPostalCode,
                        CountryId       = billingCountryId,
                        CreatedOnUtc    = DateTime.UtcNow,
                    };
                    customer.Addresses.Add(billingAddress);
                }
                //set default billing address
                customer.BillingAddress = billingAddress;
                _customerService.UpdateCustomer(customer);

                _genericAttributeService.SaveAttribute <ShippingOption>(customer, SystemCustomerAttributeNames.SelectedShippingOption, null, _storeContext.CurrentStore.Id);

                bool shoppingCartRequiresShipping = cart.RequiresShipping();
                if (shoppingCartRequiresShipping)
                {
                    string[] shippingFullname  = newOrderNotification.buyershippingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    string   shippingFirstName = shippingFullname[0];
                    string   shippingLastName  = string.Empty;
                    if (shippingFullname.Length > 1)
                    {
                        shippingLastName = shippingFullname[1];
                    }
                    string shippingEmail           = newOrderNotification.buyershippingaddress.email.Trim();
                    string shippingAddress1        = newOrderNotification.buyershippingaddress.address1.Trim();
                    string shippingAddress2        = newOrderNotification.buyershippingaddress.address2.Trim();
                    string shippingPhoneNumber     = newOrderNotification.buyershippingaddress.phone.Trim();
                    string shippingCity            = newOrderNotification.buyershippingaddress.city.Trim();
                    int?   shippingStateProvinceId = null;
                    var    shippingStateProvince   = _stateProvinceService.GetStateProvinceByAbbreviation(newOrderNotification.buyershippingaddress.region.Trim());
                    if (shippingStateProvince != null)
                    {
                        shippingStateProvinceId = shippingStateProvince.Id;
                    }
                    int?   shippingCountryId     = null;
                    string shippingZipPostalCode = newOrderNotification.buyershippingaddress.postalcode.Trim();
                    var    shippingCountry       = _countryService.GetCountryByTwoLetterIsoCode(newOrderNotification.buyershippingaddress.countrycode.Trim());
                    if (shippingCountry != null)
                    {
                        shippingCountryId = shippingCountry.Id;
                    }

                    var shippingAddress = customer.Addresses.ToList().FindAddress(
                        shippingFirstName, shippingLastName, shippingPhoneNumber,
                        shippingEmail, string.Empty, string.Empty,
                        shippingAddress1, shippingAddress2, shippingCity,
                        shippingStateProvinceId, shippingZipPostalCode, shippingCountryId);
                    if (shippingAddress == null)
                    {
                        shippingAddress = new Core.Domain.Common.Address()
                        {
                            FirstName       = shippingFirstName,
                            LastName        = shippingLastName,
                            PhoneNumber     = shippingPhoneNumber,
                            Email           = shippingEmail,
                            Address1        = shippingAddress1,
                            Address2        = shippingAddress2,
                            City            = shippingCity,
                            StateProvinceId = shippingStateProvinceId,
                            ZipPostalCode   = shippingZipPostalCode,
                            CountryId       = shippingCountryId,
                            CreatedOnUtc    = DateTime.UtcNow,
                        };
                        customer.Addresses.Add(shippingAddress);
                    }
                    //set default shipping address
                    customer.ShippingAddress = shippingAddress;
                    _customerService.UpdateCustomer(customer);

                    if (newOrderNotification.orderadjustment != null &&
                        newOrderNotification.orderadjustment.shipping != null &&
                        newOrderNotification.orderadjustment.shipping.Item != null)
                    {
                        var shippingMethod = (FlatRateShippingAdjustment)newOrderNotification.orderadjustment.shipping.Item;
                        var shippingOption = new ShippingOption();
                        shippingOption.Name = shippingMethod.shippingname;
                        shippingOption.Rate = shippingMethod.shippingcost.Value;
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.SelectedShippingOption, shippingOption, _storeContext.CurrentStore.Id);
                    }
                }

                //customer.LastCalculatedTax = decimal.Zero;

                var paymentInfo = new ProcessPaymentRequest()
                {
                    StoreId = _storeContext.CurrentStore.Id,
                    PaymentMethodSystemName = "Payments.GoogleCheckout",
                    CustomerId        = customer.Id,
                    GoogleOrderNumber = googleOrderNumber
                };
                //TODO set customer language and currency
                //paymentInfo.CustomerLanguage = IoC.Resolve<ILanguageService>().GetLanguageById(CustomerLanguageID);
                //paymentInfo.CustomerCurrency = IoC.Resolve<ICurrencyService>().GetCurrencyById(CustomerCurrencyID);
                var result = _orderProcessingService.PlaceOrder(paymentInfo);
                if (!result.Success)
                {
                    LogMessage("new-order-notification received. CreateOrder() error: Order Number " + googleOrderNumber + ". " + result);
                    return;
                }

                var order = result.PlacedOrder;
                if (order != null)
                {
                    LogMessage("new-order-notification received and saved: Order Number " + order.Id);
                }
            }
            catch (Exception exc)
            {
                LogMessage("processNewOrderNotification Exception: " + exc.Message + ": " + exc.StackTrace);
            }
        }
Beispiel #14
0
        /// <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) return result;

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

            //PrepareAuthorizeNet();

            //var creditCard = new creditCardType
            //{
            //    cardNumber = processPaymentRequest.CreditCardNumber,
            //    expirationDate =
            //        processPaymentRequest.CreditCardExpireMonth.ToString("D2") + processPaymentRequest.CreditCardExpireYear,
            //    cardCode = processPaymentRequest.CreditCardCvv2
            //};

            ////standard api call to retrieve response
            //var paymentType = new paymentType { Item = creditCard };

            //var billTo = new nameAndAddressType
            //{
            //    firstName = customer.BillingAddress.FirstName,
            //    lastName = customer.BillingAddress.LastName,
            //    //email = customer.BillingAddress.Email,
            //    address = customer.BillingAddress.Address1,
            //    //address = customer.BillingAddress.Address1 + " " + customer.BillingAddress.Address2;
            //    city = customer.BillingAddress.City,
            //    zip = customer.BillingAddress.ZipPostalCode
            //};

            //if (!string.IsNullOrEmpty(customer.BillingAddress.Company))
            //    billTo.company = customer.BillingAddress.Company;

            //if (customer.BillingAddress.StateProvince != null)
            //    billTo.state = customer.BillingAddress.StateProvince.Abbreviation;

            //if (customer.BillingAddress.Country != null)
            //    billTo.country = customer.BillingAddress.Country.TwoLetterIsoCode;

            //var dtNow = DateTime.UtcNow;

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

            //var paymentSchedule = new paymentScheduleType
            //{
            //    startDate = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day),
            //    totalOccurrences = Convert.ToInt16(processPaymentRequest.RecurringTotalCycles),
            //    interval = paymentScheduleInterval
            //};

            //var subscriptionType = new ARBSubscriptionType
            //{
            //    name = processPaymentRequest.OrderGuid.ToString(),
            //    amount = Math.Round(processPaymentRequest.OrderTotal, 2),
            //    payment = paymentType,
            //    billTo = billTo,
            //    paymentSchedule = paymentSchedule,
            //    customer = new customerType
            //    {
            //        email = customer.BillingAddress.Email
            //        //phone number should be in one of following formats: 111- 111-1111 or (111) 111-1111.
            //        //phoneNumber = customer.BillingAddress.PhoneNumber
            //    },

            //    order = new orderType
            //    {
            //        //x_invoice_num is 20 chars maximum. hece we also pass x_description
            //        invoiceNumber = processPaymentRequest.OrderGuid.ToString().Substring(0, 20),
            //        description = String.Format("Recurring payment #{0}", processPaymentRequest.OrderGuid)
            //    }
            //};

            //if (customer.ShippingAddress != null)
            //{
            //    var shipTo = new nameAndAddressType
            //    {
            //        firstName = customer.ShippingAddress.FirstName,
            //        lastName = customer.ShippingAddress.LastName,
            //        address = customer.ShippingAddress.Address1,
            //        city = customer.ShippingAddress.City,
            //        zip = customer.ShippingAddress.ZipPostalCode
            //    };

            //    if (customer.ShippingAddress.StateProvince != null)
            //    {
            //        shipTo.state = customer.ShippingAddress.StateProvince.Abbreviation;
            //    }

            //    subscriptionType.shipTo = shipTo;
            //}

            //var request = new ARBCreateSubscriptionRequest { subscription = subscriptionType };

            //// instantiate the contoller that will call the service
            //var controller = new ARBCreateSubscriptionController(request);
            //controller.Execute();

            //// get the response from the service (errors contained if any)
            //var response = controller.GetApiResponse();

            ////validate
            //if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
            //{
            //    result.SubscriptionTransactionId = response.subscriptionId;
            //    result.AuthorizationTransactionCode = response.refId;
            //    result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.refId, response.subscriptionId);
            //}
            //else if (response != null)
            //{
            //    foreach (var responseMessage in response.messages.message)
            //    {
            //        result.AddError(string.Format("Error processing recurring payment #{0}: {1}", responseMessage.code, responseMessage.text));
            //    }
            //}
            //else
            //{
            //    result.AddError("Authorize.NET unknown error");
            //}

            //return result;
            throw new Exception("this method not implemented");
        }
Beispiel #15
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();
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            try
            {
                PrepareGBS();

                //var creditCard = new creditCardType
                //{
                //    cardNumber = processPaymentRequest.CreditCardNumber,
                //    expirationDate =
                //        processPaymentRequest.CreditCardExpireMonth.ToString("D2") + processPaymentRequest.CreditCardExpireYear,
                //    cardCode = processPaymentRequest.CreditCardCvv2
                //};

                ////standard api call to retrieve response
                //var paymentType = new paymentType { Item = creditCard };

                //transactionTypeEnum transactionType;

                //switch (_authorizeNetPaymentSettings.TransactMode)
                //{
                //    case TransactMode.Authorize:
                //        transactionType = transactionTypeEnum.authOnlyTransaction;
                //        break;
                //    case TransactMode.AuthorizeAndCapture:
                //        transactionType = transactionTypeEnum.authCaptureTransaction;
                //        break;
                //    default:
                //        throw new NopException("Not supported transaction mode");
                //}

                //var billTo = new customerAddressType
                //{
                //    firstName = customer.BillingAddress.FirstName,
                //    lastName = customer.BillingAddress.LastName,
                //    email = customer.BillingAddress.Email,
                //    address = customer.BillingAddress.Address1,
                //    city = customer.BillingAddress.City,
                //    zip = customer.BillingAddress.ZipPostalCode
                //};

                //if (!string.IsNullOrEmpty(customer.BillingAddress.Company))
                //    billTo.company = customer.BillingAddress.Company;

                //if (customer.BillingAddress.StateProvince != null)
                //    billTo.state = customer.BillingAddress.StateProvince.Abbreviation;

                //if (customer.BillingAddress.Country != null)
                //    billTo.country = customer.BillingAddress.Country.TwoLetterIsoCode;

                //var transactionRequest = new transactionRequestType
                //{
                //    transactionType = transactionType.ToString(),
                //    amount = Math.Round(processPaymentRequest.OrderTotal, 2),
                //    payment = paymentType,
                //    currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode,
                //    billTo = billTo,
                //    customerIP = _webHelper.GetCurrentIpAddress(),
                //    order = new orderType
                //    {
                //        //x_invoice_num is 20 chars maximum. hece we also pass x_description
                //        invoiceNumber = processPaymentRequest.OrderGuid.ToString().Substring(0, 20),
                //        description = string.Format("Full order #{0}", processPaymentRequest.OrderGuid)
                //    }
                //};

                //var request = new createTransactionRequest { transactionRequest = transactionRequest };

                //// instantiate the contoller that will call the service
                //var controller = new createTransactionController(request);
                //controller.Execute();

                //// get the response from the service (errors contained if any)



                //NOP WEB SERVICE CALL START HERE --------------------------------------------------------------------------------------------------------------------
                //create nop payment object from user data
                PaymentTransactionModel payment = new PaymentTransactionModel();
                payment.firstName     = customer.BillingAddress.FirstName;
                payment.lastName      = customer.BillingAddress.LastName;
                payment.streetAddress = customer.BillingAddress.Address1;
                payment.billingCity   = customer.BillingAddress.City;
                payment.postalCode    = customer.BillingAddress.ZipPostalCode;
                payment.countryCode   = customer.BillingAddress.Country.Name;
                if (payment.countryCode == "United States")
                {
                    payment.countryCode = "US";
                }
                else
                {
                    payment.countryCode = "US";
                }
                payment.cardExpireMonth = processPaymentRequest.CreditCardExpireMonth.ToString().Length == 1 ? "0" + processPaymentRequest.CreditCardExpireMonth.ToString() : processPaymentRequest.CreditCardExpireMonth.ToString(); //prepend 0 for single digit months
                payment.cardExpireYear  = processPaymentRequest.CreditCardExpireYear.ToString();
                payment.cardNum         = processPaymentRequest.CreditCardNumber;
                payment.orderAmount     = processPaymentRequest.OrderTotal.ToString();
                payment.pcDestZip       = (customer.ShippingAddress != null && customer.ShippingAddress.ZipPostalCode != null) ? customer.ShippingAddress.ZipPostalCode : String.Empty;
                Object value = null;
                NopResourceDisplayNameAttribute orderNumberKeyGBS = new NopResourceDisplayNameAttribute(("Account.CustomerOrders.OrderNumber"));
                if (processPaymentRequest.CustomValues.TryGetValue(orderNumberKeyGBS.DisplayName, out value))
                {
                    payment.orderID   = processPaymentRequest.CustomValues[orderNumberKeyGBS.DisplayName].ToString();
                    payment.pcOrderID = processPaymentRequest.CustomValues[orderNumberKeyGBS.DisplayName].ToString();
                }
                else
                {
                    payment.orderID   = "NA";
                    payment.pcOrderID = "NA";
                }
                payment.state   = customer.BillingAddress.StateProvince.Abbreviation;
                payment.tax     = _orderTotalCalculationService.GetTaxTotal((IList <ShoppingCartItem>)customer.ShoppingCartItems, false).ToString();
                payment.sandBox = _gbsPaymentSettings.UseSandbox;


                if (Convert.ToBoolean(processPaymentRequest.CustomValues["SavedProfile"]) == true)
                {
                    payment.createProfile = false;
                    payment.useProfile    = true;
                    payment.profileID     = processPaymentRequest.CustomValues["ProfileID"].ToString();
                }
                else
                {
                    payment.createProfile = true;
                    payment.useProfile    = false;
                    payment.profileID     = "";
                }


                //will need to be able to switch between sand and production version
                string address = _gbsPaymentSettings.GBSPaymentWebServiceAddress;



                GBSPaymentServiceClient gateway = new GBSPaymentServiceClient();

                //calls to GBSPaymentGateway function
                var response = gateway.AuthorizeAndCapture(payment, address, _gbsPaymentSettings.LoginId, _gbsPaymentSettings.Password);


                //use returned GBSTransactionResponse to tell nop what occured in submit
                switch (response.responseCode)
                {
                case GBSTransactionResponse.ResponseCodeType.Approved:
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                    break;

                case GBSTransactionResponse.ResponseCodeType.Declined:
                case GBSTransactionResponse.ResponseCodeType.Error:
                    result.NewPaymentStatus = PaymentStatus.Voided;
                    break;

                default:
                    result.NewPaymentStatus = PaymentStatus.Voided;
                    break;
                }
                //validate
                if (GetErrors(response, result.Errors))
                {
                    return(result);
                }

                if (_gbsPaymentSettings.TransactMode == TransactMode.Authorize)
                {
                    result.AuthorizationTransactionCode = string.Format("{0},{1}", response.transactId, response.authCode);
                }
                //if (_authorizeNetPaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture)
                //    result.CaptureTransactionId = string.Format("{0},{1}", response.transactionResponse.transId, response.transactionResponse.authCode);

                result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.responseCode, response.authCode);
                //result.AvsResult = response.transactionResponse.avsResultCode;
                //result.NewPaymentStatus = _authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize ? PaymentStatus.Authorized : PaymentStatus.Paid;

                //var congrats = "Congrats the payment was successful, now insert profile id into DB";

                bool storeProfile = Convert.ToBoolean(processPaymentRequest.CustomValues["StoreProfile"]);

                if (payment.createProfile == true && storeProfile == true)
                {
                    string nickName = String.IsNullOrEmpty(processPaymentRequest.CustomValues["NickName"].ToString()) ? "" : processPaymentRequest.CustomValues["NickName"].ToString();
                    nickName = nickName.Replace("'", "''");

                    string last4Digits = response.accountNum.ToString();
                    last4Digits = last4Digits.Substring(last4Digits.Length - 4);

                    DBManager manager = new DBManager();
                    Dictionary <string, string> paramDic = new Dictionary <string, string>();
                    paramDic.Add("@CustomerID", customer.Id.ToString());
                    paramDic.Add("@ProfileID", response.customerRefNum.ToString());
                    paramDic.Add("@NickName", nickName);
                    paramDic.Add("@Last4Digits", last4Digits);
                    paramDic.Add("@CardType", response.cardBrand.ToString());
                    paramDic.Add("@ExpMonth", payment.cardExpireMonth);
                    paramDic.Add("@ExpYear", payment.cardExpireYear);

                    string insert = "INSERT INTO Profiles (CustomerID, ProfileID, NickName, Last4Digits, CardType, ExpMonth, ExpYear) ";
                    insert += "VALUES ('" + customer.Id + "', '" + response.customerRefNum + "', '" + nickName + "', '" + last4Digits + "', '" + response.cardBrand + "', '" + payment.cardExpireMonth + "', '" + payment.cardExpireYear + "')";
                    try
                    {
                        manager.SetParameterizedQueryNoData(insert, paramDic);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            _logger.Error("Payment Plugin Error inserting profile on auth : " + ex.Message + ": query = " + insert, ex, null);
                        }
                        catch (Exception ex1) {
                            _logger.Error("Payment Plugin Error inserting profile on auth with additional failure to log the sql statement : " + ex.Message, ex, null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Payment Plugin Error : " + ex.Message, ex, null);
                throw new Exception("Payment Plugin Exception: " + ex.Message, ex);
            }

            return(result);
        }
Beispiel #16
0
        public IActionResult Success(IFormCollection form)
        {
            var processor = _paymentService.LoadPaymentMethodBySystemName(IyzicoPayPaymentDefaults.SystemName) as IyzicoPayPaymentProcessor;

            if (processor == null || !_paymentService.IsPaymentMethodActive(processor) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("Iyzico  module cannot be loaded");
            }
            var model = new SuccessModel();
            CreateThreedsPaymentRequest threquest = new CreateThreedsPaymentRequest();

            threquest.Locale           = Locale.TR.ToString();
            threquest.PaymentId        = form["paymentId"];
            threquest.ConversationData = form["conversationData"];
            threquest.ConversationId   = form["conversationId"];
            ThreedsPayment threedsPayment = ThreedsPayment.Create(threquest,
                                                                  HelperApiOptions.GetApiContext(_iyzicoPayPaymentSettings));

            if (threedsPayment.Status == "success")
            {
                if (form["mdStatus"] == "1")
                {
                    var customer = _customerService.GetCustomerByGuid(new Guid(threedsPayment.ConversationId));
                    var query    = _orderService.SearchOrders(customerId: customer.Id).ToList();
                    var order    = query.FirstOrDefault();
                    order.PaymentStatus = threedsPayment.FraudStatus == 1 ? PaymentStatus.Paid : PaymentStatus.Pending;
                    order.OrderStatus   = OrderStatus.Processing;
                    order.AuthorizationTransactionId   = threedsPayment.PaymentId;
                    order.AuthorizationTransactionCode = threedsPayment.AuthCode;
                    order.PaidDateUtc = DateTime.UtcNow;
                    var paymentrequest = new ProcessPaymentRequest();
                    var ordernote      = new OrderNote();
                    ordernote.DisplayToCustomer = false;
                    ordernote.CreatedOnUtc      = DateTime.UtcNow;
                    ordernote.Note = "Fraud:" + threedsPayment.FraudStatus;

                    paymentrequest.CustomValues.Add("fraudstatus", threedsPayment.FraudStatus);
                    foreach (var item in threedsPayment.PaymentItems)
                    {
                        ordernote.Note += string.Format("{0}{1}", item.ItemId, item.PaymentTransactionId);
                    }
                    order.OrderNotes.Add(ordernote);
                    _orderService.UpdateOrder(order);;
                    _orderService.UpdateOrder(order);
                    if (_orderSettings.OnePageCheckoutEnabled)
                    {
                        return(RedirectToRoute("HomePage"));
                    }
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }
                else
                {
                    switch (form["mdStatus"])
                    {
                    case "0": model.Errorr = "3-D Secure imzası geçersiz veya doğrulama"; break;

                    case "2": model.Errorr = "Kart sahibi veya bankası sisteme kayıtlı değil"; break;

                    case "3": model.Errorr = "Kartın bankası sisteme kayıtlı değil"; break;

                    case "4": model.Errorr = "Doğrulama denemesi, kart sahibi sisteme daha sonra kayıt olmayı seçmiş"; break;

                    case "5": model.Errorr = "Doğrulama yapılamıyor"; break;

                    case "6": model.Errorr = "3-D Secure hatası"; break;

                    case "7": model.Errorr = "Sistem hatası"; break;

                    case "8": model.Errorr = "Bilinmeyen kart no"; break;

                    default: model.Errorr = "Hata Oluştu"; break;
                    }
                    return(View("~/Plugins/Payments.IyzicoPay/Views/Success.cshtml", model));
                }
            }
            else
            {
                model.Errorr = threedsPayment.ErrorMessage;
                return(View("~/Plugins/Payments.IyzicoPay/Views/Success.cshtml", model));
            }
        }
        public ActionResult ConfirmOrder(FormCollection form)
        {
            //validation
            var cart = _workContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id);

            if (cart.Count == 0)
            {
                return(RedirectToRoute("ShoppingCart"));
            }

            if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
            {
                return(new HttpUnauthorizedResult());
            }


            //model
            var model = new CheckoutConfirmModel();

            try
            {
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                    {
                        return(RedirectToAction("PaymentMethod"));
                    }

                    processPaymentRequest = new ProcessPaymentRequest();
                }

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
                {
                    throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
                }

                //place order
                processPaymentRequest.StoreId    = _storeContext.CurrentStore.Id;
                processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
                processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute <string>(
                    SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, _storeContext.CurrentStore.Id);

                var placeOrderExtraData = new Dictionary <string, string>();
                placeOrderExtraData["CustomerComment"] = form["customercommenthidden"];

                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData);

                if (placeOrderResult.Success)
                {
                    var postProcessPaymentRequest = new PostProcessPaymentRequest
                    {
                        Order = placeOrderResult.PlacedOrder
                    };
                    _paymentService.PostProcessPayment(postProcessPaymentRequest);

                    _httpContext.Session["PaymentData"]      = null;
                    _httpContext.Session["OrderPaymentInfo"] = null;
                    _httpContext.RemoveCheckoutState();

                    if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
                    {
                        //redirection or POST has been done in PostProcessPayment
                        return(Content("Redirected"));
                    }
                    else
                    {
                        //if no redirection has been done (to a third-party payment page)
                        //theoretically it's not possible
                        return(RedirectToAction("Completed"));
                    }
                }
                else
                {
                    foreach (var error in placeOrderResult.Errors)
                    {
                        model.Warnings.Add(error);
                    }
                }
            }
            catch (Exception exc)
            {
                Logger.Warning(exc.Message, exc);
                model.Warnings.Add(exc.Message);
            }

            //If we got this far, something failed, redisplay form

            //if (model.Warnings.Count > 0)
            //	TempData["ConfirmOrderWarnings"] = model.Warnings;

            //return RedirectToRoute("CheckoutConfirm");
            return(View(model));
        }
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult
            {
                NewPaymentStatus = PaymentStatus.Pending
            };

            HttpContext.Session.SafeRemove("PayPalCheckoutCompleted");

            var storeId  = processPaymentRequest.StoreId;
            var customer = Services.WorkContext.CurrentCustomer;
            var session  = HttpContext.GetPayPalState(_providerSystemName, customer, storeId, GenericAttributeService);

            if (session.AccessToken.IsEmpty() || session.PaymentId.IsEmpty())
            {
                // Do not place order because we cannot execute the payment.
                session.SessionExpired = true;
                result.AddError(T("Plugins.SmartStore.PayPal.SessionExpired"));

                // Redirect to payment page and create new payment (we need the payment id).
                var urlHelper = new UrlHelper(HttpContext.Request.RequestContext);
                HttpContext.Response.Redirect(urlHelper.Action("PaymentMethod", "Checkout", new { area = "" }));

                return(result);
            }

            processPaymentRequest.OrderGuid = session.OrderGuid;

            var settings  = Services.Settings.LoadSetting <TSetting>(storeId);
            var apiResult = PayPalService.ExecutePayment(settings, session);

            if (apiResult.Success && apiResult.Json != null)
            {
                var     state         = (string)apiResult.Json.state;
                string  reasonCode    = null;
                dynamic relatedObject = null;

                if (!state.IsCaseInsensitiveEqual("failed"))
                {
                    // the payment id is required to find the order during webhook message processing
                    result.AuthorizationTransactionCode = apiResult.Id;

                    // intent: "sale" for immediate payment, "authorize" for pre-authorized payments and "order" for an order.
                    // info required cause API has different endpoints for different intents.
                    var intent = (string)apiResult.Json.intent;

                    if (intent.IsCaseInsensitiveEqual("sale"))
                    {
                        relatedObject = apiResult.Json.transactions[0].related_resources[0].sale;

                        session.PaymentInstruction = PayPalService.ParsePaymentInstruction(apiResult.Json.payment_instruction) as PayPalPaymentInstruction;

                        // Test session data:
                        //session.PaymentInstruction = new PayPalPaymentInstruction
                        //{
                        //	ReferenceNumber = "123456789",
                        //	Type = "PAY_UPON_INVOICE",
                        //	Amount = 9.99M,
                        //	AmountCurrencyCode = "EUR",
                        //	Note = "This is a test instruction!",
                        //	RecipientBanking = new PayPalPaymentInstruction.RecipientBankingInstruction
                        //	{
                        //		BankName = "John Pierpont Morgan & Company",
                        //		AccountHolderName = "Max Mustermann",
                        //		AccountNumber = "987654321",
                        //		Iban = "DE654321987654321",
                        //		Bic = "DUDEXX321654"
                        //	}
                        //};
                    }
                    else
                    {
                        relatedObject = apiResult.Json.transactions[0].related_resources[0].authorization;
                    }

                    if (relatedObject != null)
                    {
                        state      = (string)relatedObject.state;
                        reasonCode = (string)relatedObject.reason_code;

                        // See PayPalService.Refund().
                        result.AuthorizationTransactionResult = "{0} ({1})".FormatInvariant(state.NaIfEmpty(), intent.NaIfEmpty());
                        result.AuthorizationTransactionId     = (string)relatedObject.id;

                        result.NewPaymentStatus = PayPalService.GetPaymentStatus(state, reasonCode, PaymentStatus.Authorized);

                        if (result.NewPaymentStatus == PaymentStatus.Paid)
                        {
                            result.CaptureTransactionResult = result.AuthorizationTransactionResult;
                            result.CaptureTransactionId     = result.AuthorizationTransactionId;
                        }
                    }
                }
                else
                {
                    var failureReason = (string)apiResult.Json.failure_reason;

                    result.Errors.Add(T("Plugins.SmartStore.PayPal.PaymentExecuteFailed").Text.Grow(failureReason, " "));
                }
            }

            if (!apiResult.Success)
            {
                result.Errors.Add(apiResult.ErrorMessage);
            }

            return(result);
        }
 /// <summary>
 /// Process a payment
 /// </summary>
 /// <param name="processPaymentRequest">Payment info required for an order processing</param>
 /// <returns>
 /// A task that represents the asynchronous operation
 /// The task result contains the process payment result
 /// </returns>
 public Task <ProcessPaymentResult> ProcessPaymentAsync(ProcessPaymentRequest processPaymentRequest)
 {
     return(Task.FromResult(new ProcessPaymentResult()));
 }
 private Transaction CreateTransaction(ProcessPaymentRequest request)
 {
     return new Transaction
     {
         amount = new Amount
         {
             total = request.Payment.Amount.ToString("f2", CultureInfo.InvariantCulture),
             currency = request.CurrencyCode
         },
         description = request.Payment.Description
     };
 }
 /// <summary>
 /// Process recurring payment
 /// </summary>
 /// <param name="processPaymentRequest">Payment info required for an order processing</param>
 /// <returns>
 /// A task that represents the asynchronous operation
 /// The task result contains the process payment result
 /// </returns>
 public Task <ProcessPaymentResult> ProcessRecurringPaymentAsync(ProcessPaymentRequest processPaymentRequest)
 {
     return(Task.FromResult(new ProcessPaymentResult {
         Errors = new[] { "Recurring payment not supported" }
     }));
 }
Beispiel #22
0
        public PreProcessPaymentResult PreProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new PreProcessPaymentResult();

            if (processPaymentRequest.CreditCardType.ToLower().Trim() == "visa")
            {
                result.CardType = "1";
            }
            if (processPaymentRequest.CreditCardType.ToLower().Trim() == "mastercard")
            {
                result.CardType = "2";
            }
            //CC shall be either visa or master card!
            if (result.CardType != "1" && result.CardType != "2")
            {
                return(result);
            }
            result.PaymentRequest = processPaymentRequest;
            result.FailUrl        = _FinansBankPaymentSettings.ErrorURL;
            result.OkUrl          = _FinansBankPaymentSettings.SuccessURL;
            result.RandomToken    = DateTime.Now.ToString();
            result.RedirectURL    = _FinansBankPaymentSettings.HostAddress3D;
            result.StoreType      = _FinansBankPaymentSettings.StoreType;
            result.StoreKey       = _FinansBankPaymentSettings.StoreKey;
            result.ChargeType     = "Auth";
            result.Lang           = "tr";
            result.Currency       = "949";
            result.StoreName      = _FinansBankPaymentSettings.StoreName;
            result.ClientId       = _FinansBankPaymentSettings.ClientId;
            result.OrderId        = processPaymentRequest.OrderGuid.ToString();
            string installment = processPaymentRequest.Installment <= 1 ? "" : processPaymentRequest.Installment.ToString();

            result.Installment           = installment;
            result.CreditCardNumber      = processPaymentRequest.CreditCardNumber;
            result.CreditCardExpireYear  = (processPaymentRequest.CreditCardExpireYear % 100).ToString();
            result.CreditCardExpireMonth = GetMonth(processPaymentRequest.CreditCardExpireMonth.ToString());;
            result.CreditCardCvv2        = processPaymentRequest.CreditCardCvv2;
            result.CreditCardNumber      = processPaymentRequest.CreditCardNumber;
            result.CustomerId            = processPaymentRequest.CustomerId.ToString();
            var currency = GetCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));

            result.Amount = GetCulturePrice(currency, processPaymentRequest.OrderTotal);


            String hashstr = result.ClientId +
                             result.OrderId +
                             result.Amount +
                             result.OkUrl +
                             result.FailUrl +
                             result.ChargeType +
                             result.Installment +//Installment- for now we do not use
                             result.RandomToken +
                             result.StoreKey;

            System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] hashbytes  = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(hashstr);
            byte[] inputbytes = sha.ComputeHash(hashbytes);
            String hash       = Convert.ToBase64String(inputbytes);

            result.Hash = hash;

            result.RequiresRedirection = true;

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



            return(result);
        }
Beispiel #23
0
        /// <summary>
        /// Create request parameters to charge transaction
        /// </summary>
        /// <param name="paymentRequest">Payment request parameters</param>
        /// <param name="isRecurringPayment">Whether it is a recurring payment</param>
        /// <returns>Charge request parameters</returns>
        private ExtendedChargeRequest CreateChargeRequest(ProcessPaymentRequest paymentRequest, bool isRecurringPayment)
        {
            //get customer
            var customer = _customerService.GetCustomerById(paymentRequest.CustomerId);

            if (customer == null)
            {
                throw new NopException("Customer cannot be loaded");
            }

            //get the primary store currency
            var currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);

            if (currency == null)
            {
                throw new NopException("Primary store currency cannot be loaded");
            }

            //whether the currency is supported by the Square
            if (!Enum.TryParse(currency.CurrencyCode, out SquareModel.Money.CurrencyEnum moneyCurrency))
            {
                throw new NopException($"The {currency.CurrencyCode} currency is not supported by the Square");
            }

            //check customer's billing address, shipping address and email,
            Func <Address, SquareModel.Address> createAddress = (address) => address == null ? null : new SquareModel.Address
                                                                (
                AddressLine1: address.Address1,
                AddressLine2: address.Address2,
                AdministrativeDistrictLevel1: address.StateProvince?.Abbreviation,
                Country: Enum.TryParse(address.Country?.TwoLetterIsoCode, out SquareModel.Address.CountryEnum countryCode)
                    ? (SquareModel.Address.CountryEnum?)countryCode: null,
                FirstName: address.FirstName,
                LastName: address.LastName,
                Locality: address.City,
                PostalCode: address.ZipPostalCode
                                                                );
            var billingAddress  = createAddress(customer.BillingAddress);
            var shippingAddress = billingAddress == null?createAddress(customer.ShippingAddress) : null;

            var email = customer.BillingAddress != null ? customer.BillingAddress.Email : customer.ShippingAddress?.Email;

            //the transaction is ineligible for chargeback protection if they are not provided
            if ((billingAddress == null && shippingAddress == null) || string.IsNullOrEmpty(email))
            {
                _logger.Warning("Square payment warning: Address or email is not provided, so the transaction is ineligible for chargeback protection", customer: customer);
            }

            //the amount of money, in the smallest denomination of the currency indicated by currency. For example, when currency is USD, amount is in cents;
            //most currencies consist of 100 units of smaller denomination, so we multiply the total by 100
            var orderTotal  = (int)(paymentRequest.OrderTotal * 100);
            var amountMoney = new SquareModel.Money(Amount: orderTotal, Currency: moneyCurrency);

            //create common charge request parameters
            var chargeRequest = new ExtendedChargeRequest
                                (
                AmountMoney: amountMoney,
                BillingAddress: billingAddress,
                BuyerEmailAddress: email,
                DelayCapture: _squarePaymentSettings.TransactionMode == TransactionMode.Authorize,
                IdempotencyKey: Guid.NewGuid().ToString(),
                IntegrationId: !string.IsNullOrEmpty(SquarePaymentDefaults.IntegrationId) ? SquarePaymentDefaults.IntegrationId : null,
                Note: string.Format(SquarePaymentDefaults.PaymentNote, paymentRequest.OrderGuid),
                ReferenceId: paymentRequest.OrderGuid.ToString(),
                ShippingAddress: shippingAddress
                                );

            //try to get previously stored card details
            var storedCardKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.StoredCard.Key");

            if (paymentRequest.CustomValues.TryGetValue(storedCardKey, out object storedCardId) && !storedCardId.ToString().Equals("0"))
            {
                //check whether customer exists
                var customerId     = customer.GetAttribute <string>(SquarePaymentDefaults.CustomerIdAttribute);
                var squareCustomer = _squarePaymentManager.GetCustomer(customerId);
                if (squareCustomer == null)
                {
                    throw new NopException("Failed to retrieve customer");
                }

                //set 'card on file' to charge
                chargeRequest.CustomerId     = squareCustomer.Id;
                chargeRequest.CustomerCardId = storedCardId.ToString();
                return(chargeRequest);
            }

            //or try to get the card nonce
            var cardNonceKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.CardNonce.Key");

            if (!paymentRequest.CustomValues.TryGetValue(cardNonceKey, out object cardNonce) || string.IsNullOrEmpty(cardNonce?.ToString()))
            {
                throw new NopException("Failed to get the card nonce");
            }

            //remove the card nonce from payment custom values, since it is no longer needed
            paymentRequest.CustomValues.Remove(cardNonceKey);

            //whether to save card details for the future purchasing
            var saveCardKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.SaveCard.Key");

            if (paymentRequest.CustomValues.TryGetValue(saveCardKey, out object saveCardValue) && saveCardValue is bool saveCard && saveCard && !customer.IsGuest())
            {
                //remove the value from payment custom values, since it is no longer needed
                paymentRequest.CustomValues.Remove(saveCardKey);

                try
                {
                    //check whether customer exists
                    var customerId     = customer.GetAttribute <string>(SquarePaymentDefaults.CustomerIdAttribute);
                    var squareCustomer = _squarePaymentManager.GetCustomer(customerId);

                    if (squareCustomer == null)
                    {
                        //try to create the new one, if not exists
                        var customerRequest = new SquareModel.CreateCustomerRequest
                                              (
                            EmailAddress: customer.Email,
                            Nickname: customer.Username,
                            GivenName: customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName),
                            FamilyName: customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName),
                            PhoneNumber: customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone),
                            CompanyName: customer.GetAttribute <string>(SystemCustomerAttributeNames.Company),
                            ReferenceId: customer.CustomerGuid.ToString()
                                              );
                        squareCustomer = _squarePaymentManager.CreateCustomer(customerRequest);
                        if (squareCustomer == null)
                        {
                            throw new NopException("Failed to create customer. Error details in the log");
                        }

                        //save customer identifier as generic attribute
                        _genericAttributeService.SaveAttribute(customer, SquarePaymentDefaults.CustomerIdAttribute, squareCustomer.Id);
                    }

                    //create request parameters to create the new card
                    var cardRequest = new SquareModel.CreateCustomerCardRequest
                                      (
                        BillingAddress: chargeRequest.BillingAddress ?? chargeRequest.ShippingAddress,
                        CardNonce: cardNonce.ToString()
                                      );

                    //set postal code
                    var postalCodeKey = _localizationService.GetResource("Plugins.Payments.Square.Fields.PostalCode.Key");
                    if (paymentRequest.CustomValues.TryGetValue(postalCodeKey, out object postalCode) && !string.IsNullOrEmpty(postalCode.ToString()))
                    {
                        //remove the value from payment custom values, since it is no longer needed
                        paymentRequest.CustomValues.Remove(postalCodeKey);

                        cardRequest.BillingAddress            = cardRequest.BillingAddress ?? new SquareModel.Address();
                        cardRequest.BillingAddress.PostalCode = postalCode.ToString();
                    }

                    //try to create card
                    var card = _squarePaymentManager.CreateCustomerCard(squareCustomer.Id, cardRequest);
                    if (card == null)
                    {
                        throw new NopException("Failed to create card. Error details in the log");
                    }

                    //save card identifier to payment custom values for further purchasing
                    if (isRecurringPayment)
                    {
                        paymentRequest.CustomValues.Add(storedCardKey, card.Id);
                    }

                    //set 'card on file' to charge
                    chargeRequest.CustomerId     = squareCustomer.Id;
                    chargeRequest.CustomerCardId = card.Id;
                    return(chargeRequest);
                }
                catch (Exception exception)
                {
                    _logger.Warning(exception.Message, exception, customer);
                    if (isRecurringPayment)
                    {
                        throw new NopException("For recurring payments you need to save the card details");
                    }
                }
            }
Beispiel #24
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)
 {
     return(AuthorizeOrSale(processPaymentRequest));
 }
        public ActionResult ConfirmOrder(FormCollection form)
        {
            //validation
            var storeId  = _storeContext.CurrentStore.Id;
            var customer = _workContext.CurrentCustomer;
            var cart     = customer.GetCartItems(ShoppingCartType.ShoppingCart, storeId);

            if (cart.Count == 0)
            {
                return(RedirectToRoute("ShoppingCart"));
            }

            if ((customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
            {
                return(new HttpUnauthorizedResult());
            }

            var model = new CheckoutConfirmModel();
            PlaceOrderResult          placeOrderResult          = null;
            PostProcessPaymentRequest postProcessPaymentRequest = null;

            try
            {
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                    {
                        return(RedirectToAction("PaymentMethod"));
                    }

                    processPaymentRequest = new ProcessPaymentRequest();
                }

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(customer))
                {
                    throw new Exception(T("Checkout.MinOrderPlacementInterval"));
                }

                //place order
                processPaymentRequest.StoreId    = storeId;
                processPaymentRequest.CustomerId = customer.Id;
                processPaymentRequest.PaymentMethodSystemName = customer.GetAttribute <string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, storeId);

                var placeOrderExtraData = new Dictionary <string, string>();
                placeOrderExtraData["CustomerComment"]               = form["customercommenthidden"];
                placeOrderExtraData["SubscribeToNewsLetter"]         = form["SubscribeToNewsLetterHidden"];
                placeOrderExtraData["AcceptThirdPartyEmailHandOver"] = form["AcceptThirdPartyEmailHandOverHidden"];

                placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData);

                if (!placeOrderResult.Success)
                {
                    model.Warnings.AddRange(placeOrderResult.Errors.Select(x => HtmlUtils.ConvertPlainTextToHtml(x)));
                }
            }
            catch (Exception exception)
            {
                Logger.Warning(exception.Message, exception);

                if (!model.Warnings.Any(x => x == exception.Message))
                {
                    model.Warnings.Add(exception.Message);
                }
            }

            if (placeOrderResult == null || !placeOrderResult.Success || model.Warnings.Any())
            {
                return(View(model));
            }

            try
            {
                postProcessPaymentRequest = new PostProcessPaymentRequest
                {
                    Order = placeOrderResult.PlacedOrder
                };

                _paymentService.PostProcessPayment(postProcessPaymentRequest);
            }
            catch (Exception exception)
            {
                NotifyError(exception);
            }
            finally
            {
                _httpContext.Session["PaymentData"]      = null;
                _httpContext.Session["OrderPaymentInfo"] = null;
                _httpContext.RemoveCheckoutState();
            }

            if (postProcessPaymentRequest != null && postProcessPaymentRequest.RedirectUrl.HasValue())
            {
                return(Redirect(postProcessPaymentRequest.RedirectUrl));
            }

            return(RedirectToAction("Completed"));
        }
Beispiel #26
0
        /// <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)
        {
            Log("ProcessRecurringPayment");

            return(null);
        }
 /// <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)
 {
     return(new ProcessPaymentResult {
         Errors = new[] { "Recurring payment not supported" }
     });
 }
        /// <summary>
        /// Prepare details to place an order. It also sets some properties to "processPaymentRequest"
        /// </summary>
        /// <param name="processPaymentRequest">Process payment request</param>
        /// <returns>Details</returns>
        protected override PlaceOrderContainer PreparePlaceOrderDetails(ProcessPaymentRequest processPaymentRequest)
        {
            var details = new PlaceOrderContainer
            {
                //customer
                Customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId)
            };

            if (details.Customer == null)
            {
                throw new ArgumentException("Customer is not set");
            }

            //affiliate
            var affiliate = _affiliateService.GetAffiliateById(details.Customer.AffiliateId);

            if (affiliate != null && affiliate.Active && !affiliate.Deleted)
            {
                details.AffiliateId = affiliate.Id;
            }

            //check whether customer is guest
            if (_customerService.IsGuest(details.Customer) && !_orderSettings.AnonymousCheckoutAllowed)
            {
                throw new NopException("Anonymous checkout is not allowed");
            }

            //customer currency
            var currencyTmp = _currencyService.GetCurrencyById(
                _genericAttributeService.GetAttribute <int>(details.Customer, NopCustomerDefaults.CurrencyIdAttribute, processPaymentRequest.StoreId));
            var customerCurrency     = currencyTmp != null && currencyTmp.Published ? currencyTmp : _workContext.WorkingCurrency;
            var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);

            details.CustomerCurrencyCode = customerCurrency.CurrencyCode;
            details.CustomerCurrencyRate = customerCurrency.Rate / primaryStoreCurrency.Rate;

            //customer language
            details.CustomerLanguage = _languageService.GetLanguageById(
                _genericAttributeService.GetAttribute <int>(details.Customer, NopCustomerDefaults.LanguageIdAttribute, processPaymentRequest.StoreId));
            if (details.CustomerLanguage == null || !details.CustomerLanguage.Published)
            {
                details.CustomerLanguage = _workContext.WorkingLanguage;
            }

            //billing address
            if (details.Customer.BillingAddressId == null)
            {
                throw new NopException("Billing address is not provided");
            }

            var customerBillingAddress = _customerService.GetCustomerBillingAddress(details.Customer);

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

            details.BillingAddress = _addressService.CloneAddress(customerBillingAddress);
            if (_countryService.GetCountryByAddress(details.BillingAddress) is Country countryBilling && !countryBilling.AllowsBilling)
            {
                throw new NopException($"Country '{countryBilling.Name}' is not allowed for billing");
            }

            //checkout attributes
            details.CheckoutAttributesXml        = _genericAttributeService.GetAttribute <string>(details.Customer, NopCustomerDefaults.CheckoutAttributes, processPaymentRequest.StoreId);
            details.CheckoutAttributeDescription = _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributesXml, details.Customer);

            //load shopping cart
            details.Cart = _shoppingCartService.GetShoppingCart(details.Customer, ShoppingCartType.ShoppingCart, processPaymentRequest.StoreId);

            if (!details.Cart.Any())
            {
                throw new NopException("Cart is empty");
            }

            //validate the entire shopping cart
            var warnings = _shoppingCartService.GetShoppingCartWarnings(details.Cart, details.CheckoutAttributesXml, true);

            if (warnings.Any())
            {
                throw new NopException(warnings.Aggregate(string.Empty, (current, next) => $"{current}{next};"));
            }

            //validate individual cart items
            foreach (var sci in details.Cart)
            {
                var product = _productService.GetProductById(sci.ProductId);

                var sciWarnings = _shoppingCartService.GetShoppingCartItemWarnings(details.Customer,
                                                                                   sci.ShoppingCartType, product, processPaymentRequest.StoreId, sci.AttributesXml,
                                                                                   sci.CustomerEnteredPrice, sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false, sci.Id);
                if (sciWarnings.Any())
                {
                    throw new NopException(sciWarnings.Aggregate(string.Empty, (current, next) => $"{current}{next};"));
                }
            }

            //min totals validation
            if (!ValidateMinOrderSubtotalAmount(details.Cart))
            {
                var minOrderSubtotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderSubtotalAmount, _workContext.WorkingCurrency);
                throw new NopException(string.Format(_localizationService.GetResource("Checkout.MinOrderSubtotalAmount"),
                                                     _priceFormatter.FormatPrice(minOrderSubtotalAmount, true, false)));
            }

            if (!ValidateMinOrderTotalAmount(details.Cart))
            {
                var minOrderTotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderTotalAmount, _workContext.WorkingCurrency);
                throw new NopException(string.Format(_localizationService.GetResource("Checkout.MinOrderTotalAmount"),
                                                     _priceFormatter.FormatPrice(minOrderTotalAmount, true, false)));
            }

            //tax display type
            if (_taxSettings.AllowCustomersToSelectTaxDisplayType)
            {
                details.CustomerTaxDisplayType = (TaxDisplayType)_genericAttributeService.GetAttribute <int>(details.Customer, NopCustomerDefaults.TaxDisplayTypeIdAttribute, processPaymentRequest.StoreId);
            }
            else
            {
                details.CustomerTaxDisplayType = _taxSettings.TaxDisplayType;
            }

            //sub total (incl tax)
            _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, true, out var orderSubTotalDiscountAmount, out var orderSubTotalAppliedDiscounts, out var subTotalWithoutDiscountBase, out var _);
            details.OrderSubTotalInclTax         = subTotalWithoutDiscountBase;
            details.OrderSubTotalDiscountInclTax = orderSubTotalDiscountAmount;

            //discount history
            foreach (var disc in orderSubTotalAppliedDiscounts)
            {
                if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc))
                {
                    details.AppliedDiscounts.Add(disc);
                }
            }

            //sub total (excl tax)
            _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, false, out orderSubTotalDiscountAmount,
                                                                  out orderSubTotalAppliedDiscounts, out subTotalWithoutDiscountBase, out _);
            details.OrderSubTotalExclTax         = subTotalWithoutDiscountBase;
            details.OrderSubTotalDiscountExclTax = orderSubTotalDiscountAmount;

            //shipping info
            if (_shoppingCartService.ShoppingCartRequiresShipping(details.Cart))
            {
                var pickupPoint = _genericAttributeService.GetAttribute <PickupPoint>(details.Customer,
                                                                                      NopCustomerDefaults.SelectedPickupPointAttribute, processPaymentRequest.StoreId);
                if (_shippingSettings.AllowPickupInStore && pickupPoint != null)
                {
                    var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode);
                    var state   = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation, country?.Id);

                    details.PickupInStore = true;
                    details.PickupAddress = new Address
                    {
                        Address1        = pickupPoint.Address,
                        City            = pickupPoint.City,
                        County          = pickupPoint.County,
                        CountryId       = country?.Id,
                        StateProvinceId = state?.Id,
                        ZipPostalCode   = pickupPoint.ZipPostalCode,
                        CreatedOnUtc    = DateTime.UtcNow
                    };
                }
                else
                {
                    if (details.Customer.ShippingAddressId == null)
                    {
                        throw new NopException("Shipping address is not provided");
                    }

                    var customerShippingAddress = _customerService.GetCustomerShippingAddress(details.Customer);

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

                    //clone shipping address
                    details.ShippingAddress = _addressService.CloneAddress(customerShippingAddress);
                    if (_countryService.GetCountryByAddress(details.ShippingAddress) is Country countryShipping && !countryShipping.AllowsShipping)
                    {
                        throw new NopException($"Country '{countryShipping.Name}' is not allowed for shipping");
                    }
                }

                var shippingOption = _genericAttributeService.GetAttribute <ShippingOption>(details.Customer,
                                                                                            NopCustomerDefaults.SelectedShippingOptionAttribute, processPaymentRequest.StoreId);
                if (shippingOption != null)
                {
                    details.ShippingMethodName = shippingOption.Name;
                    details.ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName;
                }

                details.ShippingStatus = ShippingStatus.NotYetShipped;
            }
            else
            {
                details.ShippingStatus = ShippingStatus.ShippingNotRequired;
            }

            //LoadAllShippingRateComputationMethods
            var shippingRateComputationMethods = _shippingPluginManager.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id);

            //shipping total
            var orderShippingTotalInclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true, shippingRateComputationMethods, out var _, out var shippingTotalDiscounts);
            var orderShippingTotalExclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, false, shippingRateComputationMethods);

            if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue)
            {
                throw new NopException("Shipping total couldn't be calculated");
            }

            details.OrderShippingTotalInclTax = orderShippingTotalInclTax.Value;
            details.OrderShippingTotalExclTax = orderShippingTotalExclTax.Value;

            foreach (var disc in shippingTotalDiscounts)
            {
                if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc))
                {
                    details.AppliedDiscounts.Add(disc);
                }
            }

            //payment total
            var paymentAdditionalFee = _paymentService.GetAdditionalHandlingFee(details.Cart, processPaymentRequest.PaymentMethodSystemName);

            details.PaymentAdditionalFeeInclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer);
            details.PaymentAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer);

            //tax amount
            details.OrderTaxTotal = _orderTotalCalculationService.GetTaxTotal(details.Cart, shippingRateComputationMethods, out var taxRatesDictionary);

            //Avalara plugin changes
            //get previously saved tax details received from the Avalara tax service
            var taxDetails = _httpContextAccessor.HttpContext.Session.Get <TaxDetails>(AvalaraTaxDefaults.TaxDetailsSessionValue);

            if (taxDetails != null)
            {
                //adjust tax total according to received value from the Avalara
                if (taxDetails.TaxTotal.HasValue)
                {
                    details.OrderTaxTotal = taxDetails.TaxTotal.Value;
                }

                if (taxDetails.TaxRates?.Any() ?? false)
                {
                    taxRatesDictionary = new SortedDictionary <decimal, decimal>(taxDetails.TaxRates);
                }
            }
            //Avalara plugin changes

            //VAT number
            var customerVatStatus = (VatNumberStatus)_genericAttributeService.GetAttribute <int>(details.Customer, NopCustomerDefaults.VatNumberStatusIdAttribute);

            if (_taxSettings.EuVatEnabled && customerVatStatus == VatNumberStatus.Valid)
            {
                details.VatNumber = _genericAttributeService.GetAttribute <string>(details.Customer, NopCustomerDefaults.VatNumberAttribute);
            }

            //tax rates
            details.TaxRates = taxRatesDictionary.Aggregate(string.Empty, (current, next) =>
                                                            $"{current}{next.Key.ToString(CultureInfo.InvariantCulture)}:{next.Value.ToString(CultureInfo.InvariantCulture)};   ");

            //order total (and applied discounts, gift cards, reward points)
            var orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(details.Cart, out var orderDiscountAmount, out var orderAppliedDiscounts, out var appliedGiftCards, out var redeemedRewardPoints, out var redeemedRewardPointsAmount);

            if (!orderTotal.HasValue)
            {
                throw new NopException("Order total couldn't be calculated");
            }

            details.OrderDiscountAmount        = orderDiscountAmount;
            details.RedeemedRewardPoints       = redeemedRewardPoints;
            details.RedeemedRewardPointsAmount = redeemedRewardPointsAmount;
            details.AppliedGiftCards           = appliedGiftCards;
            details.OrderTotal = orderTotal.Value;

            //discount history
            foreach (var disc in orderAppliedDiscounts)
            {
                if (!_discountService.ContainsDiscount(details.AppliedDiscounts, disc))
                {
                    details.AppliedDiscounts.Add(disc);
                }
            }

            processPaymentRequest.OrderTotal = details.OrderTotal;

            //Avalara plugin changes
            //delete custom value
            _httpContextAccessor.HttpContext.Session.Set <TaxDetails>(AvalaraTaxDefaults.TaxDetailsSessionValue, null);
            //Avalara plugin changes

            //recurring or standard shopping cart?
            details.IsRecurringShoppingCart = _shoppingCartService.ShoppingCartIsRecurring(details.Cart);
            if (!details.IsRecurringShoppingCart)
            {
                return(details);
            }

            var recurringCyclesError = _shoppingCartService.GetRecurringCycleInfo(details.Cart,
                                                                                  out var recurringCycleLength, out var recurringCyclePeriod, out var recurringTotalCycles);

            if (!string.IsNullOrEmpty(recurringCyclesError))
            {
                throw new NopException(recurringCyclesError);
            }

            processPaymentRequest.RecurringCycleLength = recurringCycleLength;
            processPaymentRequest.RecurringCyclePeriod = recurringCyclePeriod;
            processPaymentRequest.RecurringTotalCycles = recurringTotalCycles;

            return(details);
        }
Beispiel #29
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 = false;

            StripeCreditCardOptions cardOptions = new StripeCreditCardOptions()
            {
                Number          = processPaymentRequest.CreditCardNumber,
                ExpirationYear  = processPaymentRequest.CreditCardExpireYear.ToString(),
                ExpirationMonth = processPaymentRequest.CreditCardExpireMonth.ToString(),
                Cvc             = processPaymentRequest.CreditCardCvv2,
                Name            = processPaymentRequest.CustomerId.ToString()
            };
            string token         = CreateToken(cardOptions);
            int    paymentAmount = 0;

            if (_stripePaymentSettings.AdditionalFeePercentage && _stripePaymentSettings.AdditionalFee > 0)
            {
                decimal additionalFee = processPaymentRequest.OrderTotal * (_stripePaymentSettings.AdditionalFee / 100);
                paymentAmount = (int)(processPaymentRequest.OrderTotal * 100) + (int)(additionalFee * 100); //convert to cents/pence
            }
            else if (!_stripePaymentSettings.AdditionalFeePercentage && _stripePaymentSettings.AdditionalFee > 0)
            {
                paymentAmount = (int)(processPaymentRequest.OrderTotal * 100) + (int)(_stripePaymentSettings.AdditionalFee * 100);
            }
            else
            {
                paymentAmount = (int)(processPaymentRequest.OrderTotal * 100);
            }

            StripeChargeCreateOptions chargeOptions = new StripeChargeCreateOptions()
            {
                Amount      = paymentAmount,
                Currency    = "gbp",
                Description = processPaymentRequest.OrderGuid.ToString()
            };

            if (ChargeCard(token, chargeOptions))
            {
                result.NewPaymentStatus = PaymentStatus.Paid;
            }
            else
            {
                result.AddError("Failed");
            }
            //switch (_stripePaymentSettings.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);
        }
Beispiel #30
0
        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);
        }
Beispiel #31
0
        /// <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);

            if (customer == null)
            {
                throw new Exception("Customer cannot be loaded");
            }

            try
            {
                var apiContext = PaypalHelper.GetApiContext(_paypalDirectPaymentSettings);
                var currency   = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);

                //check that webhook exists
                if (string.IsNullOrEmpty(_paypalDirectPaymentSettings.WebhookId))
                {
                    result.AddError("Recurring payments are not available until you create a webhook");
                    return(result);
                }

                Webhook.Get(apiContext, _paypalDirectPaymentSettings.WebhookId);

                //create the plan
                var url         = _storeContext.CurrentStore.SslEnabled ? _storeContext.CurrentStore.SecureUrl : _storeContext.CurrentStore.Url;
                var billingPlan = new Plan
                {
                    name                 = processPaymentRequest.OrderGuid.ToString(),
                    description          = string.Format("nopCommerce billing plan for the {0} order", processPaymentRequest.OrderGuid),
                    type                 = "fixed",
                    merchant_preferences = new MerchantPreferences
                    {
                        return_url       = url,
                        cancel_url       = url,
                        auto_bill_amount = "YES",
                        //setting setup fee as the first payment (workaround for the processing first payment immediately)
                        setup_fee = new PayPal.Api.Currency
                        {
                            currency = currency != null ? currency.CurrencyCode : null,
                            value    = processPaymentRequest.OrderTotal.ToString("N", new CultureInfo("en-US"))
                        }
                    },
                    payment_definitions = new List <PaymentDefinition>
                    {
                        new PaymentDefinition
                        {
                            name = "nopCommerce payment for the billing plan",
                            type = "REGULAR",
                            frequency_interval = processPaymentRequest.RecurringCycleLength.ToString(),
                            frequency          = processPaymentRequest.RecurringCyclePeriod.ToString().TrimEnd('s'),
                            cycles             = (processPaymentRequest.RecurringTotalCycles - 1).ToString(),
                            amount             = new PayPal.Api.Currency
                            {
                                currency = currency != null ? currency.CurrencyCode : null,
                                value    = processPaymentRequest.OrderTotal.ToString("N", new CultureInfo("en-US"))
                            }
                        }
                    }
                }.Create(apiContext);

                //activate the plan
                var patchRequest = new PatchRequest()
                {
                    new Patch()
                    {
                        op    = "replace",
                        path  = "/",
                        value = new Plan
                        {
                            state = "ACTIVE"
                        }
                    }
                };
                billingPlan.Update(apiContext, patchRequest);

                //create subscription
                var subscription = new Agreement
                {
                    name = string.Format("nopCommerce subscription for the {0} order", processPaymentRequest.OrderGuid),
                    //we set order guid in the description, then use it in the webhook handler
                    description = processPaymentRequest.OrderGuid.ToString(),
                    //setting start date as the next date of recurring payments as the setup fee was the first payment
                    start_date = GetStartDate(processPaymentRequest.RecurringCyclePeriod, processPaymentRequest.RecurringCycleLength),

                    #region payer

                    payer = new Payer()
                    {
                        payment_method = "credit_card",

                        #region credit card info

                        funding_instruments = new List <FundingInstrument>
                        {
                            new FundingInstrument
                            {
                                credit_card = new CreditCard
                                {
                                    type         = processPaymentRequest.CreditCardType.ToLowerInvariant(),
                                    number       = processPaymentRequest.CreditCardNumber,
                                    cvv2         = processPaymentRequest.CreditCardCvv2,
                                    expire_month = processPaymentRequest.CreditCardExpireMonth,
                                    expire_year  = processPaymentRequest.CreditCardExpireYear
                                }
                            }
                        },

                        #endregion

                        #region payer info

                        payer_info = new PayerInfo
                        {
                            #region billing address

                            billing_address = customer.BillingAddress == null ? null : new Address
                            {
                                country_code = customer.BillingAddress.Country != null ? customer.BillingAddress.Country.TwoLetterIsoCode : null,
                                state        = customer.BillingAddress.StateProvince != null ? customer.BillingAddress.StateProvince.Abbreviation : null,
                                city         = customer.BillingAddress.City,
                                line1        = customer.BillingAddress.Address1,
                                line2        = customer.BillingAddress.Address2,
                                phone        = customer.BillingAddress.PhoneNumber,
                                postal_code  = customer.BillingAddress.ZipPostalCode
                            },

                            #endregion

                            email      = customer.BillingAddress.Email,
                            first_name = customer.BillingAddress.FirstName,
                            last_name  = customer.BillingAddress.LastName
                        }

                        #endregion
                    },

                    #endregion

                    #region shipping address

                    shipping_address = customer.ShippingAddress == null ? null : new ShippingAddress
                    {
                        country_code = customer.ShippingAddress.Country != null ? customer.ShippingAddress.Country.TwoLetterIsoCode : null,
                        state        = customer.ShippingAddress.StateProvince != null ? customer.ShippingAddress.StateProvince.Abbreviation : null,
                        city         = customer.ShippingAddress.City,
                        line1        = customer.ShippingAddress.Address1,
                        line2        = customer.ShippingAddress.Address2,
                        phone        = customer.ShippingAddress.PhoneNumber,
                        postal_code  = customer.ShippingAddress.ZipPostalCode
                    },

                    #endregion

                    plan = new Plan
                    {
                        id = billingPlan.id
                    }
                }.Create(apiContext);

                //if first payment failed, try again
                if (string.IsNullOrEmpty(subscription.agreement_details.last_payment_date))
                {
                    subscription.BillBalance(apiContext, new AgreementStateDescriptor {
                        amount = subscription.agreement_details.outstanding_balance
                    });
                }

                result.SubscriptionTransactionId = subscription.id;
            }
            catch (PayPal.PayPalException exc)
            {
                if (exc is PayPal.ConnectionException)
                {
                    var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response);
                    if (error != null)
                    {
                        result.AddError(string.Format("PayPal error: {0} ({1})", error.message, error.name));
                        if (error.details != null)
                        {
                            error.details.ForEach(x => result.AddError(string.Format("{0} {1}", x.field, x.issue)));
                        }
                    }
                }

                //if there are not the specific errors add exception message
                if (result.Success)
                {
                    result.AddError(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                }
            }

            return(result);
        }
Beispiel #32
0
        /// <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);
        }
 public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest) => new ProcessPaymentResult();
        /// <summary>
        /// Places an order
        /// </summary>
        /// <param name="processPaymentRequest">Process payment request</param>
        /// <returns>Place order result</returns>
        public override PlaceOrderResult PlaceOrder(ProcessPaymentRequest processPaymentRequest)
        {
            //think about moving functionality of processing recurring orders (after the initial order was placed) to ProcessNextRecurringPayment() method
            if (processPaymentRequest == null)
                throw new ArgumentNullException("processPaymentRequest");

            var result = new PlaceOrderResult();
            try
            {
                if (processPaymentRequest.OrderGuid == Guid.Empty)
                    processPaymentRequest.OrderGuid = Guid.NewGuid();

                //prepare order details
                var details = PreparePlaceOrderDetails(processPaymentRequest);

                #region Payment workflow


                //process payment
                ProcessPaymentResult processPaymentResult = null;
                //skip payment workflow if order total equals zero
                var skipPaymentWorkflow = details.OrderTotal == decimal.Zero;
                if (!skipPaymentWorkflow)
                {
                    var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(processPaymentRequest.PaymentMethodSystemName);
                    if (paymentMethod == null)
                        throw new NopException("Payment method couldn't be loaded");

                    //ensure that payment method is active
                    if (!paymentMethod.IsPaymentMethodActive(_paymentSettings))
                        throw new NopException("Payment method is not active");

                    if (!processPaymentRequest.IsRecurringPayment)
                    {
                        if (details.IsRecurringShoppingCart)
                        {
                            //recurring cart
                            var recurringPaymentType = _paymentService.GetRecurringPaymentType(processPaymentRequest.PaymentMethodSystemName);
                            switch (recurringPaymentType)
                            {
                                case RecurringPaymentType.NotSupported:
                                    throw new NopException("Recurring payments are not supported by selected payment method");
                                case RecurringPaymentType.Manual:
                                case RecurringPaymentType.Automatic:
                                    processPaymentResult = _paymentService.ProcessRecurringPayment(processPaymentRequest);
                                    break;
                                default:
                                    throw new NopException("Not supported recurring payment type");
                            }
                        }
                        else
                        {
                            //standard cart
                            processPaymentResult = _paymentService.ProcessPayment(processPaymentRequest);
                        }
                    }
                    else
                    {
                        if (details.IsRecurringShoppingCart)
                        {
                            //Old credit card info
                            processPaymentRequest.CreditCardType = details.InitialOrder.AllowStoringCreditCardNumber ? _encryptionService.DecryptText(details.InitialOrder.CardType) : "";
                            processPaymentRequest.CreditCardName = details.InitialOrder.AllowStoringCreditCardNumber ? _encryptionService.DecryptText(details.InitialOrder.CardName) : "";
                            processPaymentRequest.CreditCardNumber = details.InitialOrder.AllowStoringCreditCardNumber ? _encryptionService.DecryptText(details.InitialOrder.CardNumber) : "";
                            processPaymentRequest.CreditCardCvv2 = details.InitialOrder.AllowStoringCreditCardNumber ? _encryptionService.DecryptText(details.InitialOrder.CardCvv2) : "";
                            try
                            {
                                processPaymentRequest.CreditCardExpireMonth = details.InitialOrder.AllowStoringCreditCardNumber ? Convert.ToInt32(_encryptionService.DecryptText(details.InitialOrder.CardExpirationMonth)) : 0;
                                processPaymentRequest.CreditCardExpireYear = details.InitialOrder.AllowStoringCreditCardNumber ? Convert.ToInt32(_encryptionService.DecryptText(details.InitialOrder.CardExpirationYear)) : 0;
                            }
                            catch { }

                            var recurringPaymentType = _paymentService.GetRecurringPaymentType(processPaymentRequest.PaymentMethodSystemName);
                            switch (recurringPaymentType)
                            {
                                case RecurringPaymentType.NotSupported:
                                    throw new NopException("Recurring payments are not supported by selected payment method");
                                case RecurringPaymentType.Manual:
                                    processPaymentResult = _paymentService.ProcessRecurringPayment(processPaymentRequest);
                                    break;
                                case RecurringPaymentType.Automatic:
                                    //payment is processed on payment gateway site
                                    processPaymentResult = new ProcessPaymentResult();
                                    break;
                                default:
                                    throw new NopException("Not supported recurring payment type");
                            }
                        }
                        else
                        {
                            throw new NopException("No recurring products");
                        }
                    }
                }
                else
                {
                    //payment is not required
                    if (processPaymentResult == null)
                        processPaymentResult = new ProcessPaymentResult();
                    processPaymentResult.NewPaymentStatus = PaymentStatus.Paid;
                }

                if (processPaymentResult == null)
                    throw new NopException("processPaymentResult is not available");

                #endregion

                if (processPaymentResult.Success)
                {
                    #region Save order details

                    var order = new Order
                    {
                        StoreId = processPaymentRequest.StoreId,
                        OrderGuid = processPaymentRequest.OrderGuid,
                        CustomerId = details.Customer.Id,
                        CustomerLanguageId = details.CustomerLanguage.Id,
                        CustomerTaxDisplayType = details.CustomerTaxDisplayType,
                        CustomerIp = _webHelper.GetCurrentIpAddress(),
                        OrderSubtotalInclTax = details.OrderSubTotalInclTax,
                        OrderSubtotalExclTax = details.OrderSubTotalExclTax,
                        OrderSubTotalDiscountInclTax = details.OrderSubTotalDiscountInclTax,
                        OrderSubTotalDiscountExclTax = details.OrderSubTotalDiscountExclTax,
                        OrderShippingInclTax = details.OrderShippingTotalInclTax,
                        OrderShippingExclTax = details.OrderShippingTotalExclTax,
                        PaymentMethodAdditionalFeeInclTax = details.PaymentAdditionalFeeInclTax,
                        PaymentMethodAdditionalFeeExclTax = details.PaymentAdditionalFeeExclTax,
                        TaxRates = details.TaxRates,
                        OrderTax = details.OrderTaxTotal,
                        OrderTotal = details.OrderTotal,
                        RefundedAmount = decimal.Zero,
                        OrderDiscount = details.OrderDiscountAmount,
                        CheckoutAttributeDescription = details.CheckoutAttributeDescription,
                        CheckoutAttributesXml = details.CheckoutAttributesXml,
                        CustomerCurrencyCode = details.CustomerCurrencyCode,
                        CurrencyRate = details.CustomerCurrencyRate,
                        AffiliateId = details.AffiliateId,
                        OrderStatus = OrderStatus.Pending,
                        AllowStoringCreditCardNumber = processPaymentResult.AllowStoringCreditCardNumber,
                        CardType = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardType) : string.Empty,
                        CardName = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardName) : string.Empty,
                        CardNumber = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardNumber) : string.Empty,
                        MaskedCreditCardNumber = _encryptionService.EncryptText(_paymentService.GetMaskedCreditCardNumber(processPaymentRequest.CreditCardNumber)),
                        CardCvv2 = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardCvv2) : string.Empty,
                        CardExpirationMonth = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardExpireMonth.ToString()) : string.Empty,
                        CardExpirationYear = processPaymentResult.AllowStoringCreditCardNumber ? _encryptionService.EncryptText(processPaymentRequest.CreditCardExpireYear.ToString()) : string.Empty,
                        PaymentMethodSystemName = processPaymentRequest.PaymentMethodSystemName,
                        AuthorizationTransactionId = processPaymentResult.AuthorizationTransactionId,
                        AuthorizationTransactionCode = processPaymentResult.AuthorizationTransactionCode,
                        AuthorizationTransactionResult = processPaymentResult.AuthorizationTransactionResult,
                        CaptureTransactionId = processPaymentResult.CaptureTransactionId,
                        CaptureTransactionResult = processPaymentResult.CaptureTransactionResult,
                        SubscriptionTransactionId = processPaymentResult.SubscriptionTransactionId,
                        PaymentStatus = processPaymentResult.NewPaymentStatus,
                        PaidDateUtc = null,
                        BillingAddress = details.BillingAddress,
                        ShippingAddress = details.ShippingAddress,
                        ShippingStatus = details.ShippingStatus,
                        ShippingMethod = details.ShippingMethodName,
                        PickUpInStore = details.PickUpInStore,
                        ShippingRateComputationMethodSystemName = details.ShippingRateComputationMethodSystemName,
                        CustomValuesXml = processPaymentRequest.SerializeCustomValues(),
                        VatNumber = details.VatNumber,
                        CreatedOnUtc = DateTime.UtcNow
                    };
                    _orderService.InsertOrder(order);

                    #region Promo

                    _promoService.SendConfirmedBasket(order);

                    BasketResponse basketResponse = _promoUtilities.GetBasketResponse();

                    if (basketResponse == null)
                    {
                        throw new NopException(string.Format("Failed to create PromoOrder for order: {0}", order.Id));
                    }
                    else
                    {

                        PromoOrder promoOrder = new PromoOrder()
                        {
                            RequestXml = _workContext.CurrentCustomer.GetAttribute<string>(PromoCustomerAttributeNames.PromoBasketRequest, _genericAttributeService, _storeContext.CurrentStore.Id),
                            ResponseXml = basketResponse.ToXml(),
                            OrderId = order.Id,
                            DeliveryOriginalPrice = basketResponse.DeliveryOriginalPrice
                        };

                        _promoOrderService.InsertPromoOrder(promoOrder);

                        basketResponse.Items.ForEach(bi =>
                        {
                            PromoOrderItem promoOrderItem = new PromoOrderItem()
                            {
                                LineAmount = bi.LineAmount,
                                OrderId = order.Id,
                                PromoOrderId = promoOrder.Id,
                                IsDelivery = bi.IsDelivery,
                                ProductCode = bi.ProductCode,
                                VariantCode = bi.VariantCode,
                                LinePromotionDiscount = bi.LinePromotionDiscount,
                                Barcode = bi.Barcode,
                                Generated = bi.Generated,
                                ManualDiscount = bi.ManualDiscount,
                                OriginalAmount = bi.OriginalAmount,
                                OriginalPrice = bi.OriginalPrice,
                                OriginalQuantity = bi.OriginalQuantity,
                                Price = bi.Price,
                                ProductDescription = bi.ProductDescription,
                                Quantity = bi.Quantity,
                                SplitFromLineId = bi.SplitFromLineId,
                                TotalDiscount = bi.TotalDiscount,
                                TotalIssuedPoints = bi.TotalIssuedPoints
                            };

                            promoOrder.PromoOrderItems.Add(promoOrderItem);
                            _promoOrderService.UpdatePromoOrder(promoOrder);

                            bi.AppliedPromotions.ForEach(ap =>
                            {
                                string promotionTypeDisplay = string.Empty;
                                string promotionType = string.Empty;
                                string promotionName = string.Empty;
                                string promotionDisplayText = string.Empty;
                                var appliedPromo = (from sap in basketResponse.Summary.AppliedPromotions where sap.PromotionId == ap.PromotionId select sap).FirstOrDefault();
                                if (appliedPromo != null)
                                {
                                    promotionName = appliedPromo.PromotionName;
                                    promotionType = appliedPromo.PromotionType;
                                    promotionTypeDisplay = appliedPromo.PromotionTypeDisplay;
                                    promotionDisplayText = appliedPromo.DisplayText;
                                }

                                PromoOrderItemPromotion promoOrderItemPromotion = new PromoOrderItemPromotion()
                                {
                                    BasketLevel = ap.BasketLevelPromotion,
                                    DeliveryLevel = ap.DeliveryLevelPromotion,
                                    DiscountAmount = ap.DiscountAmount,
                                    ForLineId = ap.AssociatedLine,
                                    Instance = ap.InstanceId,
                                    PointsIssued = ap.PointsIssued,
                                    PromotionId = ap.PromotionId,
                                    DisplayText = promotionDisplayText,
                                    PromotionTypeDisplay = promotionTypeDisplay,
                                    PromotionName = promotionName,
                                    PromotionType = promotionType,
                                    ExternalIdentifier = ap.ExternalIdentifier,
                                    ReportingGroupCode = ap.ReportingGroupCode
                                };
                                promoOrderItem.PromoOrderItemPromotions.Add(promoOrderItemPromotion);
                                _promoOrderService.UpdatePromoOrder(promoOrder);
                            });
                        });

                        basketResponse.Coupons.ForEach(c =>
                            {
                                PromoOrderCoupon promoOrderCoupon = new PromoOrderCoupon()
                                {
                                    CouponCode = c.CouponCode,
                                    Issued = c.Issued,
                                    OrderId = order.Id,
                                    PromoOrderId = promoOrder.Id,
                                    CouponName = c.CouponName,
                                    IssuedConfirmed = c.IssuedConfirmed,
                                    DisplayText = c.DisplayText
                                };
                                promoOrder.PromoOrderCoupons.Add(promoOrderCoupon);
                                _promoOrderService.UpdatePromoOrder(promoOrder);
                            });
                    }

                    #region clean up

                    Customer customer = _workContext.CurrentCustomer;

                    // basket guid
                    _genericAttributeService.SaveAttribute<string>(customer, PromoCustomerAttributeNames.PromoBasketUniqueReference, null, _storeContext.CurrentStore.Id);

                    // basket response
                    _genericAttributeService.SaveAttribute<string>(customer, PromoCustomerAttributeNames.PromoBasketResponse, null, _storeContext.CurrentStore.Id);

                    // basket request
                    _genericAttributeService.SaveAttribute<string>(customer, PromoCustomerAttributeNames.PromoBasketRequest, null, _storeContext.CurrentStore.Id);

                    // coupon code
                    _genericAttributeService.SaveAttribute<string>(customer, SystemCustomerAttributeNames.DiscountCouponCode, null);

                    #endregion

                    #endregion

                    result.PlacedOrder = order;

                    if (!processPaymentRequest.IsRecurringPayment)
                    {
                        //move shopping cart items to order items
                        foreach (var sc in details.Cart)
                        {
                            var basketResponseItems = basketResponse.FindBasketResponseItems(sc);

                            if (basketResponseItems == null)
                            {
                                // TODO: handle this error
                            }
                            else
                            {
                                //prices
                                decimal taxRate;
                                decimal discountAmount = basketResponseItems.Sum(i => i.LinePromotionDiscount);
                                decimal scUnitPrice = _priceCalculationService.GetUnitPrice(sc);
                                decimal scSubTotal = basketResponseItems.Sum(i => i.LineAmount);
                                decimal scUnitPriceInclTax = _taxService.GetProductPrice(sc.Product, scUnitPrice, true, details.Customer, out taxRate);
                                decimal scUnitPriceExclTax = _taxService.GetProductPrice(sc.Product, scUnitPrice, false, details.Customer, out taxRate);
                                decimal scSubTotalInclTax = _taxService.GetProductPrice(sc.Product, scSubTotal, true, details.Customer, out taxRate);
                                decimal scSubTotalExclTax = _taxService.GetProductPrice(sc.Product, scSubTotal, false, details.Customer, out taxRate);

                                decimal discountAmountInclTax = _taxService.GetProductPrice(sc.Product, discountAmount, true, details.Customer, out taxRate);
                                decimal discountAmountExclTax = _taxService.GetProductPrice(sc.Product, discountAmount, false, details.Customer, out taxRate);

                                //attributes
                                string attributeDescription = _productAttributeFormatter.FormatAttributes(sc.Product, sc.AttributesXml, details.Customer);

                                var itemWeight = _shippingService.GetShoppingCartItemWeight(sc);

                                //save order item
                                var orderItem = new OrderItem
                                {
                                    OrderItemGuid = Guid.NewGuid(),
                                    Order = order,
                                    ProductId = sc.ProductId,
                                    UnitPriceInclTax = scUnitPriceInclTax,
                                    UnitPriceExclTax = scUnitPriceExclTax,
                                    PriceInclTax = scSubTotalInclTax,
                                    PriceExclTax = scSubTotalExclTax,
                                    OriginalProductCost = _priceCalculationService.GetProductCost(sc.Product, sc.AttributesXml),
                                    AttributeDescription = attributeDescription,
                                    AttributesXml = sc.AttributesXml,
                                    Quantity = sc.Quantity,
                                    DiscountAmountInclTax = discountAmountInclTax,
                                    DiscountAmountExclTax = discountAmountExclTax,
                                    DownloadCount = 0,
                                    IsDownloadActivated = false,
                                    LicenseDownloadId = 0,
                                    ItemWeight = itemWeight,
                                    RentalStartDateUtc = sc.RentalStartDateUtc,
                                    RentalEndDateUtc = sc.RentalEndDateUtc
                                };
                                order.OrderItems.Add(orderItem);
                                _orderService.UpdateOrder(order);

                                //gift cards
                                if (sc.Product.IsGiftCard)
                                {
                                    string giftCardRecipientName, giftCardRecipientEmail,
                                        giftCardSenderName, giftCardSenderEmail, giftCardMessage;
                                    _productAttributeParser.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
                                        {
                                            GiftCardType = sc.Product.GiftCardType,
                                            PurchasedWithOrderItem = orderItem,
                                            Amount = scUnitPriceExclTax,
                                            IsGiftCardActivated = false,
                                            GiftCardCouponCode = _giftCardService.GenerateGiftCardCode(),
                                            RecipientName = giftCardRecipientName,
                                            RecipientEmail = giftCardRecipientEmail,
                                            SenderName = giftCardSenderName,
                                            SenderEmail = giftCardSenderEmail,
                                            Message = giftCardMessage,
                                            IsRecipientNotified = false,
                                            CreatedOnUtc = DateTime.UtcNow
                                        };
                                        _giftCardService.InsertGiftCard(gc);
                                    }
                                }

                                //inventory
                                _productService.AdjustInventory(sc.Product, -sc.Quantity, sc.AttributesXml);
                            }
                        }

                        //clear shopping cart
                        details.Cart.ToList().ForEach(sci => _shoppingCartService.DeleteShoppingCartItem(sci, false));
                    }
                    else
                    {
                        //recurring payment
                        var initialOrderItems = details.InitialOrder.OrderItems;
                        foreach (var orderItem in initialOrderItems)
                        {
                            //save item
                            var newOrderItem = new OrderItem
                            {
                                OrderItemGuid = Guid.NewGuid(),
                                Order = order,
                                ProductId = orderItem.ProductId,
                                UnitPriceInclTax = orderItem.UnitPriceInclTax,
                                UnitPriceExclTax = orderItem.UnitPriceExclTax,
                                PriceInclTax = orderItem.PriceInclTax,
                                PriceExclTax = orderItem.PriceExclTax,
                                OriginalProductCost = orderItem.OriginalProductCost,
                                AttributeDescription = orderItem.AttributeDescription,
                                AttributesXml = orderItem.AttributesXml,
                                Quantity = orderItem.Quantity,
                                DiscountAmountInclTax = orderItem.DiscountAmountInclTax,
                                DiscountAmountExclTax = orderItem.DiscountAmountExclTax,
                                DownloadCount = 0,
                                IsDownloadActivated = false,
                                LicenseDownloadId = 0,
                                ItemWeight = orderItem.ItemWeight,
                                RentalStartDateUtc = orderItem.RentalStartDateUtc,
                                RentalEndDateUtc = orderItem.RentalEndDateUtc
                            };
                            order.OrderItems.Add(newOrderItem);
                            _orderService.UpdateOrder(order);

                            //gift cards
                            if (orderItem.Product.IsGiftCard)
                            {
                                string giftCardRecipientName, giftCardRecipientEmail,
                                    giftCardSenderName, giftCardSenderEmail, giftCardMessage;
                                _productAttributeParser.GetGiftCardAttribute(orderItem.AttributesXml,
                                    out giftCardRecipientName, out giftCardRecipientEmail,
                                    out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                                for (int i = 0; i < orderItem.Quantity; i++)
                                {
                                    var gc = new GiftCard
                                    {
                                        GiftCardType = orderItem.Product.GiftCardType,
                                        PurchasedWithOrderItem = newOrderItem,
                                        Amount = orderItem.UnitPriceExclTax,
                                        IsGiftCardActivated = false,
                                        GiftCardCouponCode = _giftCardService.GenerateGiftCardCode(),
                                        RecipientName = giftCardRecipientName,
                                        RecipientEmail = giftCardRecipientEmail,
                                        SenderName = giftCardSenderName,
                                        SenderEmail = giftCardSenderEmail,
                                        Message = giftCardMessage,
                                        IsRecipientNotified = false,
                                        CreatedOnUtc = DateTime.UtcNow
                                    };
                                    _giftCardService.InsertGiftCard(gc);
                                }
                            }

                            //inventory
                            _productService.AdjustInventory(orderItem.Product, -orderItem.Quantity, orderItem.AttributesXml);
                        }
                    }

                    //discount usage history
                    // TODO: replace with Promo discount usage history?

                    //gift card usage history
                    if (!processPaymentRequest.IsRecurringPayment)
                        if (details.AppliedGiftCards != null)
                            foreach (var agc in details.AppliedGiftCards)
                            {
                                decimal amountUsed = agc.AmountCanBeUsed;
                                var gcuh = new GiftCardUsageHistory
                                {
                                    GiftCard = agc.GiftCard,
                                    UsedWithOrder = order,
                                    UsedValue = amountUsed,
                                    CreatedOnUtc = DateTime.UtcNow
                                };
                                agc.GiftCard.GiftCardUsageHistory.Add(gcuh);
                                _giftCardService.UpdateGiftCard(agc.GiftCard);
                            }

                    //reward points history
                    if (details.RedeemedRewardPointsAmount > decimal.Zero)
                    {
                        details.Customer.AddRewardPointsHistoryEntry(-details.RedeemedRewardPoints,
                            string.Format(_localizationService.GetResource("RewardPoints.Message.RedeemedForOrder", order.CustomerLanguageId), order.Id),
                            order,
                            details.RedeemedRewardPointsAmount);
                        _customerService.UpdateCustomer(details.Customer);
                    }

                    //recurring orders
                    if (!processPaymentRequest.IsRecurringPayment && details.IsRecurringShoppingCart)
                    {
                        //create recurring payment (the first payment)
                        var rp = new RecurringPayment
                        {
                            CycleLength = processPaymentRequest.RecurringCycleLength,
                            CyclePeriod = processPaymentRequest.RecurringCyclePeriod,
                            TotalCycles = processPaymentRequest.RecurringTotalCycles,
                            StartDateUtc = DateTime.UtcNow,
                            IsActive = true,
                            CreatedOnUtc = DateTime.UtcNow,
                            InitialOrder = order,
                        };
                        _orderService.InsertRecurringPayment(rp);


                        var recurringPaymentType = _paymentService.GetRecurringPaymentType(processPaymentRequest.PaymentMethodSystemName);
                        switch (recurringPaymentType)
                        {
                            case RecurringPaymentType.NotSupported:
                                {
                                    //not supported
                                }
                                break;
                            case RecurringPaymentType.Manual:
                                {
                                    //first payment
                                    var rph = new RecurringPaymentHistory
                                    {
                                        RecurringPayment = rp,
                                        CreatedOnUtc = DateTime.UtcNow,
                                        OrderId = order.Id,
                                    };
                                    rp.RecurringPaymentHistory.Add(rph);
                                    _orderService.UpdateRecurringPayment(rp);
                                }
                                break;
                            case RecurringPaymentType.Automatic:
                                {
                                    //will be created later (process is automated)
                                }
                                break;
                            default:
                                break;
                        }
                    }

                    #endregion

                    #region Notifications & notes

                    //notes, messages
                    if (_workContext.OriginalCustomerIfImpersonated != null)
                    {
                        //this order is placed by a store administrator impersonating a customer
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = string.Format("Order placed by a store owner ('{0}'. ID = {1}) impersonating the customer.",
                                _workContext.OriginalCustomerIfImpersonated.Email, _workContext.OriginalCustomerIfImpersonated.Id),
                            DisplayToCustomer = false,
                            CreatedOnUtc = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                    }
                    else
                    {
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = "Order placed",
                            DisplayToCustomer = false,
                            CreatedOnUtc = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                    }

                    //send email notifications
                    int orderPlacedStoreOwnerNotificationQueuedEmailId = _workflowMessageService.SendOrderPlacedStoreOwnerNotification(order, _localizationSettings.DefaultAdminLanguageId);
                    if (orderPlacedStoreOwnerNotificationQueuedEmailId > 0)
                    {
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = string.Format("\"Order placed\" email (to store owner) has been queued. Queued email identifier: {0}.", orderPlacedStoreOwnerNotificationQueuedEmailId),
                            DisplayToCustomer = false,
                            CreatedOnUtc = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                    }

                    var orderPlacedAttachmentFilePath = _orderSettings.AttachPdfInvoiceToOrderPlacedEmail ?
                        _pdfService.PrintOrderToPdf(order, order.CustomerLanguageId) : null;
                    var orderPlacedAttachmentFileName = _orderSettings.AttachPdfInvoiceToOrderPlacedEmail ?
                        "order.pdf" : null;
                    int orderPlacedCustomerNotificationQueuedEmailId = _workflowMessageService
                        .SendOrderPlacedCustomerNotification(order, order.CustomerLanguageId, orderPlacedAttachmentFilePath, orderPlacedAttachmentFileName);
                    if (orderPlacedCustomerNotificationQueuedEmailId > 0)
                    {
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = string.Format("\"Order placed\" email (to customer) has been queued. Queued email identifier: {0}.", orderPlacedCustomerNotificationQueuedEmailId),
                            DisplayToCustomer = false,
                            CreatedOnUtc = DateTime.UtcNow
                        });
                        _orderService.UpdateOrder(order);
                    }

                    var vendors = GetVendorsInOrder(order);
                    foreach (var vendor in vendors)
                    {
                        int orderPlacedVendorNotificationQueuedEmailId = _workflowMessageService.SendOrderPlacedVendorNotification(order, vendor, order.CustomerLanguageId);
                        if (orderPlacedVendorNotificationQueuedEmailId > 0)
                        {
                            order.OrderNotes.Add(new OrderNote
                            {
                                Note = string.Format("\"Order placed\" email (to vendor) has been queued. Queued email identifier: {0}.", orderPlacedVendorNotificationQueuedEmailId),
                                DisplayToCustomer = false,
                                CreatedOnUtc = DateTime.UtcNow
                            });
                            _orderService.UpdateOrder(order);
                        }
                    }

                    //check order status
                    CheckOrderStatus(order);

                    //reset checkout data
                    if (!processPaymentRequest.IsRecurringPayment)
                        _customerService.ResetCheckoutData(details.Customer, processPaymentRequest.StoreId, clearCouponCodes: true, clearCheckoutAttributes: true);

                    if (!processPaymentRequest.IsRecurringPayment)
                    {
                        _customerActivityService.InsertActivity(
                            "PublicStore.PlaceOrder",
                            _localizationService.GetResource("ActivityLog.PublicStore.PlaceOrder"),
                            order.Id);
                    }

                    //raise event       
                    _eventPublisher.Publish(new OrderPlacedEvent(order));

                    if (order.PaymentStatus == PaymentStatus.Paid)
                    {
                        ProcessOrderPaid(order);
                    }
                    #endregion
                }
                else
                {
                    foreach (var paymentError in processPaymentResult.Errors)
                        result.AddError(string.Format(_localizationService.GetResource("Checkout.PaymentError"), paymentError));
                }
            }
            catch (Exception exc)
            {
                _logger.Error(exc.Message, exc);
                result.AddError(exc.Message);
            }

            #region Process errors

            string error = "";
            for (int i = 0; i < result.Errors.Count; i++)
            {
                error += string.Format("Error {0}: {1}", i + 1, result.Errors[i]);
                if (i != result.Errors.Count - 1)
                    error += ". ";
            }
            if (!String.IsNullOrEmpty(error))
            {
                //log it
                string logError = string.Format("Error while placing order. {0}", error);
                _logger.Error(logError);
            }

            #endregion

            return result;
        }
        private PayPalRest.Payment CreatePayPalPayment(ProcessPaymentRequest request, PayPalConfig settings)
        {
            var config = new Dictionary<string, string>();
            config.Add("mode", settings.SandboxMode ? "sandbox" : "live");

            var credentials = new OAuthTokenCredential(settings.ClientId, settings.ClientSecret, config);
            var accessToken = credentials.GetAccessToken();
            var payment = new PayPalRest.Payment
            {
                intent = "sale",
                payer = new Payer
                {
                    payment_method = "credit_card",
                    funding_instruments = new List<PayPalRest.FundingInstrument>
                    {
                        new PayPalRest.FundingInstrument
                        {
                            credit_card = CreateCreditCard(request)
                        }
                    }
                },
                transactions = new List<Transaction> { CreateTransaction(request) }
            };

            return payment.Create(new APIContext(accessToken)
            {
                Config = config
            });
        }
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            try
            {
                var options     = IyzicoHelper.GetIyzicoOptions(_iyzicoPaymentSettings);
                var paymentCard = new PaymentCard()
                {
                    CardHolderName = processPaymentRequest.CreditCardName,
                    CardNumber     = processPaymentRequest.CreditCardNumber,
                    ExpireMonth    = processPaymentRequest.CreditCardExpireMonth.ToString(),
                    ExpireYear     = processPaymentRequest.CreditCardExpireYear.ToString(),
                    Cvc            = processPaymentRequest.CreditCardCvv2
                };

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

                var billingAddress = _addressService.GetAddressById(_customerService.GetCustomerById(processPaymentRequest.CustomerId).BillingAddressId ?? 0);
                if (billingAddress == null)
                {
                    throw new NopException("Customer billing address not set");
                }

                var shippingAddress = _addressService.GetAddressById(_customerService.GetCustomerById(processPaymentRequest.CustomerId).ShippingAddressId ?? 0);

                var billingAddressModel  = _iyzicoService.PrepareAddress(billingAddress);
                var shippingAddressModel = shippingAddress != null?_iyzicoService.PrepareAddress(shippingAddress) : billingAddressModel;

                var installment = GetInstallment(processPaymentRequest, paymentCard, options);

                var shoppingCart      = _shoppingCartService.GetShoppingCart(customer, ShoppingCartType.ShoppingCart);
                var shoppingCartTotal = _orderTotalCalculationService.GetShoppingCartTotal(shoppingCart, out var orderDiscountAmount, out var orderAppliedDiscounts, out var appliedGiftCards, out var redeemedRewardPoints, out var redeemedRewardPointsAmount, usePaymentMethodAdditionalFee: false);

                var paymentRequest = new CreatePaymentRequest
                {
                    Price           = _priceCalculationService.RoundPrice(shoppingCartTotal ?? 0).ToString("f8", CultureInfo.InvariantCulture),
                    PaidPrice       = installment.TotalPrice,
                    Currency        = Currency.TRY.ToString(),
                    Installment     = installment.InstallmentNumber,
                    BasketId        = processPaymentRequest.OrderGuid.ToString(),
                    PaymentCard     = paymentCard,
                    Buyer           = _iyzicoService.PrepareBuyer(processPaymentRequest.CustomerId),
                    ShippingAddress = shippingAddressModel,
                    BillingAddress  = billingAddressModel,
                    BasketItems     = GetItems(customer, processPaymentRequest.StoreId),
                    PaymentGroup    = PaymentGroup.PRODUCT.ToString()
                };

                var payment = Payment.Create(paymentRequest, options);
                if (payment.Status != "success")
                {
                    string errorMessage = _localizationService.GetResource(String.Format("Plugins.Payments.Iyzico.ErrorMessage.{0}", payment.ErrorCode)) ?? payment.ErrorMessage;
                    result.AddError(errorMessage);
                    return(result);
                }

                result.NewPaymentStatus = PaymentStatus.Pending;

                return(result);
            }
            catch (Exception ex)
            {
                result.AddError(ex.Message);
                return(result);
            }
        }
 public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
 {
     throw new NotImplementedException();
 }
        [Consumes("application/json", new[] { "application/json-patch+json" })] // It's a trick that allows ASP.NET infrastructure to select this action with body and ProcessOrderPaymentsWithoutBankCardInfo if no body
        public async Task <ActionResult <ProcessPaymentRequestResult> > ProcessOrderPayments([FromRoute] string orderId, [FromRoute] string paymentId, [FromBody] BankCardInfo bankCardInfo)
        {
            var order = await _customerOrderService.GetByIdAsync(orderId, CustomerOrderResponseGroup.Full.ToString());

            if (order == null)
            {
                var searchCriteria = AbstractTypeFactory <CustomerOrderSearchCriteria> .TryCreateInstance();

                searchCriteria.Number        = orderId;
                searchCriteria.ResponseGroup = CustomerOrderResponseGroup.Full.ToString();

                var orders = await _searchService.SearchCustomerOrdersAsync(searchCriteria);

                order = orders.Results.FirstOrDefault();
            }

            if (order == null)
            {
                throw new InvalidOperationException($"Cannot find order with ID {orderId}");
            }

            var authorizationResult = await _authorizationService.AuthorizeAsync(User, order, new OrderAuthorizationRequirement(ModuleConstants.Security.Permissions.Update));

            if (!authorizationResult.Succeeded)
            {
                return(Unauthorized());
            }

            var inPayment = order.InPayments.FirstOrDefault(x => x.Id == paymentId);

            if (inPayment == null)
            {
                throw new InvalidOperationException($"Cannot find payment with ID {paymentId}");
            }
            if (inPayment.PaymentMethod == null)
            {
                throw new InvalidOperationException($"Cannot find payment method with code {inPayment.GatewayCode}");
            }

            var store = await _storeService.GetByIdAsync(order.StoreId, StoreResponseGroup.StoreInfo.ToString());

            if (store == null)
            {
                throw new InvalidOperationException($"Cannot find store with ID {order.StoreId}");
            }

            var request = new ProcessPaymentRequest
            {
                OrderId      = order.Id,
                Order        = order,
                PaymentId    = inPayment.Id,
                Payment      = inPayment,
                StoreId      = order.StoreId,
                Store        = store,
                BankCardInfo = bankCardInfo
            };
            var result = inPayment.PaymentMethod.ProcessPayment(request);

            if (result.OuterId != null)
            {
                inPayment.OuterId = result.OuterId;
            }

            await _customerOrderService.SaveChangesAsync(new[] { order });

            return(Ok(result));
        }
        private string GetCallbackUrl(string action, ProcessPaymentRequest request)
        {
            var commerceName = _commerceInstanceContext.CurrentInstance.Name;
            var url = Strings.AreaName + "/Buckaroo/" + action + "?commerceName=" + commerceName;
            if (action.StartsWith("return", StringComparison.OrdinalIgnoreCase))
            {
                url += "&commerceReturnUrl=" + HttpUtility.UrlEncode(request.ReturnUrl);
            }

            return url.ToFullUrl(HttpContextAccessor());
        }
        /// <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 processPaymentResult = new ProcessPaymentResult();

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

            //get settings
            var useSandbox = _braintreePaymentSettings.UseSandbox;
            var merchantId = _braintreePaymentSettings.MerchantId;
            var publicKey  = _braintreePaymentSettings.PublicKey;
            var privateKey = _braintreePaymentSettings.PrivateKey;

            //new gateway
            var gateway = new BraintreeGateway
            {
                Environment = useSandbox ? Environment.SANDBOX : Environment.PRODUCTION,
                MerchantId  = merchantId,
                PublicKey   = publicKey,
                PrivateKey  = privateKey
            };

            var billingAddress = _addressService.GetAddressById(customer.BillingAddressId ?? 0);

            //search to see if customer is already in the vault
            var searchRequest = new CustomerSearchRequest().Email.Is(billingAddress?.Email);
            var vaultCustomer = gateway.Customer.Search(searchRequest);

            var customerId = vaultCustomer.FirstOrDefault()?.Id ?? string.Empty;

            var currencyMerchantId = string.Empty;
            var amount             = processPaymentRequest.OrderTotal;

            if (_braintreePaymentSettings.UseMultiCurrency)
            {
                //get currency
                var currency = _workContext.WorkingCurrency;

                currencyMerchantId = _braintreeMerchantService.GetMerchantId(currency.CurrencyCode);

                if (!string.IsNullOrEmpty(currencyMerchantId))
                {
                    amount = _currencyService.ConvertCurrency(amount, currency.Rate);
                }
            }

            //new transaction request
            var transactionRequest = new TransactionRequest
            {
                Amount            = amount,
                CustomerId        = customerId,
                Channel           = BraintreePaymentDefaults.PartnerCode,
                MerchantAccountId = currencyMerchantId
            };

            if (_braintreePaymentSettings.Use3DS)
            {
                transactionRequest.PaymentMethodNonce = processPaymentRequest.CustomValues["CardNonce"].ToString();
            }
            else
            {
                //transaction credit card request
                var transactionCreditCardRequest = new TransactionCreditCardRequest
                {
                    Number         = processPaymentRequest.CreditCardNumber,
                    CVV            = processPaymentRequest.CreditCardCvv2,
                    ExpirationDate = processPaymentRequest.CreditCardExpireMonth + "/" + processPaymentRequest.CreditCardExpireYear,
                };
                transactionRequest.CreditCard = transactionCreditCardRequest;
            }

            //customer request
            var customerRequest = new CustomerRequest
            {
                CustomerId = customerId,
                FirstName  = billingAddress?.FirstName,
                LastName   = billingAddress?.LastName,
                Email      = billingAddress?.Email,
                Fax        = billingAddress?.FaxNumber,
                Company    = billingAddress?.Company,
                Phone      = billingAddress?.PhoneNumber
            };

            transactionRequest.Customer = customerRequest;

            var country = _countryService.GetCountryByAddress(billingAddress);

            //address request
            var addressRequest = new AddressRequest
            {
                FirstName         = billingAddress?.FirstName,
                LastName          = billingAddress?.LastName,
                StreetAddress     = billingAddress?.Address1,
                PostalCode        = billingAddress?.ZipPostalCode,
                CountryCodeAlpha2 = country?.TwoLetterIsoCode,
                CountryCodeAlpha3 = country?.ThreeLetterIsoCode
            };

            transactionRequest.BillingAddress = addressRequest;

            //transaction options request
            var transactionOptionsRequest = new TransactionOptionsRequest
            {
                SubmitForSettlement = true,
                ThreeDSecure        = new TransactionOptionsThreeDSecureRequest()
            };

            transactionRequest.Options = transactionOptionsRequest;

            //sending a request
            var result = gateway.Transaction.Sale(transactionRequest);

            //result
            if (result.IsSuccess())
            {
                processPaymentResult.NewPaymentStatus = PaymentStatus.Paid;
            }
            else
            {
                processPaymentResult.AddError("Error processing payment." + result.Message);
            }

            return(processPaymentResult);
        }
        /// <summary>
        /// Prepare details to place an order. It also sets some properties to "processPaymentRequest"
        /// </summary>
        /// <param name="processPaymentRequest">Process payment request</param>
        /// <returns>Details</returns>
        protected override PlaceOrderContainter PreparePlaceOrderDetails(ProcessPaymentRequest processPaymentRequest)
        {
            var details = new PlaceOrderContainter();

            //Recurring orders. Load initial order
            if (processPaymentRequest.IsRecurringPayment)
            {
                details.InitialOrder = _orderService.GetOrderById(processPaymentRequest.InitialOrderId);
                if (details.InitialOrder == null)
                    throw new ArgumentException("Initial order is not set for recurring payment");

                processPaymentRequest.PaymentMethodSystemName = details.InitialOrder.PaymentMethodSystemName;
            }

            //customer
            details.Customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            if (details.Customer == null)
                throw new ArgumentException("Customer is not set");

            //affiliate
            var affiliate = _affiliateService.GetAffiliateById(details.Customer.AffiliateId);
            if (affiliate != null && affiliate.Active && !affiliate.Deleted)
                details.AffiliateId = affiliate.Id;

            //customer currency
            if (!processPaymentRequest.IsRecurringPayment)
            {
                var currencyTmp = _currencyService.GetCurrencyById(details.Customer.GetAttribute<int>(SystemCustomerAttributeNames.CurrencyId, processPaymentRequest.StoreId));
                var customerCurrency = (currencyTmp != null && currencyTmp.Published) ? currencyTmp : _workContext.WorkingCurrency;
                details.CustomerCurrencyCode = customerCurrency.CurrencyCode;
                var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
                details.CustomerCurrencyRate = customerCurrency.Rate / primaryStoreCurrency.Rate;
            }
            else
            {
                details.CustomerCurrencyCode = details.InitialOrder.CustomerCurrencyCode;
                details.CustomerCurrencyRate = details.InitialOrder.CurrencyRate;
            }

            //customer language
            if (!processPaymentRequest.IsRecurringPayment)
            {
                details.CustomerLanguage = _languageService.GetLanguageById(details.Customer.GetAttribute<int>(
                    SystemCustomerAttributeNames.LanguageId, processPaymentRequest.StoreId));
            }
            else
            {
                details.CustomerLanguage = _languageService.GetLanguageById(details.InitialOrder.CustomerLanguageId);
            }
            if (details.CustomerLanguage == null || !details.CustomerLanguage.Published)
                details.CustomerLanguage = _workContext.WorkingLanguage;

            //check whether customer is guest
            if (details.Customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
                throw new NopException("Anonymous checkout is not allowed");

            //billing address
            if (!processPaymentRequest.IsRecurringPayment)
            {
                if (details.Customer.BillingAddress == null)
                    throw new NopException("Billing address is not provided");

                if (!CommonHelper.IsValidEmail(details.Customer.BillingAddress.Email))
                    throw new NopException("Email is not valid");

                //clone billing address
                details.BillingAddress = (Address)details.Customer.BillingAddress.Clone();
                if (details.BillingAddress.Country != null && !details.BillingAddress.Country.AllowsBilling)
                    throw new NopException(string.Format("Country '{0}' is not allowed for billing", details.BillingAddress.Country.Name));
            }
            else
            {
                if (details.InitialOrder.BillingAddress == null)
                    throw new NopException("Billing address is not available");

                //clone billing address
                details.BillingAddress = (Address)details.InitialOrder.BillingAddress.Clone();
                if (details.BillingAddress.Country != null && !details.BillingAddress.Country.AllowsBilling)
                    throw new NopException(string.Format("Country '{0}' is not allowed for billing", details.BillingAddress.Country.Name));
            }

            //checkout attributes
            if (!processPaymentRequest.IsRecurringPayment)
            {
                details.CheckoutAttributesXml = details.Customer.GetAttribute<string>(SystemCustomerAttributeNames.CheckoutAttributes, processPaymentRequest.StoreId);
                details.CheckoutAttributeDescription = _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributesXml, details.Customer);
            }
            else
            {
                details.CheckoutAttributesXml = details.InitialOrder.CheckoutAttributesXml;
                details.CheckoutAttributeDescription = details.InitialOrder.CheckoutAttributeDescription;
            }

            //load and validate customer shopping cart
            if (!processPaymentRequest.IsRecurringPayment)
            {
                //load shopping cart
                details.Cart = details.Customer.ShoppingCartItems
                    .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                    .LimitPerStore(processPaymentRequest.StoreId)
                    .ToList();

                if (details.Cart.Count == 0)
                    throw new NopException("Cart is empty");

                //validate the entire shopping cart
                var warnings = _shoppingCartService.GetShoppingCartWarnings(details.Cart,
                    details.CheckoutAttributesXml,
                    true);
                if (warnings.Count > 0)
                {
                    var 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 details.Cart)
                {
                    var sciWarnings = _shoppingCartService.GetShoppingCartItemWarnings(details.Customer, sci.ShoppingCartType,
                        sci.Product, processPaymentRequest.StoreId, sci.AttributesXml,
                        sci.CustomerEnteredPrice, sci.RentalStartDateUtc, sci.RentalEndDateUtc,
                        sci.Quantity, false);
                    if (sciWarnings.Count > 0)
                    {
                        var warningsSb = new StringBuilder();
                        foreach (string warning in sciWarnings)
                        {
                            warningsSb.Append(warning);
                            warningsSb.Append(";");
                        }
                        throw new NopException(warningsSb.ToString());
                    }
                }
            }

            //min totals validation
            if (!processPaymentRequest.IsRecurringPayment)
            {
                bool minOrderSubtotalAmountOk = ValidateMinOrderSubtotalAmount(details.Cart);
                if (!minOrderSubtotalAmountOk)
                {
                    decimal minOrderSubtotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderSubtotalAmount, _workContext.WorkingCurrency);
                    throw new NopException(string.Format(_localizationService.GetResource("Checkout.MinOrderSubtotalAmount"), _priceFormatter.FormatPrice(minOrderSubtotalAmount, true, false)));
                }
                bool minOrderTotalAmountOk = ValidateMinOrderTotalAmount(details.Cart);
                if (!minOrderTotalAmountOk)
                {
                    decimal minOrderTotalAmount = _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderTotalAmount, _workContext.WorkingCurrency);
                    throw new NopException(string.Format(_localizationService.GetResource("Checkout.MinOrderTotalAmount"), _priceFormatter.FormatPrice(minOrderTotalAmount, true, false)));
                }
            }

            //tax display type
            if (!processPaymentRequest.IsRecurringPayment)
            {
                if (_taxSettings.AllowCustomersToSelectTaxDisplayType)
                    details.CustomerTaxDisplayType = (TaxDisplayType)details.Customer.GetAttribute<int>(SystemCustomerAttributeNames.TaxDisplayTypeId, processPaymentRequest.StoreId);
                else
                    details.CustomerTaxDisplayType = _taxSettings.TaxDisplayType;
            }
            else
            {
                details.CustomerTaxDisplayType = details.InitialOrder.CustomerTaxDisplayType;
            }

            //sub total
            if (!processPaymentRequest.IsRecurringPayment)
            {
                //sub total (incl tax)
                decimal orderSubTotalDiscountAmount1;

                decimal subTotalWithoutDiscountBase1;
                decimal subTotalWithDiscountBase1;
                global::Nop.Core.Domain.Discounts.Discount orderSubTotalAppliedDiscount1; // TODO: NOT ACTUALLY USED - confirm this, add interface with new signature?
                _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart,
                    true, out orderSubTotalDiscountAmount1, out orderSubTotalAppliedDiscount1,
                    out subTotalWithoutDiscountBase1, out subTotalWithDiscountBase1);
                details.OrderSubTotalInclTax = subTotalWithoutDiscountBase1;
                details.OrderSubTotalDiscountInclTax = orderSubTotalDiscountAmount1;

                //discount history
                if (orderSubTotalAppliedDiscount1 != null && !details.AppliedDiscounts.ContainsDiscount(orderSubTotalAppliedDiscount1))
                    details.AppliedDiscounts.Add(orderSubTotalAppliedDiscount1);

                //sub total (excl tax)
                decimal orderSubTotalDiscountAmount2;
                global::Nop.Core.Domain.Discounts.Discount orderSubTotalAppliedDiscount2; // TODO: NOT ACTUALLY USED - confirm this, add interface with new signature?
                decimal subTotalWithoutDiscountBase2;
                decimal subTotalWithDiscountBase2;
                _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart,
                    false, out orderSubTotalDiscountAmount2, out orderSubTotalAppliedDiscount2,
                    out subTotalWithoutDiscountBase2, out subTotalWithDiscountBase2);
                details.OrderSubTotalExclTax = subTotalWithoutDiscountBase2;
                details.OrderSubTotalDiscountExclTax = orderSubTotalDiscountAmount2;
            }
            else
            {
                details.OrderSubTotalInclTax = details.InitialOrder.OrderSubtotalInclTax;
                details.OrderSubTotalExclTax = details.InitialOrder.OrderSubtotalExclTax;
            }


            //shipping info
            bool shoppingCartRequiresShipping;
            if (!processPaymentRequest.IsRecurringPayment)
            {
                shoppingCartRequiresShipping = details.Cart.RequiresShipping();
            }
            else
            {
                shoppingCartRequiresShipping = details.InitialOrder.ShippingStatus != ShippingStatus.ShippingNotRequired;
            }
            if (shoppingCartRequiresShipping)
            {
                if (!processPaymentRequest.IsRecurringPayment)
                {
                    details.PickUpInStore = _shippingSettings.AllowPickUpInStore &&
                        details.Customer.GetAttribute<bool>(SystemCustomerAttributeNames.SelectedPickUpInStore, processPaymentRequest.StoreId);

                    if (!details.PickUpInStore)
                    {
                        if (details.Customer.ShippingAddress == null)
                            throw new NopException("Shipping address is not provided");

                        if (!CommonHelper.IsValidEmail(details.Customer.ShippingAddress.Email))
                            throw new NopException("Email is not valid");

                        //clone shipping address
                        details.ShippingAddress = (Address)details.Customer.ShippingAddress.Clone();
                        if (details.ShippingAddress.Country != null && !details.ShippingAddress.Country.AllowsShipping)
                        {
                            throw new NopException(string.Format("Country '{0}' is not allowed for shipping", details.ShippingAddress.Country.Name));
                        }
                    }

                    var shippingOption = details.Customer.GetAttribute<ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, processPaymentRequest.StoreId);
                    if (shippingOption != null)
                    {
                        details.ShippingMethodName = shippingOption.Name;
                        details.ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName;
                    }
                }
                else
                {
                    details.PickUpInStore = details.InitialOrder.PickUpInStore;
                    if (!details.PickUpInStore)
                    {
                        if (details.InitialOrder.ShippingAddress == null)
                            throw new NopException("Shipping address is not available");

                        //clone shipping address
                        details.ShippingAddress = (Address)details.InitialOrder.ShippingAddress.Clone();
                        if (details.ShippingAddress.Country != null && !details.ShippingAddress.Country.AllowsShipping)
                        {
                            throw new NopException(string.Format("Country '{0}' is not allowed for shipping", details.ShippingAddress.Country.Name));
                        }
                    }

                    details.ShippingMethodName = details.InitialOrder.ShippingMethod;
                    details.ShippingRateComputationMethodSystemName = details.InitialOrder.ShippingRateComputationMethodSystemName;
                }
            }
            details.ShippingStatus = shoppingCartRequiresShipping
                ? ShippingStatus.NotYetShipped
                : ShippingStatus.ShippingNotRequired;

            //shipping total
            if (!processPaymentRequest.IsRecurringPayment)
            {
                decimal taxRate;
                global::Nop.Core.Domain.Discounts.Discount shippingTotalDiscount; // TODO: NOT ACTUALLY USED - confirm this, add interface with new signature?
                decimal? orderShippingTotalInclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true, out taxRate, out shippingTotalDiscount);
                decimal? orderShippingTotalExclTax = _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, false);
                if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue)
                    throw new NopException("Shipping total couldn't be calculated");
                details.OrderShippingTotalInclTax = orderShippingTotalInclTax.Value;
                details.OrderShippingTotalExclTax = orderShippingTotalExclTax.Value;

                if (shippingTotalDiscount != null && !details.AppliedDiscounts.ContainsDiscount(shippingTotalDiscount))
                    details.AppliedDiscounts.Add(shippingTotalDiscount);
            }
            else
            {
                details.OrderShippingTotalInclTax = details.InitialOrder.OrderShippingInclTax;
                details.OrderShippingTotalExclTax = details.InitialOrder.OrderShippingExclTax;
            }


            //payment total
            if (!processPaymentRequest.IsRecurringPayment)
            {
                decimal paymentAdditionalFee = _paymentService.GetAdditionalHandlingFee(details.Cart, processPaymentRequest.PaymentMethodSystemName);
                details.PaymentAdditionalFeeInclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer);
                details.PaymentAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer);
            }
            else
            {
                details.PaymentAdditionalFeeInclTax = details.InitialOrder.PaymentMethodAdditionalFeeInclTax;
                details.PaymentAdditionalFeeExclTax = details.InitialOrder.PaymentMethodAdditionalFeeExclTax;
            }


            //tax total
            if (!processPaymentRequest.IsRecurringPayment)
            {
                //tax amount
                SortedDictionary<decimal, decimal> taxRatesDictionary;
                details.OrderTaxTotal = _orderTotalCalculationService.GetTaxTotal(details.Cart, out taxRatesDictionary);

                //VAT number
                var customerVatStatus = (VatNumberStatus)details.Customer.GetAttribute<int>(SystemCustomerAttributeNames.VatNumberStatusId);
                if (_taxSettings.EuVatEnabled && customerVatStatus == VatNumberStatus.Valid)
                    details.VatNumber = details.Customer.GetAttribute<string>(SystemCustomerAttributeNames.VatNumber);

                //tax rates
                foreach (var kvp in taxRatesDictionary)
                {
                    var taxRate = kvp.Key;
                    var taxValue = kvp.Value;
                    details.TaxRates += string.Format("{0}:{1};   ", taxRate.ToString(CultureInfo.InvariantCulture), taxValue.ToString(CultureInfo.InvariantCulture));
                }
            }
            else
            {
                details.OrderTaxTotal = details.InitialOrder.OrderTax;
                //VAT number
                details.VatNumber = details.InitialOrder.VatNumber;
            }


            //order total (and applied discounts, gift cards, reward points)
            if (!processPaymentRequest.IsRecurringPayment)
            {
                List<AppliedGiftCard> appliedGiftCards = null;
                global::Nop.Core.Domain.Discounts.Discount orderAppliedDiscount; // TODO: NOT ACTUALLY USED - confirm this, add interface with new signature?
                decimal orderDiscountAmount;
                int redeemedRewardPoints;
                decimal redeemedRewardPointsAmount;

                var orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(details.Cart,
                    out orderDiscountAmount, out orderAppliedDiscount, out appliedGiftCards,
                    out redeemedRewardPoints, out redeemedRewardPointsAmount);
                if (!orderTotal.HasValue)
                    throw new NopException("Order total couldn't be calculated");

                details.OrderDiscountAmount = orderDiscountAmount;
                details.RedeemedRewardPoints = redeemedRewardPoints;
                details.RedeemedRewardPointsAmount = redeemedRewardPointsAmount;
                details.AppliedGiftCards = appliedGiftCards;
                details.OrderTotal = orderTotal.Value;

                //discount history
                if (orderAppliedDiscount != null && !details.AppliedDiscounts.ContainsDiscount(orderAppliedDiscount))
                    details.AppliedDiscounts.Add(orderAppliedDiscount);
            }
            else
            {
                details.OrderDiscountAmount = details.InitialOrder.OrderDiscount;
                details.OrderTotal = details.InitialOrder.OrderTotal;
            }
            processPaymentRequest.OrderTotal = details.OrderTotal;

            //recurring or standard shopping cart?
            if (!processPaymentRequest.IsRecurringPayment)
            {
                details.IsRecurringShoppingCart = details.Cart.IsRecurring();
                if (details.IsRecurringShoppingCart)
                {
                    int recurringCycleLength;
                    RecurringProductCyclePeriod recurringCyclePeriod;
                    int recurringTotalCycles;
                    string recurringCyclesError = details.Cart.GetRecurringCycleInfo(_localizationService,
                        out recurringCycleLength, out recurringCyclePeriod, out recurringTotalCycles);
                    if (!string.IsNullOrEmpty(recurringCyclesError))
                        throw new NopException(recurringCyclesError);

                    processPaymentRequest.RecurringCycleLength = recurringCycleLength;
                    processPaymentRequest.RecurringCyclePeriod = recurringCyclePeriod;
                    processPaymentRequest.RecurringTotalCycles = recurringTotalCycles;
                }
            }
            else
            {
                details.IsRecurringShoppingCart = true;
            }

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

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            var store    = _services.StoreService.GetStoreById(processPaymentRequest.StoreId);

            var webClient = new WebClient();
            var form      = new NameValueCollection();

            form.Add("x_login", _authorizeNetPaymentSettings.LoginId);
            form.Add("x_tran_key", _authorizeNetPaymentSettings.TransactionKey);
            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", store.PrimaryStoreCurrency.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 SmartException("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);
            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);
            }
            //20 chars maximum
            form.Add("x_invoice_num", processPaymentRequest.OrderGuid.ToString().Substring(0, 20));
            form.Add("x_customer_ip", _services.WebHelper.GetCurrentIpAddress());

            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":
                    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);
        }