Adding Klarna payments to your application is as easy as adding a view and performing the payment operations on it.
![]() | ![]() | ![]() | ![]() |
Your native checkout screen in default state. | Your native checkout screen when Klarna is selected as payment method. | Klarna purchase flow starts when customer confirms to Continue with Klarna. | Your native order confirmation screen after a successful payment. |
client_token
to your app.When you integrate Klarna payments into your online store, your customers see Klarna as an option when they select a payment method for their purchases. If your customers select Klarna for their purchase, they are redirected to log into their Klarna account.
Your customers select their preferred Klarna payment option (pay now, pay later, pay in parts) once they're logged into their Klarna account. We handle the Klarna account user flow, so you don't have to worry about it.
We understand that checkout flows are designed differently according to each store's needs. For this reason, we have some recommendations in our Klarna payments integration best practices guide so that you can leverage the Klarna payments product for your business.
Before you start integrating Klarna payments, there are a few things you need to prepare in advance:
When your customer wants to pay with Klarna, you have to open a payment session and share the shopping cart details in a POST
request to the {apiURL}/payments/v1/sessions
endpoint. In that request, you also specify if the payment is one-time or recurring.
Once you start a payment session, it stays open for 48 hours or until you place an order. You can also send a separate POST
request to cancel the session.
Klarna payments API uses HTTP basic authentication. To authenticate, use your API credentials that consist of:
If you're using an API platform that lets you store your credentials, you can add them in relevant fields. Otherwise, make sure to include the Base64-encoded username:password in the Authorization header field of each API request, as shown below.
Authorization: Basic pwhcueUff0MmwLShJiBE9JHA==
A sample authorization request header with Base64-encoded credentials.
To get a success response, include the following required parameters in your POST {apiURL}/payments/v1/sessions
request.
Parameter | Description |
---|---|
locale | The language of information presented on the Klarna widget. Learn more about using locale in API calls. |
purchase_country | The country where the purchase is made. Learn more about supported countries. |
purchase_currency | The currency in which the customer is charged. Learn more about supported currencies. |
order_amount | The total price of the order, including tax and discounts. |
order_lines | The details of order lines in the purchase. |
intent | The purpose of the payment session. |
merchant_urls.authorization | Get a callback once the customer has completed the flow and you can create an order. |
In response to a create session call, you receive:
session_id
, a payment session identifier you can use to [ update the session] and [ retrieve session] detailsclient_token
, a token you pass to the JavaScript SDK or Mobile SDK(Android, iOS and React Native) to launch the Klarna widgetpayment_method_categories
, an array that lists the grouped Klarna payment methods available for the session. We can respond with one or more categories depending on the market and account configuration.{
"session_id": "068df369-13a7-4d47-a564-62f8408bb760",
"client_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjAwMDAwMDAwMDAtMDAwMDAtMDAwMC0wMDAwMDAwMC0wMDAwIiwidXJsIjoiaHR0cHM6Ly9jcmVkaXQtZXUua2xhcm5hLmNvbSJ9.A_rHWMSXQN2NRNGYTREBTkGwYwtm-sulkSDMvlJL87M",
"payment_method_categories": [
{
"identifier": "klarna"
"name" : "Pay with Klarna",
"asset_urls" : {
"descriptive" : "https://x.klarnacdn.net/payment-method/assets/badges/generic/klarna.svg",
"standard" : "https://x.klarnacdn.net/payment-method/assets/badges/generic/klarna.svg"
A sample success response to the create session call.
If your request doesn't pass our validation, you'll receive an error response.
{
"correlation_id": "6a9b1cb1-73a3-4936-a030-481ba4bb203b",
"error_code": "BAD_VALUE",
"error_messages": [
"Bad value: order_lines"
]
}
A sample error response caused by incorrect order line details.
Go to Error Handling to learn more about common errors and troubleshooting suggestions. You can use the value in correlation_id
to find entries related to the request under Logs in the Merchant portal.
In Xcode, navigate to File → Swift Packages → Add Package Dependency and enter the repository URL: https://github.com/klarna/klarna-mobile-sdk-spm
In Version, Select Up to Next Major and take the default option. Then choose KlarnaMobileSDK
in the Package Product column.
If you’re using Cocoapods, you can add the SDK by adding the dependency to your Podfile:
pod "KlarnaMobileSDK"
Followed by performing:
pod install
You should then be able to import the KlarnaMobileSDK
module in your workspace.
If you’re using Carthage, you can add the SDK to your Cartfile as below:
binary "https://raw.githubusercontent.com/klarna/klarna-mobile-sdk/master/KlarnaMobileSDK.json"
Followed by performing:
carthage update --use-xcframeworks
You should be then able to add the XCFramework
to your project.
To read more about Mobile SDK versioning policy, check out this section.
Klarna purchase flows might require authorizations in other applications (e.g. bank apps) or do a handover to the Klarna app. In such cases, a return URL to your application ensures seamless return to the flow in your app, hence setting up a return URL is required. It is expected that redirects to this URL should only open your application without any changes in the UI state, ensuring the customer can continue the flow prior to external navigation.
You can set up a Return URL app scheme to your application by configuring a custom URL scheme.
Important: The return URL string passed to the SDK must include ://
after the scheme name. For example, if you defined myApp
as the scheme, you must use "myApp://"
as the return URL argument to the SDK.
To avoid a Klarna specific app scheme, you can use a host in a common scheme for Klarna redirects, e.g. myApp://klarna-redirect
, this can allow you to differentiate and handle these redirect in your handler.
Considering the return URL is a constant value in Constants.klarnaReturnUrl
, you can handle redirects to your return URL as such:
Klarna flows on mobile utilize Application Queries for Klarna app schemes to offer seamless app handover experience to customers. In order for the SDK to check availability of the Klarna app, we need you to enable querying Klarna app on the device by adding Klarna app schemes to LSApplicationQueriesSchemes.
This can be configured easily in XCode by going to your project setting and under "Info"(alternatively this is also available in your Info.plist
file) you should see an entry list for Queried URL Schemes
, this list should contain the klarna
and klarnaconsent
schemes:
The payment process starts when you create a session towards Klarna. With an active session, you are able to show Klarna as a payment method in your checkout. This session identifies the payment and is unique for the order life cycle.
Creating a session takes place in the server side. You have to send a request to the Klarna payments API. As a response, you get a client_token
(JSON Web Token), useful for the following step.
For more technical details, see Step 1: Initiate a payment from our Klarna Payments server-side documentation.
Payment View is an instance of KlarnaPaymentView
, which is a native view intended to be used natively in your checkout screen.
You can initialize the KlarnaPaymentView
by providing a category, return URL and the event listener.
// Create the view
let paymentView = KlarnaPaymentView.init(category: "klarna", returnUrl: Constants.klarnaReturnUrl, eventListener: self)
// Add as subview
paymentView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(paymentView)
// Create a height constraint that we'll update as its height changes.
self.paymentViewHeightConstraint = paymentView.heightAnchor.constraint(equalToConstant: 0)
paymentViewHeightConstraint.isActive = true
Param | Type | Description |
---|---|---|
category | String | Should always be set to "klarna" as it's the preferred payment category. |
returnUrl | URL | App scheme URL as defined in set up to return from external applications. |
eventListener | KlarnaPaymentEventListener | Listener that receives events during the payment process. It acts like a conventional delegate on iOS, however, unlike a delegate, it’s not optional. |
The payment view does not define any height internally as we want to allow you to handle height changes in whichever way is most convenient to you.
The payment view instead notifies you through KlarnaPaymentEventListener
for you to update it accordingly via klarnaResized
method:
func klarnaResized(paymentView: KlarnaPaymentView, to newHeight: CGFloat) {
self.paymentViewHeightConstraint.constant = newHeight
}
Before content is rendered into a payment view or an authorization, payment session with it's client token needs to be initialized. This can be done by calling initialize
and handling result in klarnaInitialized
.
// initilize with clientToken for session created from server-side
paymentView.initialize(clientToken: clientToken)
If successful, klarnaInitialized
from KlarnaPaymentEventListener
will be called in the listener you supplied. If it’s not successful, klarnaFailed
will be called instead.
func klarnaInitialized(paymentView: KlarnaPaymentView) {
paymentView.load() // optionally load payment widget upon initialize
}
Once you’ve initialized the view and you’re ready to display the payment widget, simply by calling load
.
Displaying the payment widget is optional. If you choose to display it, make sure to it is inline with the payment method and not in a separate screen. If you choose to skip, then continue to authorize instead.
// load optional payment widget
paymentView.load()
Param | Type | Description |
---|---|---|
jsonData | String | An optional string with the order data to update the session. Formatted as JSON. |
Optionally you can provide a string as jsonData
parameter to the load
method with updated order data to update the session. This string should be formatted as valid JSON.
If successful, klarnaLoaded
will be called in KlarnaPaymentEventListener
and for errors klarnaFailed
will be called instead.
func klarnaLoaded(paymentView: KlarnaPaymentView) {
// Content has finished loading and if you have any loader you could hide it here.
}
To learn more about Klarna Payments UX guidelines, check out this section.
![]() | ![]() |
Your native checkout screen before the customer chooses to Continue with Klarna. | Klarna purchase flow after the customer clicked your Continue with Klarna button and you called authorize. |
Once the user has confirmed that they want to pay with Klarna, it’s time to authorize the session. This is done by calling authorize
, and similar to load
, you can supply an optional JSON string with jsonData
parameter to update the session. You can also specify whether auto-finalization should be turned off(on by default) and in that case you might be required to finalize the session after.
// authorize the payment session
paymentView.authorize()
Param | Type | Description |
---|---|---|
autoFinalize | Boolean? | An optional flag used to turn off auto-finalization for direct bank transfer. |
jsonData | String? | An optional string to update the session. Formatted as JSON. |
If successful, klarnaAuthorized
will be called in your KlarnaPaymentEventListener
and for errors klarnaFailed
will be called instead.
func klarnaAuthorized(paymentView: KlarnaPaymentView, approved: Bool, authToken: String?, finalizeRequired: Bool) {
if let token = authToken, approved {
// authorization is successful, backend may create order
}
if finalizeRequired == true {
// finalize() call is required
}
}
Param | Type | Description |
---|---|---|
paymentView | KlarnaPaymentView | The payment view that was authorized. |
approved | Bool | Whether the authorization was approved or not. |
authToken | String? | The token that allows you to place the order. This is only returned if it's an approved authorization. |
finalizedRequired | Bool | Will be true if autoFinalize was false and this payment method needs a second confirmation step. |
This is only needed if you set autoFinalize
to false
in authorize call.
If the session needs to be finalized, you’ll need to perform this last step to get an authorization token, simply call finalise
in order to get the authentication token. Similar to authorize
you can supply an optional JSON string with jsonData
parameter to update the session.
While we tend to name all finalize operations “finalize” with a “z”, all classes subclassing from NSObject already have a a conflicting finalize
method. In this specific case, we use the alternative british-english spelling.
paymentView.finalise()
Param | Type | Description |
---|---|---|
paymentView | KlarnaPaymentView | The payment view that was finalized. |
approved | Bool | Whether the user was approved on finalize or not. |
authToken | String? | If the finalization went through, the token will not be null. |
To continue with the purchase, you have to create an order in Klarna's system. This step takes place in the server side through the Klarna payments API.
Follow create an order documentation for server-side to complete your integration with an order.
This will handle all the errors from the previous implementations. KlarnaPaymentError
will contain the information needed to show to the user and also to handle all the states of the listener.
Param | Type | Description |
---|---|---|
paymentView | KlarnaPaymentView | The payment view that had the error. |
error | KlarnaPaymentError? | lass that contains the information (name , message , isFatal , debugDescription ) about the error. |
func klarnaFailed(inPaymentView paymentView: KlarnaPaymentView, withError error: KlarnaPaymentError) {
if error.name == "InvalidClientTokenError" {
// Client token used to initialize the SDK is invalid.
// Merchant should get a valid client token and use it to initialize the SDK again.
} else if error.name == "ShowFormFalseError" {
// The selected payment method is invalid.
// Merchant should set a valid payment method for SDK and initialize the SDK again.
} else {
// Handle other errors
}
The SDK will log events and errors while it’s running, which you can read in XCode console. You can set the logging level for the SDK through the loggingLevel
property of integration instance.
klarnaPaymentView.loggingLevel = .verbose
Name | Description |
---|---|
KlarnaLoggingLevel.off | Nothing will be logged into console. |
KlarnaLoggingLevel.error | Only errors will be logged into console. |
KlarnaLoggingLevel.verbose | Everything will be logged into console. |
You can enhance your customer experience with other Klarna products from Mobile SDK:
Complete your integration with