The order resource.
Inheritance: IResource
コード例 #1
0
        public ActionResult Checkout(Cart cart)
        {
            var cartItems = new List<Dictionary<string, object>>();

            foreach (Cart.CartLine item in GetCart().Lines)
            {
              cartItems.Add(new Dictionary<string, object>
                {
                    { "reference", item.Product.ArticleNumber.ToString() },
                    { "name", item.Product.Name },
                    { "quantity", item.Quantity },
                    { "unit_price", (int)item.Product.Price * 100},
                    { "tax_rate", 2500 }
                });
            }
            var cart_info = new Dictionary<string, object> { { "items", cartItems } };

            var data = new Dictionary<string, object>
            {
            { "cart", cart_info }
            };
            var merchant = new Dictionary<string, object>
            {
            { "id", "5214" },
            { "back_to_store_uri", "https://localhost:44300/" },
            { "terms_uri", "https://localhost:44300/Cart/Terms" },
            {
            "checkout_uri",
            "https://localhost:44300/Cart/Checkout"
            },
            {
            "confirmation_uri",
            "https://localhost:44300/Cart/ThankYou" +
            "?klarna_order_id={checkout.order.id}"
            },
            {
            "push_uri",
            "https://localhost:44300/Cart/push" +
            "?klarna_order_id={checkout.order.id}"
            }
            };
            data.Add("purchase_country", "SE");
            data.Add("purchase_currency", "SEK");
            data.Add("locale", "sv-se");
            data.Add("merchant", merchant);
            var connector = Connector.Create("Y7mNXnxIdYxXU6c", Connector.TestBaseUri);

            Order order = new Order(connector);
            order.Create(data);
            order.Fetch();

            // Store order id of checkout in session object.
            // session["klarna_order_id"] = order.GetValue("id") as string;
            // Display checkout
            var gui = order.GetValue("gui") as JObject;
            var snippet = gui["snippet"];
            return View(snippet);
        }
コード例 #2
0
ファイル: Confirmation.cs プロジェクト: klarna/kco_dotnet
        /// <summary>
        /// This example demonstrates the use of the Klarna library to complete
        /// the purchase and display the confirmation page snippet.
        /// </summary>
        public void Example()
        {
            try
            {
                const string SharedSecret = "sharedSecret";
                var connector = Connector.Create(SharedSecret);

                // Retrieve location from session object.
                // Use following in ASP.NET.
                // var checkoutId = Session["klarna_checkout"] as Uri;
                // Just a placeholder in this example.
                var checkoutId = new Uri(
                    "https://checkout.testdrive.klarna.com/checkout/orders/12"
                );

                var order = new Order(connector, checkoutId)
                {
                    ContentType = "application/vnd.klarna.checkout.aggregated-order-v2+json"
                };

                order.Fetch();

                if ((string)order.GetValue("status") == "checkout_incomplete")
                {
                    // Report error

                    // Use following in ASP.NET.
                    // Response.Write("Checkout not completed, redirect to checkout.aspx");
                }

                // Display thank you snippet
                var gui = order.GetValue("gui") as JObject;
                var snippet = gui["snippet"];

                // DESKTOP: Width of containing block shall be at least 750px
                // MOBILE: Width of containing block shall be 100% of browser
                // window (No padding or margin)
                // Use following in ASP.NET.
                // Response.Write(string.Format("<div>{0}</div>", snippet));

                // Clear session object.
                // Session["klarna_checkout"] = null;
            }
            catch (Exception ex)
            {
            }
        }
コード例 #3
0
ファイル: Push.cs プロジェクト: klarna/kco_dotnet
        /// <summary>
        /// The example.
        /// </summary>
        public void Example()
        {
            try
            {
                const string SharedSecret = "sharedSecret";
                var connector = Connector.Create(SharedSecret);

                // Retrieve location from query string.
                // Use following in ASP.NET.
                // var checkoutId = Request.QueryString["checkout_uri"] as Uri;
                // Just a placeholder in this example.
                var checkoutId = new Uri(
                    "https://checkout.testdrive.klarna.com/checkout/orders/12"
                );
                var order = new Order(connector, checkoutId)
                    {
                        ContentType = "application/vnd.klarna.checkout.aggregated-order-v2+json"
                    };

                order.Fetch();

                if ((string)order.GetValue("status") == "checkout_complete")
                {
                    // At this point make sure the order is created in your
                    // system and send a confirmation email to the customer.

                    var uniqueId = Guid.NewGuid().ToString("N");
                    var reference =
                        new Dictionary<string, object>
                            {
                                { "orderid1", uniqueId }
                            };
                    var data =
                        new Dictionary<string, object>
                            {
                                { "status", "created" },
                                { "merchant_reference", reference}
                            };

                    order.Update(data);
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #4
0
        public override CallbackInfo ProcessCallback(Order order, HttpRequest request, IDictionary <string, string> settings)
        {
            CallbackInfo callbackInfo = null;

            try {
                order.MustNotBeNull("order");
                request.MustNotBeNull("request");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("sharedSecret", "settings");

                IConnector  connector   = Connector.Create(settings["sharedSecret"]);
                KlarnaOrder klarnaOrder = new KlarnaOrder(connector, new Uri(order.Properties["klarnaLocation"]))
                {
                    ContentType = KlarnaApiRequestContentType
                };
                klarnaOrder.Fetch();

                if ((string)klarnaOrder.GetValue("status") == "checkout_complete")
                {
                    //We need to populate the order with the information entered into Klarna.
                    SaveOrderPropertiesFromKlarnaCallback(order, klarnaOrder);

                    decimal amount   = ((JObject)klarnaOrder.GetValue("cart"))["total_price_including_tax"].Value <decimal>() / 100M;
                    string  klarnaId = klarnaOrder.GetValue("id").ToString();

                    callbackInfo = new CallbackInfo(amount, klarnaId, PaymentState.Authorized);

                    klarnaOrder.Update(new Dictionary <string, object>()
                    {
                        { "status", "created" }
                    });
                }
                else
                {
                    throw new Exception("Trying to process a callback from Klarna with an order that isn't completed");
                }
            } catch (Exception exp) {
                LoggingService.Instance.Error <Klarna>("Klarna(" + order.CartNumber + ") - Process callback", exp);
            }

            return(callbackInfo);
        }
        public bool Update(Uri resourceUri)
        {
            try
            {
                var klarnaOrderId   = _klarnaCheckoutUtils.GetOrderIdFromUri(resourceUri);
                var cart            = _klarnaCheckoutUtils.GetCart();
                var options         = _klarnaCheckoutUtils.GetOptions();
                var connector       = Connector.Create(_klarnaSettings.SharedSecret, BaseUri);
                var supportedLocale = _klarnaCheckoutUtils.GetSupportedLocale();

                var klarnaOrder = new KlarnaCheckoutOrder
                {
                    Cart             = cart,
                    Options          = options,
                    Locale           = supportedLocale.Locale,
                    PurchaseCountry  = supportedLocale.PurchaseCountry,
                    PurchaseCurrency = supportedLocale.PurchaseCurrency
                };

                var order    = new Order(connector, klarnaOrderId);
                var dictData = klarnaOrder.ToDictionary();

                order.Update(dictData);

                return(true);
            }
            catch (Exception ex)
            {
                var exceptionJson = JsonConvert.SerializeObject(ex.Data);

                _logger.Warning(string.Format(CultureInfo.CurrentCulture, "KlarnaCheckout: Error updating Klarna order. Will try to create a new one. ResourceURI: {0}, Data: {1}",
                                              resourceUri, exceptionJson), exception: ex);
            }

            return(false);
        }
        public void Acknowledge(Uri resourceUri, global::Nop.Core.Domain.Orders.Order order)
        {
            try
            {
                var connector = Connector.Create(_klarnaSettings.SharedSecret);
                var klarnaOrder = new Klarna.Checkout.Order(connector, resourceUri)
                {
                    ContentType = ContentType
                };

                klarnaOrder.Fetch();
                var fetchedData = klarnaOrder.Marshal();
                var typedData = KlarnaOrder.FromDictionary(fetchedData);

                if (typedData.Status == KlarnaOrder.StatusCheckoutComplete)
                {
                    var updateData = new KlarnaOrder
                    {
                        Status = KlarnaOrder.StatusCreated,
                        MerchantReference = new MerchantReference
                        {
                            OrderId1 = order.Id.ToString(CultureInfo.InvariantCulture),
                            OrderId2 = order.OrderGuid.ToString()
                        }
                    };

                    var dictData = updateData.ToDictionary();

                    klarnaOrder.Update(dictData);
                }
            }
            catch (Exception ex)
            {
                throw new NopException("Error Acknowledging Klarna Order", ex);
            }
        }
コード例 #7
0
        public override string ProcessRequest(Order order, HttpRequest request, IDictionary <string, string> settings)
        {
            string response = "";

            try {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("sharedSecret", "settings");

                string communicationType = request["communicationType"];

                KlarnaOrder klarnaOrder = null;
                IConnector  connector   = Connector.Create(settings["sharedSecret"]);

                if (communicationType == "checkout")
                {
                    settings.MustContainKey("merchant.id", "settings");
                    settings.MustContainKey("merchant.terms_uri", "settings");
                    settings.MustContainKey("locale", "settings");

                    //Cart information
                    List <Dictionary <string, object> > cartItems = new List <Dictionary <string, object> > {
                        new Dictionary <string, object> {
                            { "reference", settings.ContainsKey("totalSku") ? settings["totalSku"] : "0001" },
                            { "name", settings.ContainsKey("totalName") ? settings["totalName"] : "Total" },
                            { "quantity", 1 },
                            { "unit_price", (int)(order.TotalPrice.Value.WithVat * 100M) },
                            { "tax_rate", 0 }
                        }
                    };

                    Dictionary <string, object> data = new Dictionary <string, object> {
                        { "cart", new Dictionary <string, object> {
                              { "items", cartItems }
                          } }
                    };
                    string klarnaLocation   = order.Properties["klarnaLocation"];
                    string merchantTermsUri = settings["merchant.terms_uri"];

                    if (!merchantTermsUri.StartsWith("http"))
                    {
                        Uri baseUrl = new UriBuilder(HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port).Uri;
                        merchantTermsUri = new Uri(baseUrl, merchantTermsUri).AbsoluteUri;
                    }

                    //Merchant information
                    data["merchant"] = new Dictionary <string, object> {
                        { "id", settings["merchant.id"] },
                        { "terms_uri", merchantTermsUri },
                        { "checkout_uri", request.UrlReferrer.ToString() },
                        { "confirmation_uri", order.Properties["teaCommerceContinueUrl"] },
                        { "push_uri", order.Properties["teaCommerceCallbackUrl"] }
                    };

                    data["merchant_reference"] = new Dictionary <string, object>()
                    {
                        { "orderid1", order.CartNumber }
                    };

                    //Combined data
                    Currency currency = CurrencyService.Instance.Get(order.StoreId, order.CurrencyId);

                    //If the currency is not a valid iso4217 currency then throw an error
                    if (!Iso4217CurrencyCodes.ContainsKey(currency.IsoCode))
                    {
                        throw new Exception("You must specify an ISO 4217 currency code for the " + currency.Name + " currency");
                    }

                    data["purchase_country"]  = CountryService.Instance.Get(order.StoreId, order.PaymentInformation.CountryId).RegionCode;
                    data["purchase_currency"] = currency.IsoCode;
                    data["locale"]            = settings["locale"];

                    //Check if the order has a Klarna location URI property - then we try and update the order
                    if (!string.IsNullOrEmpty(klarnaLocation))
                    {
                        try {
                            klarnaOrder = new KlarnaOrder(connector, new Uri(klarnaLocation))
                            {
                                ContentType = KlarnaApiRequestContentType
                            };
                            klarnaOrder.Fetch();
                            klarnaOrder.Update(data);
                        } catch (Exception) {
                            //Klarna cart session has expired and we make sure to remove the Klarna location URI property
                            klarnaOrder = null;
                        }
                    }

                    //If no Klarna order was found to update or the session expired - then create new Klarna order
                    if (klarnaOrder == null)
                    {
                        klarnaOrder = new KlarnaOrder(connector)
                        {
                            BaseUri     = settings.ContainsKey("testMode") && settings["testMode"] == "1" ? new Uri("https://checkout.testdrive.klarna.com/checkout/orders") : new Uri("https://checkout.klarna.com/checkout/orders"),
                            ContentType = KlarnaApiRequestContentType
                        };

                        //Create new order
                        klarnaOrder.Create(data);
                        klarnaOrder.Fetch();
                        order.Properties.AddOrUpdate(new CustomProperty("klarnaLocation", klarnaOrder.Location.ToString())
                        {
                            ServerSideOnly = true
                        });
                        order.Save();
                    }
                }
                else if (communicationType == "confirmation")
                {
                    //get confirmation response
                    string klarnaLocation = order.Properties["klarnaLocation"];

                    if (!string.IsNullOrEmpty(klarnaLocation))
                    {
                        //Fetch and show confirmation page if status is not checkout_incomplete
                        klarnaOrder = new KlarnaOrder(connector, new Uri(klarnaLocation))
                        {
                            ContentType = KlarnaApiRequestContentType
                        };
                        klarnaOrder.Fetch();

                        if ((string)klarnaOrder.GetValue("status") == "checkout_incomplete")
                        {
                            throw new Exception("Confirmation page reached without a Klarna order that is finished");
                        }
                    }
                }

                //Get the JavaScript snippet from the Klarna order
                if (klarnaOrder != null)
                {
                    JObject guiElement = klarnaOrder.GetValue("gui") as JObject;
                    if (guiElement != null)
                    {
                        response = guiElement["snippet"].ToString();
                    }
                }
            } catch (Exception exp) {
                LoggingService.Instance.Error <Klarna>("Klarna(" + order.CartNumber + ") - ProcessRequest", exp);
            }

            return(response);
        }
コード例 #8
0
        protected virtual void SaveOrderPropertiesFromKlarnaCallback(Order order, KlarnaOrder klarnaOrder)
        {
            //Some order properties in Tea Commerce comes with a special alias,
            //defining a mapping of klarna propteries to these aliases.
            Store store = StoreService.Instance.Get(order.StoreId);
            Dictionary <string, string> magicOrderPropertyAliases = new Dictionary <string, string> {
                { "billing_address.given_name", Constants.OrderPropertyAliases.FirstNamePropertyAlias },
                { "billing_address.family_name", Constants.OrderPropertyAliases.LastNamePropertyAlias },
                { "billing_address.email", Constants.OrderPropertyAliases.EmailPropertyAlias },
            };


            //The klarna properties we wish to save on the order.

            List <string> klarnaPropertyAliases = new List <string> {
                "billing_address.given_name",
                "billing_address.family_name",
                "billing_address.care_of",
                "billing_address.street_address",
                "billing_address.postal_code",
                "billing_address.city",
                "billing_address.email",
                "billing_address.phone",
                "shipping_address.given_name",
                "shipping_address.family_name",
                "shipping_address.care_of",
                "shipping_address.street_address",
                "shipping_address.postal_code",
                "shipping_address.city",
                "shipping_address.email",
                "shipping_address.phone",
            };

            Dictionary <string, object> klarnaProperties = klarnaOrder.Marshal();

            foreach (string klarnaPropertyAlias in klarnaPropertyAliases)
            {
                //if a property mapping exists then use the magic alias, otherwise use the property name itself.
                string tcOrderPropertyAlias = magicOrderPropertyAliases.ContainsKey(klarnaPropertyAlias) ? magicOrderPropertyAliases[klarnaPropertyAlias] : klarnaPropertyAlias;

                string klarnaPropertyValue = "";

                /* Some klarna properties are of the form parent.child
                 * in which case the lookup in klarnaProperties
                 * needs to be (in pseudocode)
                 * klarnaProperties[parent].getValue(child) .
                 * In the case that there is no '.' we assume that
                 * klarnaProperties[klarnaPropertyAlias].ToString()
                 * contains what we need.
                 */
                string[] klarnaPropertyParts = klarnaPropertyAlias.Split('.');
                if (klarnaPropertyParts.Length == 1 && klarnaProperties.ContainsKey(klarnaPropertyAlias))
                {
                    klarnaPropertyValue = klarnaProperties[klarnaPropertyAlias].ToString();
                }
                else if (klarnaPropertyParts.Length == 2 && klarnaProperties.ContainsKey(klarnaPropertyParts[0]))
                {
                    JObject parent = klarnaProperties[klarnaPropertyParts[0]] as JObject;
                    if (parent != null)
                    {
                        JToken value = parent.GetValue(klarnaPropertyParts[1]);
                        klarnaPropertyValue = value != null?value.ToString() : "";
                    }
                }

                if (!string.IsNullOrEmpty(klarnaPropertyValue))
                {
                    order.Properties.AddOrUpdate(tcOrderPropertyAlias, klarnaPropertyValue);
                }
            }
            // order was passed as reference and updated. Saving it now.
            order.Save();
        }
コード例 #9
0
ファイル: Klarna.cs プロジェクト: EtchUK/Payment-providers
        protected virtual void SaveOrderPropertiesFromKlarnaCallback( Order order, KlarnaOrder klarnaOrder )
        {
            //Some order properties in Tea Commerce comes with a special alias,
              //defining a mapping of klarna propteries to these aliases.
              Store store = StoreService.Instance.Get( order.StoreId );
              Dictionary<string, string> magicOrderPropertyAliases = new Dictionary<string, string>{
            { "billing_address.given_name", Constants.OrderPropertyAliases.FirstNamePropertyAlias },
            { "billing_address.family_name", Constants.OrderPropertyAliases.LastNamePropertyAlias },
            { "billing_address.email", Constants.OrderPropertyAliases.EmailPropertyAlias },
              };

              //The klarna properties we wish to save on the order.

              List<string> klarnaPropertyAliases = new List<string>{
            "billing_address.given_name",
            "billing_address.family_name",
            "billing_address.care_of",
            "billing_address.street_address",
            "billing_address.postal_code",
            "billing_address.city",
            "billing_address.email",
            "billing_address.phone",
            "shipping_address.given_name",
            "shipping_address.family_name",
            "shipping_address.care_of",
            "shipping_address.street_address",
            "shipping_address.postal_code",
            "shipping_address.city",
            "shipping_address.email",
            "shipping_address.phone" ,
              };

              Dictionary<string, object> klarnaProperties = klarnaOrder.Marshal();

              foreach ( string klarnaPropertyAlias in klarnaPropertyAliases ) {
            //if a property mapping exists then use the magic alias, otherwise use the property name itself.
            string tcOrderPropertyAlias = magicOrderPropertyAliases.ContainsKey( klarnaPropertyAlias ) ? magicOrderPropertyAliases[ klarnaPropertyAlias ] : klarnaPropertyAlias;

            string klarnaPropertyValue = "";
            /* Some klarna properties are of the form parent.child
             * in which case the lookup in klarnaProperties
             * needs to be (in pseudocode)
             * klarnaProperties[parent].getValue(child) .
             * In the case that there is no '.' we assume that
             * klarnaProperties[klarnaPropertyAlias].ToString()
             * contains what we need.
             */
            string[] klarnaPropertyParts = klarnaPropertyAlias.Split( '.' );
            if ( klarnaPropertyParts.Length == 1 && klarnaProperties.ContainsKey( klarnaPropertyAlias ) ) {
              klarnaPropertyValue = klarnaProperties[ klarnaPropertyAlias ].ToString();
            } else if ( klarnaPropertyParts.Length == 2 && klarnaProperties.ContainsKey( klarnaPropertyParts[ 0 ] ) ) {
              JObject parent = klarnaProperties[ klarnaPropertyParts[ 0 ] ] as JObject;
              if ( parent != null ) {
            JToken value = parent.GetValue( klarnaPropertyParts[ 1 ] );
            klarnaPropertyValue = value != null ? value.ToString() : "";
              }
            }

            if ( !string.IsNullOrEmpty( klarnaPropertyValue ) ) {
              order.Properties.AddOrUpdate( tcOrderPropertyAlias, klarnaPropertyValue );
            }
              }
              // order was passed as reference and updated. Saving it now.
              order.Save();
        }
コード例 #10
0
ファイル: Klarna.cs プロジェクト: EtchUK/Payment-providers
        public override string ProcessRequest( Order order, HttpRequest request, IDictionary<string, string> settings )
        {
            string response = "";

              try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "sharedSecret", "settings" );

            string communicationType = request[ "communicationType" ];

            KlarnaOrder klarnaOrder = null;
            IConnector connector = Connector.Create( settings[ "sharedSecret" ] );

            if ( communicationType == "checkout" ) {
              settings.MustContainKey( "merchant.id", "settings" );
              settings.MustContainKey( "merchant.terms_uri", "settings" );
              settings.MustContainKey( "locale", "settings" );

              //Cart information
              List<Dictionary<string, object>> cartItems = new List<Dictionary<string, object>> {
            new Dictionary<string, object> {
              {"reference", settings.ContainsKey( "totalSku" ) ? settings[ "totalSku" ] : "0001"},
              {"name", settings.ContainsKey( "totalName" ) ? settings[ "totalName" ] : "Total"},
              {"quantity", 1},
              {"unit_price", (int) ( order.TotalPrice.Value.WithVat*100M )},
              {"tax_rate", 0}
            }
              };

              Dictionary<string, object> data = new Dictionary<string, object> { { "cart", new Dictionary<string, object> { { "items", cartItems } } } };
              string klarnaLocation = order.Properties[ "klarnaLocation" ];
              string merchantTermsUri = settings[ "merchant.terms_uri" ];

              if ( !merchantTermsUri.StartsWith( "http" ) ) {
            Uri baseUrl = new UriBuilder( HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port ).Uri;
            merchantTermsUri = new Uri( baseUrl, merchantTermsUri ).AbsoluteUri;
              }

              //Merchant information
              data[ "merchant" ] = new Dictionary<string, object> {
              {"id", settings[ "merchant.id" ]},
              {"terms_uri", merchantTermsUri},
              {"checkout_uri", request.UrlReferrer.ToString()},
              {"confirmation_uri", order.Properties[ "teaCommerceContinueUrl" ]},
              {"push_uri", order.Properties[ "teaCommerceCallbackUrl" ]}
            };

              data[ "merchant_reference" ] = new Dictionary<string, object>() {
              {"orderid1", order.CartNumber}
            };

              //Combined data
              Currency currency = CurrencyService.Instance.Get( order.StoreId, order.CurrencyId );

              //If the currency is not a valid iso4217 currency then throw an error
              if ( !Iso4217CurrencyCodes.ContainsKey( currency.IsoCode ) ) {
            throw new Exception( "You must specify an ISO 4217 currency code for the " + currency.Name + " currency" );
              }

              data[ "purchase_country" ] = CountryService.Instance.Get( order.StoreId, order.PaymentInformation.CountryId ).RegionCode;
              data[ "purchase_currency" ] = currency.IsoCode;
              data[ "locale" ] = settings[ "locale" ];

              //Check if the order has a Klarna location URI property - then we try and update the order
              if ( !string.IsNullOrEmpty( klarnaLocation ) ) {
            try {
              klarnaOrder = new KlarnaOrder( connector, new Uri( klarnaLocation ) ) {
                ContentType = KlarnaApiRequestContentType
              };
              klarnaOrder.Fetch();
              klarnaOrder.Update( data );
            } catch ( Exception ) {
              //Klarna cart session has expired and we make sure to remove the Klarna location URI property
              klarnaOrder = null;
            }
              }

              //If no Klarna order was found to update or the session expired - then create new Klarna order
              if ( klarnaOrder == null ) {
            klarnaOrder = new KlarnaOrder( connector ) {
              BaseUri = settings.ContainsKey( "testMode" ) && settings[ "testMode" ] == "1" ? new Uri( "https://checkout.testdrive.klarna.com/checkout/orders" ) : new Uri( "https://checkout.klarna.com/checkout/orders" ),
              ContentType = KlarnaApiRequestContentType
            };

            //Create new order
            klarnaOrder.Create( data );
            klarnaOrder.Fetch();
            order.Properties.AddOrUpdate( new CustomProperty( "klarnaLocation", klarnaOrder.Location.ToString() ) { ServerSideOnly = true } );
            order.Save();
              }
            } else if ( communicationType == "confirmation" ) {
              //get confirmation response
              string klarnaLocation = order.Properties[ "klarnaLocation" ];

              if ( !string.IsNullOrEmpty( klarnaLocation ) ) {
            //Fetch and show confirmation page if status is not checkout_incomplete
            klarnaOrder = new KlarnaOrder( connector, new Uri( klarnaLocation ) ) {
              ContentType = KlarnaApiRequestContentType
            };
            klarnaOrder.Fetch();

            if ( (string)klarnaOrder.GetValue( "status" ) == "checkout_incomplete" ) {
              throw new Exception( "Confirmation page reached without a Klarna order that is finished" );
            }
              }
            }

            //Get the JavaScript snippet from the Klarna order
            if ( klarnaOrder != null ) {
              JObject guiElement = klarnaOrder.GetValue( "gui" ) as JObject;
              if ( guiElement != null ) {
            response = guiElement[ "snippet" ].ToString();
              }
            }

              } catch ( Exception exp ) {
            LoggingService.Instance.Error<Klarna>( "Klarna(" + order.CartNumber + ") - ProcessRequest", exp );
              }

              return response;
        }
コード例 #11
0
ファイル: Klarna.cs プロジェクト: EtchUK/Payment-providers
        public override CallbackInfo ProcessCallback( Order order, HttpRequest request, IDictionary<string, string> settings )
        {
            CallbackInfo callbackInfo = null;

              try {
            order.MustNotBeNull( "order" );
            request.MustNotBeNull( "request" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "sharedSecret", "settings" );

            IConnector connector = Connector.Create( settings[ "sharedSecret" ] );
            KlarnaOrder klarnaOrder = new KlarnaOrder( connector, new Uri( order.Properties[ "klarnaLocation" ] ) ) {
              ContentType = KlarnaApiRequestContentType
            };
            klarnaOrder.Fetch();

            if ( (string)klarnaOrder.GetValue( "status" ) == "checkout_complete" ) {

              //We need to populate the order with the information entered into Klarna.
              SaveOrderPropertiesFromKlarnaCallback( order, klarnaOrder );

              decimal amount = ( (JObject)klarnaOrder.GetValue( "cart" ) )[ "total_price_including_tax" ].Value<decimal>() / 100M;
              string klarnaId = klarnaOrder.GetValue( "id" ).ToString();

              callbackInfo = new CallbackInfo( amount, klarnaId, PaymentState.Authorized );

              klarnaOrder.Update( new Dictionary<string, object>() { { "status", "created" } } );
            } else {
              throw new Exception( "Trying to process a callback from Klarna with an order that isn't completed" );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Error<Klarna>( "Klarna(" + order.CartNumber + ") - Process callback", exp );
              }

              return callbackInfo;
        }
コード例 #12
0
		public override CaptureProcessPaymentResult CaptureProcessPayment(CaptureProcessPaymentEvaluationContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");
			if (context.Payment == null)
				throw new ArgumentNullException("context.Payment");

			var retVal = new CaptureProcessPaymentResult();

			Uri resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.Payment.OuterId));
			var connector = Connector.Create(AppSecret);
			Order order = new Order(connector, resourceUri)
			{
				ContentType = _contentType
			};
			order.Fetch();

			var reservation = order.GetValue("reservation") as string;
			if (!string.IsNullOrEmpty(reservation))
			{
				try
				{
					Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
					{
						Eid = Convert.ToInt32(AppKey),
						Secret = AppSecret,
						IsLiveMode = false
					};
					Api.Api api = new Api.Api(configuration);
					var response = api.Activate(reservation);

					retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Paid;
					context.Payment.CapturedDate = DateTime.UtcNow;
					context.Payment.IsApproved = true;
					retVal.IsSuccess = true;
					retVal.OuterId = context.Payment.OuterId = response.InvoiceNumber;
				}
				catch(Exception ex)
				{
					retVal.ErrorMessage = ex.Message;
				}
			}
			else
			{
				retVal.ErrorMessage = "No reservation for this order";
			}

			return retVal;
		}
コード例 #13
0
        //Klarna
        public ViewResult ThankYou(string klarna_order_id)
        {
            var connector = Connector.Create("Y7mNXnxIdYxXU6c", Connector.TestBaseUri);

            Order order = new Order(connector, klarna_order_id);

            order.Fetch();

            var gui = order.GetValue("gui") as JObject;
            var snippet = gui["snippet"];
            return View(snippet);
        }
        public Order Fetch(Uri resourceUri)
        {
            var connector = Connector.Create(_klarnaSettings.SharedSecret);
            var order = new Klarna.Checkout.Order(connector, resourceUri)
            {
                ContentType = ContentType
            };

            order.Fetch();

            return order;
        }
コード例 #15
0
		private PostProcessPaymentResult PostProcessKlarnaOrder(PostProcessPaymentEvaluationContext context)
		{
			var retVal = new PostProcessPaymentResult();

			Uri resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.OuterId));

			var connector = Connector.Create(AppSecret);

			Order order = new Order(connector, resourceUri)
			{
				ContentType = _contentType
			};

			order.Fetch();
			var status = order.GetValue("status") as string;

			if (status == "checkout_complete")
			{
				var data = new Dictionary<string, object> { { "status", "created" } };
				order.Update(data);
				order.Fetch();
				status = order.GetValue("status") as string;
			}

			if (status == "created" && IsSale())
			{
				var result = CaptureProcessPayment(new CaptureProcessPaymentEvaluationContext { Payment = context.Payment });

				retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Paid;
				context.Payment.OuterId = retVal.OuterId;
				context.Payment.IsApproved = true;
				context.Payment.CapturedDate = DateTime.UtcNow;
				retVal.IsSuccess = true;
			}
			else if (status == "created")
			{
				retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Authorized;
				context.Payment.OuterId = retVal.OuterId = context.OuterId;
				context.Payment.AuthorizedDate = DateTime.UtcNow;
				retVal.IsSuccess = true;
			}
			else
			{
				retVal.ErrorMessage = "order not created";
			}

			retVal.OrderId = context.Order.Id;

			return retVal;
		}
コード例 #16
0
		private ProcessPaymentResult ProcessKlarnaOrder(KlarnaLocalization localization, ProcessPaymentEvaluationContext context)
		{
			var retVal = new ProcessPaymentResult();

			var cartItems = CreateKlarnaCartItems(context.Order);

			//Create cart
			var cart = new Dictionary<string, object> { { "items", cartItems } };
			var data = new Dictionary<string, object>
					{
						{ "cart", cart }
					};

			//Create klarna order "http://example.com" context.Store.Url
			var connector = Connector.Create(AppSecret);
			Order order = null;
			var merchant = new Dictionary<string, object>
					{
						{ "id", AppKey },
						{ "terms_uri", string.Format("{0}/{1}", context.Store.Url, TermsUrl) },
						{ "checkout_uri", string.Format("{0}/{1}", context.Store.Url, CheckoutUrl) },
						{ "confirmation_uri", string.Format("{0}/{1}?sid=123&orderId={2}&", context.Store.Url, ConfirmationUrl, context.Order.Id) + "klarna_order={checkout.order.uri}" },
						{ "push_uri", string.Format("{0}/{1}?sid=123&orderId={2}&", context.Store.Url, "admin/api/paymentcallback", context.Order.Id) + "klarna_order={checkout.order.uri}" },
						{ "back_to_store_uri", context.Store.Url }
					};

			var layout = new Dictionary<string, object>
					{
						{ "layout", "desktop" }
					};

			data.Add("purchase_country", localization.CountryName);
			data.Add("purchase_currency", localization.Currency);
			data.Add("locale", localization.Locale);
			data.Add("merchant", merchant);
			data.Add("gui", layout);

			order =
				new Order(connector)
				{
					BaseUri = new Uri(GetCheckoutBaseUrl(localization.Currency)),
					ContentType = _contentType
				};
			order.Create(data);
			order.Fetch();

			//Gets snippet
			var gui = order.GetValue("gui") as JObject;
			var html = gui["snippet"].Value<string>();

			retVal.IsSuccess = true;
			retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Pending;
			retVal.HtmlForm = html;
			retVal.OuterId = context.Payment.OuterId = order.GetValue("id") as string;

			return retVal;
		}
コード例 #17
0
		public override VoidProcessPaymentResult VoidProcessPayment(VoidProcessPaymentEvaluationContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");
			if (context.Payment == null)
				throw new ArgumentNullException("context.Payment");

			var retVal = new VoidProcessPaymentResult();

			if (!context.Payment.IsApproved && (context.Payment.PaymentStatus == PaymentStatus.Authorized || context.Payment.PaymentStatus == PaymentStatus.Cancelled))
			{
				Uri resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.Payment.OuterId));
				var connector = Connector.Create(AppSecret);
				Order order = new Order(connector, resourceUri)
				{
					ContentType = _contentType
				};
				order.Fetch();

				var reservation = order.GetValue("reservation") as string;
				if (!string.IsNullOrEmpty(reservation))
				{
					try
					{
						Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
						{
							Eid = Convert.ToInt32(AppKey),
							Secret = AppSecret,
							IsLiveMode = false
						};
						Api.Api api = new Api.Api(configuration);
						var result = api.CancelReservation(reservation);
						if (result)
						{
							retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Voided;
							context.Payment.VoidedDate = context.Payment.CancelledDate = DateTime.UtcNow;
							context.Payment.IsCancelled = true;
							retVal.IsSuccess = true;
						}
						else
						{
							retVal.ErrorMessage = "Payment was not canceled, try later";
						}
					}
					catch(Exception ex)
					{
						retVal.ErrorMessage = ex.Message;
					}
				}
			}
			else if(context.Payment.IsApproved)
			{
				retVal.ErrorMessage = "Payment already approved, use refund";
				retVal.NewPaymentStatus = PaymentStatus.Paid;
			}
			else if(context.Payment.IsCancelled)
			{
				retVal.ErrorMessage = "Payment already canceled";
				retVal.NewPaymentStatus = PaymentStatus.Voided;
			}

			return retVal;
		}
コード例 #18
0
ファイル: CartController.cs プロジェクト: kappsegla/Products
        public ViewResult Checkout(Cart cart)
        {
            var cartItems = new List<Dictionary<string, object>>();

                foreach(CartLine item in cart.Lines)
                {
                cartItems.Add(new Dictionary<string, object>
                    {
                        { "reference", item.Product.ArticleNumber.ToString() },
                        { "name", item.Product.Name },
                        { "quantity", item.Quantity },
                        { "unit_price", (int)item.Product.Price * 100 },
                        { "tax_rate", 2500 }
                    });
                }
            cartItems.Add(
            new Dictionary<string, object>
                {
                    { "type", "shipping_fee" },
                    { "reference", "SHIPPING" },
                    { "name", "Shipping Fee" },
                    { "quantity", 1 },
                    { "unit_price", 4900 },
                    { "tax_rate", 2500 }
                });

            var cart_info = new Dictionary<string, object> { { "items", cartItems } };

            var data = new Dictionary<string, object>
            {
                { "cart", cart_info }
            };

            var merchant = new Dictionary<string, object>
            {
               { "id", "5160" },
               { "back_to_store_uri", "http://127.0.0.1:53284/" },
               { "terms_uri", "http://127.0.0.1:53284/Cart/Terms" },
            {
                "checkout_uri",
                "http://127.0.0.1:53284/sv/Cart/Checkout"
            },
            {
                "confirmation_uri",
                "http://127.0.0.1:53284/sv/Cart/OrderConfirmed" +
                "?klarna_order_id={checkout.order.id}"
            },
            {
                "push_uri",
                "https://snowroller.azurewebsites.net/Home/Callback" +
                "?secret="+Shared_Secret+"&klarna_order_id={checkout.order.id}"
            }
             };
            data.Add("purchase_country", "SE");
            data.Add("purchase_currency", "SEK");
            data.Add("locale", "sv-se");
            data.Add("merchant", merchant);

            var connector = Connector.Create(Shared_Secret, Connector.TestBaseUri);
            Order order = new Order(connector);
            order.Create(data);

            order.Fetch();

            // Store order id of checkout in session object.
            Session.Add("klarna_order_id", order.GetValue("id"));

            // Display checkout
            var gui = order.GetValue("gui") as JObject;
            var snippet = gui["snippet"];

            return View(snippet);
        }
        public Uri Create()
        {
            var cart = _klarnaCheckoutUtils.GetCart();
            var merchant = _klarnaCheckoutUtils.GetMerchant();
            var supportedLocale = _klarnaCheckoutUtils.GetSupportedLocale();
            var gui = _klarnaCheckoutUtils.GetGui();
            var options = _klarnaCheckoutUtils.GetOptions();

            var klarnaOrder = new KlarnaOrder
            {
                Cart = cart,
                Merchant = merchant,
                Gui = gui,
                Options = options,
                Locale = supportedLocale.Locale,
                PurchaseCountry = supportedLocale.PurchaseCountry,
                PurchaseCurrency = supportedLocale.PurchaseCurrency
            };

            var dictData = klarnaOrder.ToDictionary();
            var connector = Connector.Create(_klarnaSettings.SharedSecret);
            var order = new Klarna.Checkout.Order(connector)
            {
                BaseUri = new Uri(BaseUri),
                ContentType = ContentType
            };

            order.Create(dictData);

            var location = order.Location;

            var kcoOrderRequest = GetKcoOrderRequest(_workContext.CurrentCustomer, location);
            _klarnaRepository.Insert(kcoOrderRequest);

            return location;
        }
コード例 #20
0
		private PostProcessPaymentResult OldRegisterKlarnaOrder(PostProcessPaymentEvaluationContext context)
		{
			var retVal = new PostProcessPaymentResult();

			Uri resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.OuterId));

			var connector = Connector.Create(AppSecret);

			Order order = new Order(connector, resourceUri)
			{
				ContentType = _contentType
			};

			order.Fetch();
			var status = order.GetValue("status") as string;

			if (status == "checkout_complete")
			{
				var data = new Dictionary<string, object> { { "status", "created" } };
				order.Update(data);
				order.Fetch();
				status = order.GetValue("status") as string;
			}

			if (status == "created")
			{
				var reservation = order.GetValue("reservation") as string;

				if (!string.IsNullOrEmpty(reservation))
				{
					Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
					{
						Eid = Convert.ToInt32(AppKey),
						Secret = AppSecret,
						IsLiveMode = false
					};

					Api.Api api = new Api.Api(configuration);

					var response = api.Activate(reservation);

					order.Fetch();

					var klarnaCart = order.GetValue("cart") as JObject;
				}
			}

			retVal.IsSuccess = status == "created";
			retVal.NewPaymentStatus = retVal.IsSuccess ? PaymentStatus.Paid : PaymentStatus.Pending;
			retVal.OrderId = context.Order.Id;

			return retVal;
		}
        public bool Update(Uri resourceUri)
        {
            try
            {
                var klarnaOrderId = _klarnaCheckoutUtils.GetOrderIdFromUri(resourceUri);
                var cart = _klarnaCheckoutUtils.GetCart();
                var options = _klarnaCheckoutUtils.GetOptions();
                var connector = Connector.Create(_klarnaSettings.SharedSecret, BaseUri);
                var supportedLocale = _klarnaCheckoutUtils.GetSupportedLocale();

                var klarnaOrder = new KlarnaCheckoutOrder
                {
                    Cart = cart,
                    Options = options,
                    Locale = supportedLocale.Locale,
                    PurchaseCountry = supportedLocale.PurchaseCountry,
                    PurchaseCurrency = supportedLocale.PurchaseCurrency
                };

                var order = new Order(connector, klarnaOrderId);
                var dictData = klarnaOrder.ToDictionary();

                order.Update(dictData);

                return true;
            }
            catch (Exception ex)
            {
                var exceptionJson = JsonConvert.SerializeObject(ex.Data);

                _logger.Warning(string.Format(CultureInfo.CurrentCulture, "KlarnaCheckout: Error updating Klarna order. Will try to create a new one. ResourceURI: {0}, Data: {1}",
                    resourceUri, exceptionJson), exception: ex);
            }

            return false;
        }
コード例 #22
0
ファイル: CartController.cs プロジェクト: kappsegla/Products
        public ViewResult OrderConfirmed(string klarna_order_id)
        {
            var connector = Connector.Create(Shared_Secret, Connector.TestBaseUri);

            var order = new Order(connector, klarna_order_id);

            order.Fetch();

            var gui = order.GetValue("gui") as JObject;
            var snippet = gui["snippet"];

            // Clear session object.
             Session["klarna_order_id"] = null;

            return View(snippet);
        }