Fetch() public méthode

Fetches order data.
public Fetch ( ) : void
Résultat void
        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);
        }
Exemple #2
0
        /// <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)
            {
            }
        }
Exemple #3
0
        /// <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)
            {
            }
        }
Exemple #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 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);
            }
        }
Exemple #6
0
        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);
        }
		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;
		}
        //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 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;
		}
		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;
		}
Exemple #11
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;
        }
Exemple #12
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);
        }
Exemple #13
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;
        }
Exemple #14
0
        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 Order Fetch(Uri resourceUri)
        {
            var connector = Connector.Create(_klarnaSettings.SharedSecret);
            var order = new Klarna.Checkout.Order(connector, resourceUri)
            {
                ContentType = ContentType
            };

            order.Fetch();

            return order;
        }
		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;
		}
		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;
		}