/// <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) { } }
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 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); }
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; }
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); } }
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 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; }