Adding Klarna payments to your application is as easy as adding a view and performing the payment operations on it.
![]() | ![]() | ![]() |
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. |
{{#lst:Prepare your integration web|introduction}}
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 ! style="vertical-align:middle;text-align:center;width:30px;" |Required | 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. |
To open a one-time payment session, include all common parameters in the request body and set intent
to buy
.
{
"acquiring_channel": "ECOMMERCE",
"intent": "buy",
"purchase_country": "SE",
"purchase_currency": "SEK",
"locale": "en-SE",
"order_amount": 9500,
"order_tax_amount": 1900,
"order_lines": [
{
A sample POST
request to create a one-time payment session.
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.
Add the Klarna Mobile SDK maven repository:
Add the SDK as a dependency to your app:
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 read more about how deep links and intent filters work on the Android Developers site.
You can set up a Return URL app scheme for your application by registering an intent-filter
for the Activity you integrated Klarna, in your app’s AndroidManifest.xml
:
<application...>
<activity...>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="<your-custom-scheme>" />
<data android:host="<your-custom-host>" />
</intent-filter>
</activity>
Important: Construct the return URL string passed to Klarna by combining the attributes defined in your <intent-filter>
's <data>
tags, following the standard URL format: <your-custom-scheme>://<your-custom-host>
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
intent?.data?.let { uri ->
if (uri.host == Contants.klarnaReturnUrl.host && uri.host == Contants.klarnaReturnUrl.host) {
// This is a return URL for Klarna – skip deep linking
return
}
// This was not a return URL for Klarna
}
}
The hosting Activity
should be using launchMode
of type singleTask
or singleTop
to prevent a new instance from being created when returning from an external application.
Payment View is an instance of KlarnaPaymentView
, which is a native view intended to be used natively in your checkout screen.
You can add the view to your layout as shown below:
<com.klarna.mobile.sdk.api.payments.KlarnaPaymentView
...
android:id="@+id/paymentView"/>
You should then be able to set up the view in code by setting a category and registering a callback:
val paymentView: KlarnaPaymentView = findViewById(R.id.paymentView)
paymentView.category = "klarna"
paymentView.registerPaymentViewCallback(callback)
If you instead want to create the view in code, you can use its constructor to set it up with a single line.
val paymentView = KlarnaPaymentView(
context = this,
category = "klarna",
callback = callback,
returnURL = Constants.klarnaReturnUrl
)
paymentView.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
view.addView(paymentView)
Param | Type | Description |
---|---|---|
context | Context | The context of the Activity the Payment View is in. |
category | String | Should always be set to "klarna" as it's the preferred payment category. |
callback | KlarnaPaymentViewCallback | Callback interface that receives events during the payment process. |
returnURL | String | URL schema as defined in your AndroidManifest.xml to return from external applications. |
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 onInitialized
.
// initilize with clientToken for session created from server-side
paymentView.initialize(clientToken)
If successful, onInitialized
from KlarnaPaymentViewCallback
will be called in the callback you supplied. If it’s not successful, onErrorOccurred
will be called instead.
override fun onInitialized(view: KlarnaPaymentView) {
view.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 completely optional. If you choose to display it, make sure to it is inline with the payment method and not in a separate screen.
// load optional payment widget
paymentView.load(null)
Param | Type | Description |
---|---|---|
args | String? | An optional string with the order data to update the session. Formatted as JSON. |
Optionally you can provide a string as args parameter to the load
method with updated order data to update the session. This string should be formatted as valid JSON.
If successful, onLoaded
will be called in KlarnaPaymentViewCallback
and for errors onErrorOccurred will be called instead.
override fun onLoaded(view: 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 sessionData 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(sessionData = null)
Param | Type | Description |
---|---|---|
view | KlarnaPaymentView | The payment view that was authorized. |
approved | Boolean | Whether the authorization was approved or not. |
authToken | String? | If the session was authorized, the token will not be null. |
finalizedRequired | Boolean? | 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 finalize
in order to get the authentication token. Similar to authorize
you can supply an optional JSON string with sessionData parameter to update the session.
paymentView.finalize(null)
Param | Type | Description |
---|---|---|
view | KlarnaPaymentView | The payment view that was finalized. |
approved | Boolean | 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.
To create an order for a one-time payment, send a POST
request to the {apiUrl}/payments/v1/authorizations/{authorizationToken}/order
endpoint and include authorization_token
in the path.
For example, if the authorization_token
is b4bd3423-24e3
, send your request to the {apiUrl}/payments/v1/authorizations/b4bd3423-24e3/order
endpoint.
{
"purchase_country": "US",
"purchase_currency": "USD",
"billing_address": {
"given_name": "John",
"family_name": "Doe",
"email": "john@doe.com",
"title": "Mr",
"street_address": "Lombard St 10",
"street_address2": "Apt 214",
A POST
request to create an order for a one-time payment.
When you receive a success response, the customer gets charged and the Klarna payments session is closed.
As part of the response, you receive the following details:
order_id
, an order identifier that you can later use to capture or refund the order using the Order management APIredirect_url
, a URL to which you redirect the customer. This isn't included in the response received if you didn't include the URL when initiating a paymentfraud_status
, an indicator of whether the transaction is suspected to be legitimate or fraudulentauthorized_payment_method
, the payment method selected by your customer for this purchase{
"order_id": "3eaeb557-5e30-47f8-b840-b8d987f5945d",
"redirect_url": "https://payments.klarna.com/redirect/...",
"fraud_status": "ACCEPTED",
"authorized_payment_method": "invoice"
}
A success response to the order creation request for a one-time payment.
Send the customer browser to redirect_url
provided in the response. Klarna places a cookie in the browser and redirects the customer back to the confirmation URL you provided when creating the session. This makes the checkout faster the next time the customer chooses to pay with Klarna.
If your request doesn't pass our validation, you'll receive an error response. The most common reasons why creating an order fails are:
{
"correlation_id": "6a9b1cb1-73a3-4936-a030-481ba4bb203b",
"error_code": "ERROR_CODE",
"error_messages": [
"ERROR_MESSAGE"
]
}
An error response to the order creation request for a one-time payment.
Here are examples of common errors with troubleshooting suggestions. You can use the value in correlation_id
to find entries related to the request under Logs in the Merchant portal.
Error code | Error message | Description |
---|---|---|
NOT_FOUND | Invalid authorization token | The authorization token has expired because the order was placed more than 60 minutes after authorization. To fix the error, request a new authorization_token and use it to place the order. |
BAD_VALUE | Not matching fields: [billing_address.postal_code] | The data shared with Klarna in a previous step (create_session , load() , or authorize() ) have been modified causing the validation to fail. |
BAD_VALUE | Not matching fields: [Incorrect number of items in the cart. Expected: 2, Actual: 3] | The order lines or the cart were updated after the authorize() call. Please ensure that the cart is kept as-is or send a new authorization request. |
REJECTED | Rejected | This is an edge case reason, but can be triggered in case the merchant is configured with being allowed to update the cart. This could be updated from the authorize to the place order in such a way that a new authorize is triggered. In this case this is rejected. |
The SDK will log events and errors while it’s running, which you can read in logcat console. You can set the logging level for the SDK through the loggingLevel
property of integration instance.
klarnaPaymentView.loggingLevel = KlarnaLoggingLevel.Verbose
Value | Description |
---|---|
KlarnaLoggingLevel.Off | No logging |
KlarnaLoggingLevel.Error | Log error messages only |
KlarnaLoggingLevel.Verbose | Log all messages (debug and error) |
You can enhance your customer experience with other Klarna products from Mobile SDK:
Complete your integration with