Native View - Android

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.

Authentication

Klarna payments API uses HTTP basic authentication. To authenticate, use your API credentials that consist of:

  • A username linked to your Klarna merchant ID (MID)
  • A password associated with your username

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.

JSON
Authorization: Basic pwhcueUff0MmwLShJiBE9JHA==

A sample authorization request header with Base64-encoded credentials.

Common Parameters

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
localeThe 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.
intentThe purpose of the payment session.
merchant_urls.authorizationGet 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.

JSON
{
"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.

Success Response

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] details
  • client_token, a token you pass to the JavaScript SDK or Mobile SDK(Android, iOS and React Native) to launch the Klarna widget
  • payment_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.
JSON
{
"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.

Error Response

If your request doesn't pass our validation, you'll receive an error response.

JSON
{
"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 Repository

Add the Klarna Mobile SDK maven repository:

Add the Dependency

Add the SDK as a dependency to your app:

To read more about Mobile SDK versioning policy, check out this section.

Return URL

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:

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>

KOTLIN
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.

Inflate from XML

You can add the view to your layout as shown below:

JSON
<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:

KOTLIN
val paymentView: KlarnaPaymentView = findViewById(R.id.paymentView)
paymentView.category = "klarna"
paymentView.registerPaymentViewCallback(callback)

Create programmatically

If you instead want to create the view in code, you can use its constructor to set it up with a single line.

KOTLIN
val paymentView = KlarnaPaymentView(
   context = this,
   category = "klarna",
   callback = callback,
   returnURL = Constants.klarnaReturnUrl
)
paymentView.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
view.addView(paymentView)
ParamTypeDescription
contextContextThe context of the Activity the Payment View is in.
categoryStringShould always be set to "klarna" as it's the preferred payment category.
callbackKlarnaPaymentViewCallbackCallback interface that receives events during the payment process.
returnURLStringURL 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.

KOTLIN
// 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.

KOTLIN
override fun onInitialized(view: KlarnaPaymentView) {
    view.load() // optionally load payment widget upon initialize
}
  1. Payment Descriptor: Dynamically populated in Klarna Payment session.
  2. Payment Sub header: Added by merchant.
  3. Widget: Dynamically populated in Klarna Payment session.
  4. Klarna Badge: Dynamically populated in Klarna Payment session.

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.

KOTLIN
// load optional payment widget
paymentView.load(null)
ParamTypeDescription
argsString?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.

KOTLIN
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.

KOTLIN
// authorize the payment session
paymentView.authorize(sessionData = null)
ParamTypeDescription
viewKlarnaPaymentViewThe payment view that was authorized.
approvedBooleanWhether the authorization was approved or not.
authTokenString?If the session was authorized, the token will not be null.
finalizedRequiredBoolean?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.

KOTLIN
paymentView.finalize(null)
ParamTypeDescription
viewKlarnaPaymentViewThe payment view that was finalized.
approvedBooleanWhether the user was approved on finalize or not.
authTokenString?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.

JSON
{
"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.

Success response

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 API
  • redirect_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 payment
  • fraud_status, an indicator of whether the transaction is suspected to be legitimate or fraudulent
  • authorized_payment_method, the payment method selected by your customer for this purchase
JSON
{
"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.

Error response

If your request doesn't pass our validation, you'll receive an error response. The most common reasons why creating an order fails are:

  • placing the order more than 60 minutes after authorization
  • modifying purchase details after authorization without updating the payment session
JSON
{
"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 codeError messageDescription
NOT_FOUNDInvalid authorization tokenThe 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_VALUENot 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_VALUENot 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.
REJECTEDRejectedThis 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.

KOTLIN
klarnaPaymentView.loggingLevel = KlarnaLoggingLevel.Verbose

KlarnaLoggingLevel

ValueDescription
KlarnaLoggingLevel.OffNo logging
KlarnaLoggingLevel.ErrorLog error messages only
KlarnaLoggingLevel.VerboseLog all messages (debug and error)

You can enhance your customer experience with other Klarna products from Mobile SDK:

Complete your integration with