public CheckoutOrder Build(CheckoutOrder checkoutOrderData, ICart cart, CheckoutConfiguration checkoutConfiguration)
        {
            if (checkoutConfiguration == null)
            {
                return(checkoutOrderData);
            }

            checkoutOrderData.ExternalPaymentMethods = new[]
            {
                new PaymentProvider {
                    Fee = 10, ImageUrl = "https://klarna.geta.no/Styles/Images/paypalpng", Name = "PayPal", RedirectUrl = "https://klarna.geta.no"
                }
            };

            if (checkoutConfiguration.PrefillAddress)
            {
                // Try to parse address into dutch address lines
                if (checkoutOrderData.ShippingCheckoutAddress != null && !string.IsNullOrEmpty(checkoutOrderData.ShippingCheckoutAddress.Country) && checkoutOrderData.ShippingCheckoutAddress.Country.Equals("NL"))
                {
                    var dutchAddress = ConvertToDutchAddress(checkoutOrderData.ShippingCheckoutAddress);
                    checkoutOrderData.ShippingCheckoutAddress = dutchAddress;
                }
            }
            UpdateOrderLines(checkoutOrderData.OrderLines, checkoutConfiguration);

            return(checkoutOrderData);
        }
        /// <summary>
        /// Updates an existing order.
        /// Please note: an order can only be updated when the status is 'checkout_incomplete'.
        /// <a href="https://developers.klarna.com/api/#checkout-api-update-an-order">https://developers.klarna.com/api/#checkout-api-update-an-order</a>
        /// </summary>
        /// <param name="order">The <see cref="CheckoutOrder"/> object</param>
        /// <returns><see cref="CheckoutOrder"/></returns>
        public async Task <CheckoutOrder> UpdateOrder(CheckoutOrder order)
        {
            var url = ApiUrlHelper.GetApiUrlForController(ApiSession.ApiUrl, ApiControllerUri, order.OrderId);

            var response = await Post <CheckoutOrder>(url, order);

            return(response);
        }
Beispiel #3
0
 public bool Compare(CheckoutOrder checkoutData, CheckoutOrder otherCheckoutOrderData)
 {
     return(checkoutData.OrderAmount.Equals(otherCheckoutOrderData.OrderAmount) &&
            checkoutData.OrderTaxAmount.Equals(otherCheckoutOrderData.OrderTaxAmount) &&
            checkoutData.ShippingCheckoutAddress != null &&
            otherCheckoutOrderData.ShippingCheckoutAddress != null &&
            checkoutData.ShippingCheckoutAddress.PostalCode.Equals(otherCheckoutOrderData.ShippingCheckoutAddress.PostalCode, StringComparison.InvariantCultureIgnoreCase) &&
            (checkoutData.ShippingCheckoutAddress.Region == null && otherCheckoutOrderData.ShippingCheckoutAddress.Region == null ||
             checkoutData.ShippingCheckoutAddress.Region.Equals(otherCheckoutOrderData.ShippingCheckoutAddress.Region, StringComparison.InvariantCultureIgnoreCase)) &&
            checkoutData.ShippingCheckoutAddress.Country.Equals(otherCheckoutOrderData.ShippingCheckoutAddress.Country, StringComparison.InvariantCultureIgnoreCase));
 }
Beispiel #4
0
        public Sale OrderSale(CheckoutOrder checkoutOrder)
        {
            var sale = checkoutRepository.Checkout(checkoutOrder);

            if (sale != null)
            {
                saleRepository.Save(sale);
            }

            return(sale);
        }
Beispiel #5
0
 public async Task <CheckoutOrder> Update(CheckoutOrder checkoutOrderData)
 {
     try
     {
         return(await _client.UpdateOrder(checkoutOrderData).ConfigureAwait(false));
     }
     catch (ApiException e)
     {
         Log(e);
         throw;
     }
 }
Beispiel #6
0
        public Sale Checkout(CheckoutOrder checkoutOrder)
        {
            Sale sale = null;

            if (checkoutOrder != null)
            {
                SaleRequestMessage request = new SaleRequestMessage()
                {
                    Order = new SaleRequestMessage.OrderClass()
                    {
                        OrderReference = Guid.NewGuid().ToString()
                    }
                };
                request.CreditCardTransactionCollection.Add(new SaleRequestMessage.CreditCardTransactionCollectionClass()
                {
                    AmountInCents    = Convert.ToInt32(checkoutOrder.TransactionValue * 100),
                    InstallmentCount = 1,
                    CreditCard       = new SaleRequestMessage.CreditCard()
                    {
                        CreditCardBrand  = checkoutOrder.CreditCardFlag,
                        CreditCardNumber = checkoutOrder.CreditCardNumber,
                        ExpMonth         = checkoutOrder.ExpirationMonth,
                        ExpYear          = checkoutOrder.ExpirationYear,
                        HolderName       = checkoutOrder.NameOnCreditCard,
                        SecurityCode     = checkoutOrder.SecurityCode
                    }
                });
                using (MundipaggApiClient client = new MundipaggApiClient())
                {
                    var response = client.Sale(checkoutOrder.MerchantId, request);
                    if (response.CreditCardTransactionResultCollection != null)
                    {
                        var creditResult = response.CreditCardTransactionResultCollection[0];
                        sale = new Sale()
                        {
                            AmountInCents    = creditResult.AmountInCents,
                            CreditCardBrand  = creditResult.CreditCard.CreditCardBrand,
                            CreditCardNumber = creditResult.CreditCard.MaskedCreditCardNumber,
                            Date             = DateTime.Now,
                            Email            = checkoutOrder.Email,
                            HolderName       = checkoutOrder.NameOnCreditCard,
                            Name             = checkoutOrder.Name,
                            OrderKey         = response.OrderResult.OrderKey
                        };
                    }
                }
            }
            return(sale);
        }
Beispiel #7
0
        protected virtual ICart UpdateCartWithOrderData(ICart cart, CheckoutOrder orderData)
        {
            var shipment = cart.GetFirstShipment();

            if (shipment != null && orderData.ShippingCheckoutAddress.IsValid())
            {
                shipment.ShippingAddress = orderData.ShippingCheckoutAddress.ToOrderAddress(cart);
                _orderRepository.Save(cart);
            }

            // Store checkout order id on cart
            cart.Properties[Constants.KlarnaCheckoutOrderIdCartField] = orderData.OrderId;

            _orderRepository.Save(cart);

            return(cart);
        }
Beispiel #8
0
        public static CheckoutOrder MapToDomain(CheckoutOrderView order)
        {
            CheckoutOrder checkout = null;

            if (order != null)
            {
                checkout = new CheckoutOrder()
                {
                    CreditCardFlag   = order.CreditCardFlag,
                    CreditCardNumber = order.CreditCardNumber,
                    Email            = order.Email,
                    ExpirationMonth  = order.ExpirationMonth,
                    ExpirationYear   = order.ExpirationYear,
                    Name             = order.Name,
                    NameOnCreditCard = order.NameOnCreditCard,
                    SecurityCode     = order.SecurityCode,
                    TransactionValue = order.TransactionValue,
                    MerchantId       = order.MerchantId
                };
            }

            return(checkout);
        }
        public IHttpActionResult OrderValidation(int orderGroupId, [FromBody] CheckoutOrder checkoutData)
        {
            var cart = _orderRepository.Load <ICart>(orderGroupId);

            // Validate cart lineitems
            var validationIssues = _cartService.ValidateCart(cart);

            if (validationIssues.Any())
            {
                // check validation issues and redirect to a page to display the error
                var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
                httpResponseMessage.Headers.Location = new Uri("https://klarna.geta.no/en/error-pages/checkout-something-went-wrong/");
                return(ResponseMessage(httpResponseMessage));
            }

            // Validate billing address if necessary (this is just an example)
            // To return an error like this you need require_validate_callback_success set to true
            if (checkoutData.BillingCheckoutAddress.PostalCode.Equals("94108-2704"))
            {
                var errorResult = new ErrorResult
                {
                    ErrorType = ErrorType.address_error,
                    ErrorText = "Can't ship to postalcode 94108-2704"
                };
                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, errorResult)));
            }

            // Validate order amount, shipping address
            if (!_klarnaCheckoutService.ValidateOrder(cart, checkoutData))
            {
                var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
                httpResponseMessage.Headers.Location = new Uri("https://klarna.geta.no/en/error-pages/checkout-something-went-wrong/");
                return(ResponseMessage(httpResponseMessage));
            }

            return(Ok());
        }
Beispiel #10
0
        public virtual bool ValidateOrder(ICart cart, CheckoutOrder checkoutData)
        {
            // Compare the current cart state to the Klarna order state (totals, shipping selection, discounts, and gift cards). If they don't match there is an issue.
            var market = _marketService.GetMarket(cart.MarketId);
            var localCheckoutOrderData = GetCheckoutOrderData(cart, market, PaymentMethodDto);

            localCheckoutOrderData.ShippingCheckoutAddress = cart.GetFirstShipment().ShippingAddress.ToCheckoutAddress();

            if (!_klarnaOrderValidator.Compare(checkoutData, localCheckoutOrderData))
            {
                return(false);
            }

            // Order is valid, create on hold cart in epi
            cart.Name = OrderStatus.OnHold.ToString();
            _orderRepository.Save(cart);

            // Create new default cart
            var newCart = _orderRepository.Create <ICart>(cart.CustomerId, Cart.DefaultName);

            _orderRepository.Save(newCart);

            return(true);
        }
        protected void Page_Load(object sender, EventArgs args)
        {
            PutHTMLLogs("Page is loading...");
            // Set your credentials and point to an API environment
            // Remember to set $MERCHANT_ID$ and $PASSWORD$ to your account's values
            // More about authentication here https://developers.klarna.com/api/#authentication
            var username = "******";
            var password = "******";

            PutHTMLLogs("Creating Klarna API Client");
            var client = new Client(username, password, KlarnaEnvironment.TestingEurope);

            PutHTMLLogs("Prepare an order by constructing its body");
            var order = new CheckoutOrder
            {
                PurchaseCountry  = "gb",
                PurchaseCurrency = "gbp",
                Locale           = "en-gb",
                OrderAmount      = 10000,
                OrderTaxAmount   = 2000,
                MerchantUrls     = new CheckoutMerchantUrls
                {
                    Terms        = "https://www.example.com/terms.html",
                    Checkout     = "https://www.example.com/checkout.html",
                    Confirmation = "https://www.example.com/confirmation.html",
                    Push         = "https://www.example.com/push.html"
                },
                OrderLines = new List <OrderLine>()
                {
                    new OrderLine
                    {
                        Type                = OrderLineType.physical,
                        Name                = "Tomatoes",
                        Quantity            = 10,
                        QuantityUnit        = "kg",
                        UnitPrice           = 600,
                        TaxRate             = 2500,
                        TotalAmount         = 6000,
                        TotalTaxAmount      = 1200,
                        TotalDiscountAmount = 0,
                    },
                    new OrderLine
                    {
                        Type                = OrderLineType.physical,
                        Name                = "Bananas",
                        Quantity            = 1,
                        QuantityUnit        = "bag",
                        UnitPrice           = 5000,
                        TaxRate             = 2500,
                        TotalAmount         = 4000,
                        TotalTaxAmount      = 800,
                        TotalDiscountAmount = 1000
                    }
                }
            };

            PutHTMLLogs("Proceed with operating against the Klarna Checkout API");
            try
            {
                PutHTMLLogs("Sending a request to Klarna API server");
                // Due to the Web Forms limitations we cannot use Task.Result in the Main thread
                // https://blogs.msdn.microsoft.com/jpsanders/2017/08/28/asp-net-do-not-use-task-result-in-main-context/
                Task <CheckoutOrder> callTask = Task.Run(() => client.Checkout.CreateOrder(order));

                PutHTMLLogs("Waiting for the result");
                callTask.Wait();

                PutHTMLLogs("Show the HTML snippet code to the customer");
                HTMLSnippet.InnerHtml = callTask.Result.HtmlSnippet;
            }
            catch (AggregateException ae)
            {
                foreach (var e in ae.InnerExceptions)
                {
                    if (e is ApiException)
                    {
                        var apiException     = (ApiException)e;
                        var error            = "Status code: " + apiException.StatusCode;
                        var exceptionMessage = string.Join("; ", apiException.ErrorMessage.ErrorMessages);
                        Console.WriteLine(error, exceptionMessage);
                        PutHTMLLogs($"An Error occured: {error}");
                        HTMLSnippet.InnerHtml = exceptionMessage;
                    }
                    else
                    {
                        Console.WriteLine(e.Message);
                        PutHTMLLogs($"An Error occured: {e.Message}");
                    }
                }
            }
        }
        /// <summary>
        /// Run the example code.
        /// Remember to replace username and password with valid Klarna credentials.
        /// </summary>
        static void Main()
        {
            var username = "******";
            var password = "******";

            var client = new Klarna(username, password, KlarnaEnvironment.TestingEurope);

            var order = new CheckoutOrder
            {
                PurchaseCountry  = "se",
                PurchaseCurrency = "sek",
                Locale           = "sv-se",
                OrderAmount      = 10000,
                OrderTaxAmount   = 2000,
                MerchantUrls     = new CheckoutMerchantUrls
                {
                    Terms        = "https://www.estore.com/terms.html",
                    Checkout     = "https://www.estore.com/checkout.html",
                    Confirmation = "https://www.estore.com/confirmation.html",
                    Push         = "https://www.estore.com/push.html"
                },
                OrderLines = new List <OrderLine>()
                {
                    new OrderLine
                    {
                        Type                = OrderLineType.physical,
                        Name                = "Foo",
                        Quantity            = 1,
                        UnitPrice           = 10000,
                        TaxRate             = 2500,
                        TotalAmount         = 10000,
                        TotalTaxAmount      = 2000,
                        TotalDiscountAmount = 0,
                    }
                },
                CheckoutOptions = new CheckoutOptions
                {
                    AllowSeparateShippingAddress = false,
                    ColorButton            = "#FF9900",
                    ColorButtonText        = "#FF9900",
                    ColorCheckbox          = "#FF9900",
                    ColorCheckboxCheckmark = "#FF9900",
                    ColorHeader            = "#FF9900",
                    ColorLink            = "#FF9900",
                    DateOfBirthMandatory = false,
                    ShippingDetails      = "bar",
                }
            };

            try
            {
                var createdOrder = client.Checkout.CreateOrder(order).Result;
                var orderId      = createdOrder.OrderId;
                Console.WriteLine($"Order ID: {orderId}");
            }
            catch (ApiException ex)
            {
                Console.WriteLine(ex.ErrorMessage.ErrorCode);
                Console.WriteLine(ex.ErrorMessage.ErrorMessages);
                Console.WriteLine(ex.ErrorMessage.CorrelationId);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// Updates an existing order.
        /// Please note: an order can only be updated when the status is 'checkout_incomplete'.
        /// <a href="https://developers.klarna.com/api/#checkout-api-update-an-order">
        ///     https://developers.klarna.com/api/#checkout-api-update-an-order
        /// </a>
        /// </summary>
        /// <param name="order">The <see cref="CheckoutOrder"/> object</param>
        /// <returns><see cref="CheckoutOrder"/></returns>
        public async Task <CheckoutOrder> UpdateOrder(CheckoutOrder order)
        {
            var url = ApiUrlHelper.GetApiUrlForController(ApiSession.ApiUrl, ApiControllerUri, order.OrderId);

            return(await Post <CheckoutOrder>(url, order).ConfigureAwait(false));
        }
        /// <summary>
        /// Run the example code.
        /// Remember to replace username and password with valid Klarna credentials.
        /// </summary>
        static void Main()
        {
            var username = "******";
            var password = "******";

            var client = new Klarna(username, password, KlarnaEnvironment.TestingEurope);

            var order = new CheckoutOrder
            {
                PurchaseCountry  = "se",
                PurchaseCurrency = "sek",
                Locale           = "sv-se",
                OrderAmount      = 10000,
                OrderTaxAmount   = 2000,
                MerchantUrls     = new CheckoutMerchantUrls
                {
                    Terms        = "https://www.example.com/terms.html",
                    Checkout     = "https://www.example.com/checkout.html",
                    Confirmation = "https://www.example.com/confirmation.html",
                    Push         = "https://www.example.com/push.html"
                },
                OrderLines = new List <OrderLine>()
                {
                    new OrderLine
                    {
                        Type                = OrderLineType.physical,
                        Name                = "Foo",
                        Quantity            = 1,
                        UnitPrice           = 10000,
                        TaxRate             = 2500,
                        TotalAmount         = 10000,
                        TotalTaxAmount      = 2000,
                        TotalDiscountAmount = 0,
                    }
                },
                CheckoutOptions = new CheckoutOptions
                {
                    AllowSeparateShippingAddress = false,
                    ColorButton            = "#FF9900",
                    ColorButtonText        = "#FF9900",
                    ColorCheckbox          = "#FF9900",
                    ColorCheckboxCheckmark = "#FF9900",
                    ColorHeader            = "#FF9900",
                    ColorLink            = "#FF9900",
                    DateOfBirthMandatory = false,
                    ShippingDetails      = "bar",
                    AllowedCustomerTypes = new List <string>()
                    {
                        "person", "organization"
                    }
                }
            };

            try
            {
                var createdOrder = client.Checkout.CreateOrder(order).Result;
                var orderId      = createdOrder.OrderId;
                Console.WriteLine($"Order ID: {orderId}");
            }
            catch (AggregateException ae)
            {
                foreach (var e in ae.InnerExceptions)
                {
                    if (e is ApiException)
                    {
                        var apiException = (ApiException)e;
                        Console.WriteLine("Status code: " + apiException.StatusCode);
                        Console.WriteLine("Error: " + string.Join("; ", apiException.ErrorMessage.ErrorMessages));
                    }
                    else
                    {
                        // Rethrow any other exception or process it
                        Console.WriteLine(e.Message);
                        throw;
                    }
                }
            }
        }
Beispiel #15
0
        /// <summary>
        /// Creates a new instance of the <see cref="ICheckoutOrder"/> interface.
        /// </summary>
        /// <param name="orderID">id of the checkout order</param>
        /// <returns>the checkout order</returns>
        public ICheckoutOrder NewCheckoutOrder(string orderID)
        {
            CheckoutOrder order = new CheckoutOrder(this.Connector, orderID);

            return(order);
        }
Beispiel #16
0
#pragma warning disable IDE0060 // Remove unused parameter
        public void UpdateDataSentToKlarna(UrlHelper urlHelper, OrderCarrier orderCarrier, KlarnaPaymentArgs paymentArgs, CheckoutOrder klarnaCheckoutOrder)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            //if the project has specific data to be sent to Klarna, outside the order carrier,
            //or has them as additional order info, and is not handled by the Klarna addOn, modify the klarnaCheckoutOrder parameter.
            //it is the klarnaCheckoutOrder object that will be sent to Klarna checkout api at Klarna.
            //the format of klarnaCheckoutOrder parameter is described in Klarna API documentation https://developers.klarna.com.

            //Set the checkout options here.
            klarnaCheckoutOrder.CheckoutOptions = new CheckoutOptions
            {
                AllowSeparateShippingAddress = true,
                ColorButton          = "#ff69b4",
                DateOfBirthMandatory = true
            };

            //External payment methods should be configured for each Merchant account by Klarna before they are used.
            AddCashOnDeliveryExternalPaymentMethod(urlHelper, orderCarrier, klarnaCheckoutOrder);
        }
Beispiel #17
0
#pragma warning disable IDE0060 // Remove unused parameter
        public void AddressUpdate(CheckoutOrder checkoutOrderData)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            // If the campaigns depend on address location, re-calculate the cart, after updating delivery addresses.
            // if you recalculate order totals, the checkoutOrderData must contain the correct order rows and order total values.
        }
Beispiel #18
0
        protected virtual CheckoutOrder GetCheckoutOrderData(
            ICart cart, IMarket market, PaymentMethodDto paymentMethodDto)
        {
            var totals        = _orderGroupCalculator.GetOrderGroupTotals(cart);
            var shipment      = cart.GetFirstShipment();
            var marketCountry = CountryCodeHelper.GetTwoLetterCountryCode(market.Countries.FirstOrDefault());

            if (string.IsNullOrWhiteSpace(marketCountry))
            {
                throw new ConfigurationException($"Please select a country in CM for market {cart.MarketId}");
            }
            var checkoutConfiguration = GetCheckoutConfiguration(market);

            var orderData = new CheckoutOrder
            {
                PurchaseCountry  = marketCountry,
                PurchaseCurrency = cart.Currency.CurrencyCode,
                Locale           = _languageService.ConvertToLocale(Thread.CurrentThread.CurrentCulture.Name),
                // Non-negative, minor units. Total amount of the order, including tax and any discounts.
                OrderAmount = AmountHelper.GetAmount(totals.Total),
                // Non-negative, minor units. The total tax amount of the order.
                OrderTaxAmount = AmountHelper.GetAmount(totals.TaxTotal),
                MerchantUrls   = GetMerchantUrls(cart),
                OrderLines     = GetOrderLines(cart, totals, checkoutConfiguration.SendProductAndImageUrl)
            };

            if (checkoutConfiguration.SendShippingCountries)
            {
                orderData.ShippingCountries = GetCountries().ToList();
            }

            // KCO_6 Setting to let the user select shipping options in the iframe
            if (checkoutConfiguration.SendShippingOptionsPriorAddresses)
            {
                if (checkoutConfiguration.ShippingOptionsInIFrame)
                {
                    orderData.ShippingOptions = GetShippingOptions(cart, cart.Currency).ToList();
                }
                else
                {
                    if (shipment != null)
                    {
                        orderData.SelectedShippingOption = ShippingManager.GetShippingMethod(shipment.ShippingMethodId)
                                                           ?.ShippingMethod?.FirstOrDefault()
                                                           ?.ToShippingOption();
                    }
                }
            }

            if (paymentMethodDto != null)
            {
                orderData.CheckoutOptions = GetOptions(cart.MarketId);
            }

            if (checkoutConfiguration.PrefillAddress)
            {
                // KCO_4: In case of signed in user the email address and default address details will be prepopulated by data from Merchant system.
                var customerContact = CustomerContext.Current.GetContactById(cart.CustomerId);
                if (customerContact?.PreferredBillingAddress != null)
                {
                    orderData.BillingCheckoutAddress = customerContact.PreferredBillingAddress.ToAddress();
                }

                if (orderData.CheckoutOptions.AllowSeparateShippingAddress)
                {
                    if (customerContact?.PreferredShippingAddress != null)
                    {
                        orderData.ShippingCheckoutAddress = customerContact.PreferredShippingAddress.ToAddress();
                    }

                    if (shipment?.ShippingAddress != null)
                    {
                        orderData.ShippingCheckoutAddress = shipment.ShippingAddress.ToCheckoutAddress();
                    }
                }
            }

            return(orderData);
        }
Beispiel #19
0
        /*
         * public static T[] SubArrayDeepClone<T>(T[] data, int index, int length)
         * {
         *  T[] arrCopy = new T[length];
         *  Array.Copy(data, index, arrCopy, 0, length);
         *  using (MemoryStream ms = new MemoryStream())
         *  {
         *      var bf = new BinaryFormatter();
         *      bf.Serialize(ms, arrCopy);
         *      ms.Position = 0;
         *      return (T[])bf.Deserialize(ms);
         *  }
         * }
         * public static string[] GetRandomValue()
         * {
         *  string[] array = new[] {
         *  "21546",
         *  "22039",
         *  "23066",
         *  "23176",
         *  "24134",
         *  "24153",
         *  "31949",
         *  "31953",
         *  "34855",
         *  "37310",
         *  "38703",
         *  "23066",
         *  "38703",
         *  "21546",
         *  "20588"
         * };
         *  SubArrayDeepClone(array, 1, 13);
         *
         *  var count = array.Length;
         *
         *  var random= new Random();
         *  int howMuchSelectElement= random.Next(1, count-1);
         *  int startPosition = random.Next(0, howMuchSelectElement - 1);
         * // string[] outputArray = new List<string>(array).GetRange(startPosition, howMuchSelectElement).ToArray();
         *
         *
         *  return SubArrayDeepClone(array, startPosition, howMuchSelectElement); ;
         * }
         */
        #endregion
        static void Main(string[] args)
        {
            #region InputingIDsOfProducts
            string[] array = new[] {
                "21546",
                "22039",
                "23066",
                "23176",
                "24134",
                "24153",
                "31949",
                "31953",
                "34855",
                "37310",
                "38703",
                "23066",
                "38703",
                "21546",
                "20588"
            };
            var arr1 = new[]
            {
                "21546",
                "22039",
                "23066",
                "23176"
            };
            var arr2 = new[]
            {
                "24153",
                "31949",
                "31953",
                "34855",
                "37310",
                "38703"
            };
            var arr3 = new[]
            {
                "34855",
                "37310",
                "38703",
                "23066",
                "38703",
                "21546",
                "20588"
            };
            var arr4 = new[]
            {
                "34855",
                "37310",
                "38703"
            };
            #endregion
            //inizitialisation
            IWebDriver driverChrome = new ChromeDriver();
            Cases      cases        = new Cases();

            MainUnitTest unitTest0 = new MainUnitTest("+380505577332", "1q2w3e", arr4, driverChrome);
            unitTest0.Navigate();
            CheckoutOrder order0 = new CheckoutOrder(2, "Lisichansk", "Petrovskogo", "5B", 6, 2, 2, "comment to address");
            unitTest0.CheckoutOrder(order0);
            cases.OutputFailedCases("I", unitTest0);

            MainUnitTest unitTest = new MainUnitTest("+380666999966", "1q2w3e", arr1, driverChrome);
            unitTest.Navigate();
            CheckoutOrder order = new CheckoutOrder(2, "Severodonetsk", "Mayakovskogo", "58", 4, 2, 2, "comment to address");
            unitTest.CheckoutOrder(order);
            cases.OutputFailedCases("II", unitTest);

            MainUnitTest unitTest2 = new MainUnitTest("+380123456789", "1q2w3e", arr2, driverChrome);
            unitTest2.Navigate();
            CheckoutOrder order2 = new CheckoutOrder(2, "Kiev", "Lenina", "33", 18, 10, 1, "comment to address2");
            unitTest2.CheckoutOrder(order2);
            cases.OutputFailedCases("III", unitTest2);

            MainUnitTest unitTest3 = new MainUnitTest("+380101010101", "1q2w3e", arr3, driverChrome);
            unitTest3.Navigate();
            CheckoutOrder order3 = new CheckoutOrder(2, "Odessa", "Chkalova", "16", 1, 1, 1, "comment to address2");
            unitTest3.CheckoutOrder(order3);
            cases.OutputFailedCases("IV", unitTest3);

            driverChrome.Close();
            Environment.Exit(0);
        }
Beispiel #20
0
        public IPurchaseOrder CreatePurchaseOrderForKlarna(string klarnaOrderId, CheckoutOrder order, ICart cart)
        {
            var paymentRow = PaymentManager.GetPaymentMethodBySystemName(Constants.KlarnaCheckoutSystemKeyword, _languageService.GetPreferredCulture().Name).PaymentMethod.FirstOrDefault();

            var payment = cart.CreatePayment(_orderGroupFactory);

            payment.PaymentType       = PaymentType.Other;
            payment.PaymentMethodId   = paymentRow.PaymentMethodId;
            payment.PaymentMethodName = Constants.KlarnaCheckoutSystemKeyword;
            payment.Amount            = cart.GetTotal(_orderGroupCalculator).Amount;
            payment.Status            = PaymentStatus.Pending.ToString();
            payment.TransactionType   = TransactionType.Authorization.ToString();

            cart.AddPayment(payment, _orderGroupFactory);

            var billingAddress = new AddressModel
            {
                Name               = $"{order.BillingCheckoutAddress.StreetAddress}{order.BillingCheckoutAddress.StreetAddress2}{order.BillingCheckoutAddress.City}",
                FirstName          = order.BillingCheckoutAddress.GivenName,
                LastName           = order.BillingCheckoutAddress.FamilyName,
                Email              = order.BillingCheckoutAddress.Email,
                DaytimePhoneNumber = order.BillingCheckoutAddress.Phone,
                Line1              = order.BillingCheckoutAddress.StreetAddress,
                Line2              = order.BillingCheckoutAddress.StreetAddress2,
                PostalCode         = order.BillingCheckoutAddress.PostalCode,
                City               = order.BillingCheckoutAddress.City,
                CountryName        = order.BillingCheckoutAddress.Country
            };

            payment.BillingAddress = _addressBookService.ConvertToAddress(billingAddress, cart);

            cart.ProcessPayments(_paymentProcessor, _orderGroupCalculator);

            var totalProcessedAmount = cart.GetFirstForm().Payments.Where(x => x.Status.Equals(PaymentStatus.Processed.ToString())).Sum(x => x.Amount);

            if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount)
            {
                throw new InvalidOperationException("Wrong amount");
            }

            if (payment.HasFraudStatus(FraudStatus.PENDING))
            {
                payment.Status = PaymentStatus.Pending.ToString();
            }

            _cartService.RequestInventory(cart);

            var orderReference = _orderRepository.SaveAsPurchaseOrder(cart);
            var purchaseOrder  = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId);

            _orderRepository.Delete(cart.OrderLink);

            if (purchaseOrder == null)
            {
                _klarnaCheckoutService.CancelOrder(cart);

                return(null);
            }
            else
            {
                _klarnaCheckoutService.Complete(purchaseOrder);
                purchaseOrder.Properties[Klarna.Common.Constants.KlarnaOrderIdField] = klarnaOrderId;

                _orderRepository.Save(purchaseOrder);
                return(purchaseOrder);
            }
        }
Beispiel #21
0
        public ActionResult Kco()
        {
            AddLogs("Creating Klarna API Client");
            var client = new Client(_username, _password, KlarnaEnvironment.TestingEurope);

            AddLogs("Prepare an order by constructing its body");
            var order = new CheckoutOrder
            {
                PurchaseCountry  = "gb",
                PurchaseCurrency = "gbp",
                Locale           = "en-gb",
                OrderAmount      = 10000,
                OrderTaxAmount   = 2000,
                MerchantUrls     = new CheckoutMerchantUrls
                {
                    Terms        = "https://www.example.com/terms.html",
                    Checkout     = "https://www.example.com/checkout.html",
                    Confirmation = "https://www.example.com/confirmation.html",
                    Push         = "https://www.example.com/push.html"
                },
                OrderLines = new List <OrderLine>()
                {
                    new OrderLine
                    {
                        Type                = OrderLineType.physical,
                        Name                = "Foo",
                        Quantity            = 1,
                        UnitPrice           = 10000,
                        TaxRate             = 2500,
                        TotalAmount         = 10000,
                        TotalTaxAmount      = 2000,
                        TotalDiscountAmount = 0,
                    }
                }
            };

            AddLogs("Proceed with operating against the Klarna Checkout API");
            try
            {
                AddLogs("Sending a request to Klarna API server");
                var createdOrder = client.Checkout.CreateOrder(order).Result;

                AddLogs("Getting the HTML snippet code ");
                ViewBag.HTMLSnippet = createdOrder.HtmlSnippet;
            }
            catch (AggregateException ae)
            {
                foreach (var e in ae.InnerExceptions)
                {
                    if (e is ApiException)
                    {
                        var apiException = (ApiException)e;
                        ViewBag.Error = "Status code: " + apiException.StatusCode + "; Error: "
                                        + string.Join("; ", apiException.ErrorMessage.ErrorMessages);
                        AddLogs($"Error happened {ViewBag.Error}");
                    }
                    else
                    {
                        ViewBag.Error = e.Message;
                        AddLogs($"Error happened {ViewBag.Error}");
                    }
                }
            }

            ViewBag.Logs = GetLogs().ToArray();
            AddLogs("Render the page template");

            return(View());
        }
        /// <summary>
        /// Run the example code.
        /// Remember to replace username and password with valid Klarna credentials.
        /// </summary>
        static void Main()
        {
            var username = "******";
            var password = "******";

            var client = new Klarna(username, password, KlarnaEnvironment.TestingEurope);

            var order = new CheckoutOrder
            {
                PurchaseCountry  = "gb",
                PurchaseCurrency = "gbp",
                Locale           = "en-gb",
                OrderAmount      = 9000,
                OrderTaxAmount   = 818,
                MerchantUrls     = new CheckoutMerchantUrls
                {
                    Terms        = "https://www.example.com/terms.html",
                    Checkout     = "https://www.example.com/checkout.html",
                    Confirmation = "https://www.example.com/confirmation.html",
                    Push         = "https://www.example.com/push.html"
                },
                OrderLines = new List <OrderLine>()
                {
                    new OrderLine
                    {
                        Type           = OrderLineType.physical,
                        Reference      = "19-402-USA",
                        Name           = "Red T-Shirt",
                        Quantity       = 1,
                        QuantityUnit   = "pcs",
                        UnitPrice      = 10000,
                        TaxRate        = 1000,
                        TotalAmount    = 10000,
                        TotalTaxAmount = 909
                    },

                    // Set a discount
                    new OrderLine
                    {
                        Type           = OrderLineType.discount,
                        Reference      = "10-gbp-order-discount",
                        Name           = "Discount",
                        Quantity       = 1,
                        UnitPrice      = -1000,
                        TaxRate        = 1000,
                        TotalAmount    = -1000,
                        TotalTaxAmount = -91
                    }
                },
            };

            try
            {
                var createdOrder = client.Checkout.CreateOrder(order).Result;
                Console.WriteLine(createdOrder.HtmlSnippet);
            }
            catch (AggregateException ae)
            {
                foreach (var e in ae.InnerExceptions)
                {
                    if (e is ApiException)
                    {
                        var apiException = (ApiException)e;
                        Console.WriteLine("Status code: " + apiException.StatusCode);
                        Console.WriteLine("Error: " + string.Join("; ", apiException.ErrorMessage.ErrorMessages));
                    }
                    else
                    {
                        // Rethrow any other exception or process it
                        Console.WriteLine(e.Message);
                        throw;
                    }
                }
            }
        }
Beispiel #23
0
        /// <summary>
        ///     Adds the cash on delivery external payment method., by using Litium default "DirectPay" as the payment method.
        ///     Note: To use, Klarna has to configure the "Cash on delivery" external payment method for the merchant account.
        /// </summary>
        private void AddCashOnDeliveryExternalPaymentMethod(UrlHelper urlHelper, OrderCarrier orderCarrier, CheckoutOrder klarnaCheckoutOrder)
        {
            var checkoutPage = _websiteService.Get(orderCarrier.WebSiteID)?.Fields.GetValue <PointerPageItem>(AcceleratorWebsiteFieldNameConstants.CheckouPage)?.EntitySystemId.MapTo <Page>();
            var channel      = _channelService.Get(orderCarrier.ChannelID);

            if (checkoutPage == null || channel == null)
            {
                return;
            }

            var redirectUrl = urlHelper.Action(checkoutPage, routeValues: new { action = nameof(CheckoutController.PlaceOrderDirect) }, channel: channel);

            var routeValues = new
            {
                PaymentProvider = "DirectPay",
                PaymentMethod   = "DirectPayment",
                RedirectUrl     = redirectUrl
            };

            var changePaymentProviderUrl      = new Uri(urlHelper.Action("ChangePaymentMethod", "KlarnaPayment", routeValues, Uri.UriSchemeHttps)).AbsoluteUri;
            var cashOnDeliveryExternalPayment = new PaymentProvider
            {
                Name        = "Cash on delivery",
                RedirectUrl = changePaymentProviderUrl,
                Fee         = 0
            };

            klarnaCheckoutOrder.ExternalPaymentMethods = new List <PaymentProvider>
            {
                cashOnDeliveryExternalPayment
            };
        }
        public ActionResult AddressUpdate(string accountId, string transactionNumber, [FromJsonBody] CheckoutOrder checkoutOrderData)
        {
            this.Log().Debug("Address update started accountId {accountId} transactionNumber {transactionNumber}.", accountId, transactionNumber);
            _paymentConfigv3.AddressUpdate(checkoutOrderData);

            this.Log().Debug("Completed.");
            //if the correct Json result is not written to Klarna, the checkout snippet will show and error!.
            return(new JsonResult {
                Data = checkoutOrderData
            });
        }