Integrate Sign in with Klarna to offer a fast, simple and smoooth login to your customers.
16 min read
The simplest and fastest way to start using Sign in with Klarna is to use the minimal template below.
Please refer to the Before you start article for instructions on how to obtain your CLIENT_ID.
This guide applies to the PUBLIC client type. If your client is set to CONFIDENTIAL, please refer to the next section.
Basic example: Assume that you are serving these 2 files from your web server.
MARKUP
1
2
3
4
5
6
7
8
9
10
<html>
<head>
<!--
1. Add SDK with `defer` attribute
to ensure DOM creation was finished.
-->
<script
defer
src="https://js.klarna.com/web-sdk/v1/klarna.js"
data-client-id="[YOUR CLIENT ID]"
For confidential client
You would need to also obtain the CLIENT_SECRET. Please refer to the Before you start article for instructions on how to obtain your CLIENT_SECRET.
MARKUP
1
2
3
4
5
6
7
8
9
10
<html>
<head>
<!--
1. Add SDK with `defer` attribute
to ensure DOM creation was finished.
-->
<script
defer
src="https://js.klarna.com/web-sdk/v1/klarna.js"
data-client-id="[YOUR CLIENT ID]"
After obtaining the code response, pass it to your server to perform the token exchange. Here’s a JavaScript snippet demonstrating how to send a request to the token endpoint for the exchange:
JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
// An example of the request to exchange for the token.const { URLSearchParams } = require('url');
const fetch = require('node-fetch');
const encodedParams = newURLSearchParams();
encodedParams.set('grant_type', 'authorization_code');
encodedParams.set('client_id', '[YOUR CLIENT ID]');
encodedParams.set('client_secret', '[YOUR API KEY]');
encodedParams.set('code', 'ory_ac_79aOXXm39rfMunrYXglwHZn3dseaMpGAb5b_kJB6WcE...');
IMPORTANT: Why do you need the callback page?
Sign in with Klarna ideally will start in a Popup window to avoid users leaving the merchant's website. However, due to various reasons popup window can be blocked. Thus, having a redirect callback page is REQUIRED to allow users to continue their sign in flow in case their popup is blocked. You can use the callback.html template provided in the example above.
Integration requirement
To successfully implement the REDIRECT mode, below prerequisites must be met:
The redirect URL must match exactly with one of the URLs whitelisted for your client.
The redirect URL must be either passed to the buttonmethod with the redirectUri property or klarna-identity-buttonelement with data-redirect-uri attribute.
The redirect URL page must contain the Web SDK and event handler for signin must be registered.
Understanding the interaction modes
The Sign in with Klarna flow can be initiated in two main modes: DEVICE_BEST or REDIRECT.
DEVICE_BEST (default)
DEVICE_BEST allows Web SDK to automatically decide the most suitable mode, based on user's device configurations. For instance, Web SDK may opt for a REDIRECT if popup blockers are enabled or the page is loaded in an web frame.
By default, DEVICE_BEST mode starts the flow in a popup window for web browsers. This is ideal for merchants who don't want their customers to leave their website. However, if the popup is blocked, Web SDK will switch to REDIRECT mode and the user will be redirected to the login page on the current tab.
REDIRECT
REDIRECT mode redirects the user to the login page on the current tab. However, user will be redirected back to the merchant's redirect callback page at the end of the sign in flow with Authorization tokens or OAuth2Error parameters.
Initialising the Web SDK programmatically
Please note that you can also just load the Web SDK script without the dataset attributes and use the init method to initialise the Web SDK.
After initialising the Web SDK, all Sign in with Klarna related API can be found under the Identity namespace.
Type Definitions
TYPESCRIPT
1
2
3
4
5
6
7
8
9
10
interfaceIdentity {
/**
* Returns the button with given id
*
* If id is not provided, returns the first button instance
*
* If no button instance found returns undefined
*/button(id?: string): KlarnaIdentityButton | undefined;
Displaying the Sign in with Klarna Button
Web SDK provides a flexible API that allows merchants to integrate Sign in with Klarna based on their preference.
1. Using the default Sign in with Klarna button
Web SDK provides a default button that has all functionalities built-in and styled based on official Klarna design guidelines.
1.1. Using <klarna-identity-button /> element
Web SDK registers a custom web component klarna-identity-button, that renders the Sign in with Klarna button where it is mounted.
If the button method is called more than once with the configuration** object**, it will create multiple button instances. If you do not need more than one button, please make sure the button method is only called once.
Multiple buttons require IDs
If you do need multiple buttons make sure you provide an id attribute to each button instance.
Retrieve existing button instance
You can provide a string button id to the button method, to retrieve an existing button instance. For more information, see the Identity API Overview > Type Definitions.
2. Using your custom Sign in with Klarna button
If a merchant wants to use a custom button matching with Klarna's but also with their own design guidelines, they can use the attach method that is provided by Web SDK. The attach method will register the necessary event handlers to start the sign in flow.
Please refer to our Custom button article for essential design considerations.
JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
window.KlarnaSDKCallback = function (klarna) {
const siwkButton = klarna.Identity.button({
id: "klarna-identity-button",
scope: "openid offline_access payment:request:create profile:name",
redirectUri: "http://localhost:3000/callback.html",
locale: "en-GB"
});
// notice, we are using the `attach` method// and providing a button id instead of a container id
Events
SDK Events
Web SDK Identity API can emit two events: signin and error which can be handled as below:
JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
window.KlarnaSDKCallback = function (klarna) {
// 1. Listen for `signin` event to receive signin response object
klarna.Identity.on("signin", async (signinResponse) => {
console.log(signinResponse);
});
// 2. Listen for `error` event to handle error object
klarna.Identity.on("error", async (error) => {
console.log(error);
});
Button Events
Sign in with Klarna buttons can emit two events: ready and click.
JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
window.KlarnaSDKCallback = function (klarna) {
// Please notice that we can retrieve the button instance,// by providing the button instance id to the button methodconst siwkButton = klarna.Identity.button("klarna-identity-button");
siwkButton.on('ready', async () => {
// handle ready event
})
siwkButton.on('click', async () => {
Scopes and Claims
The table below lists the available scopes and how they correspond to claims and permissions.
Scope
Claims
Type
Can be toggled off
profile:name
given_name
string
No
profile:name
family_name
string
No
profile:email
email
string (Email)
No
profile:email
email_verified
boolean
profile:phone
phone
string (E. 164)
No
profile:phone
phone_verified
boolean
profile:date_of_birth
date_of_birth
string (ISO 8601)
Yes
profile:billing_address
street_address
string
Yes
profile:billing_address
street_address2
string
profile:billing_address
postal_code
string
profile:billing_address
city
string
profile:billing_address
region
string
profile:billing_address
country
string (ISO 3166-1 alpha-2)
profile:shipping_address
street_address
string
Yes
profile:shipping_address
street_address2
string
profile:shipping_address
postal_code
string
profile:shipping_address
city
string
profile:shipping_address
region
string
profile:shipping_address
country
string (ISO 3166-1 alpha-2)
profile:national_id
national_id
string
Yes
profile:country
country
string (ISO 3166-1 alpha-2)
Yes
profile:locale
locale
string (ISO 3166)
Yes
payment:consumer_present
trigger on-demand flow
N/A
N/A
payment:consumer_not_present
trigger subscription flow
N/A
N/A
Required scopes
Remember to always add 'openid', 'offline_access' and 'payment:request:create' scopes to receive full functionality of Sign in with Klarna.
The mock-ups below show how users will see required versus optional scopes when entering the Sign in with Klarna flow.
Finalizing the sign in the flow
Before using data from the id_token, it needs to be validated. More about it under Token Validation.
Upon completing the sign-in process, utilise a specific claim (such as phone, email, or national identification number for Sweden) as a unique customer identifier.
Make sure you are handling the following scenarios to ensure seamless integration:
New Users: If the identifier does not match any existing user in your database, check if the consumer consented to share all the data you requested. If additional information is required, remember to show your onboarding UI after Sign in with Klarna flow. Once onboarding is complete, create a new user account using the data returned from Klarna and store the user_account_linking_refresh_token within that record.
Existing Klarna Users: In cases where the identifier is already linked to a Klarna account, Sign in with Klarna always returns fresh customer data. Update your user record with this data to ensure that the information in your database remains current.
Existing Users: For users already in your database but not connected to Klarna, consider these approaches:
Account Merging
User Confirmation for Merging
Merge the account automatically, add customer data from Klarna that was missing in the existing record and save the user_account_linking_refresh_token in it
Prompt the user to confirm if they wish to merge their existing account. If yes, follow *Account Merging *above. If not, ask them to login with a different Klarna account
By carefully managing these scenarios, you can provide a fluid and integrated user experience, leveraging the comprehensive data and functionality offered through the Sign in with Klarna.
Integrating in purchase flow
For those who have already integrated Klarna Payments, Sign in with Klarna enhances user experience by enabling automatic login within these products. To achieve this, simply pass the access_token, obtained from a token refresh call (see Refresh Token), to your existing integrations. You can find examples below depending if you have Klarna Payments.
Integration requirement
access_token has a limited lifespan of only 5 minutes. Therefore, it's essential to renew the token right before initiating the checkout process. To receive a new set of token, perform a token exchange through a POST request to the token endpoint. Remember to always save the new refreshed token in the database, since the old one will be invalid.
For Klarna Payments
Include the access_token in the POST create a payment session request to the Klarna payments API. Add the key to the customer object as klarna_access_token key as shown in the example below.