Klarna Docs - Web SDK integration
Web SDK integration

Integrate Sign in with Klarna to offer a fast, simple and smoooth login to your customers.

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 .

Basic example: Assume that you are serving these 2 files from your web server.

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.

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 button method with the redirectUri property or klarna-identity-button element with data-redirect-uri attribute.
  • The redirect URL page must contain the Web SDK and event handler for signin must be registered.

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.

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.

JAVASCRIPT
<script defer src="https://js.klarna.com/web-sdk/v1/klarna.js"></script>
<script>
  window.onload = async function () {
    const klarna = await Klarna.init({
      clientId: "<YOUR CLIENT ID>"
    });
  };
</script>

After initialising the Web SDK, all Sign in with Klarna related API can be found under the Identity namespace.

TYPESCRIPT
interface Identity {
  /**
   * 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;

Web SDK provides a flexible API that allows merchants to integrate Sign in with Klarna based on their preference.

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.

MARKUP
<klarna-identity-button
  id="klarna-identity-button"
  data-scope="openid offline_access payment:request:create profile:name"
  data-redirect-uri="http://localhost:3000/callback.html"
  data-locale="en-GB"
  ></klarna-identity-button>

1.2. Creating the button programmatically

Web SDK provides the button method that allows to create and mount the Sign in with Klarna button programmatically.

JAVASCRIPT
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"
  });

  siwkButton.mount("#button-container");
};

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.

If you do need multiple buttons make sure you provide an id attribute to each 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.

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

Web SDK Identity API can emit two events: signin and error which can be handled as below:

JAVASCRIPT
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);
  });

Sign in with Klarna buttons can emit two events: ready and click.

JAVASCRIPT
window.KlarnaSDKCallback = function (klarna) {
  // Please notice that we can retrieve the button instance,
  // by providing the button instance id to the button method
  const siwkButton = klarna.Identity.button("klarna-identity-button");

  siwkButton.on('ready', async () => {
    // handle ready event
  })

  siwkButton.on('click', async () => {

The table below lists the available scopes and how they correspond to claims and permissions. 

ScopeClaimsTypeCan be toggled off
profile:namegiven_namestringNo
profile:namefamily_namestringNo
profile:emailemailstring (Email)No
profile:emailemail_verifiedboolean
profile:phonephonestring (E. 164)No
profile:phonephone_verifiedboolean
profile:date_of_birthdate_of_birthstring (ISO 8601)Yes
profile:billing_addressstreet_addressstringYes
profile:billing_addressstreet_address2string
profile:billing_addresspostal_codestring
profile:billing_addresscitystring
profile:billing_addressregionstring
profile:billing_addresscountrystring (ISO 3166-1 alpha-2)
profile:national_idnational_idstringYes
profile:countrycountrystring (ISO 3166-1 alpha-2)Yes
profile:localelocalestring (ISO 3166)Yes
personalization:interestsinterests associated with a consumerstringYes
payment:consumer_presenttrigger on-demand flowN/AN/A
payment:consumer_not_presenttrigger subscription flowN/AN/A

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.   

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 MergingUser 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 itPrompt 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.

For those who have already integrated Klarna Payments or Klarna Checkout, 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 Payment or Klarna Checkout. 

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.

JAVASCRIPT
fetch("https://api.klarna.com/payments/v1/sessions", {
	method: "POST",
	headers: {
		"Content-Type": "application/json"
	},
	body: {
	  ...
  	  "customer": {
    	    ...
    	    "klarna_access_token": "access_token",

For Klarna Checkout 

Include the access_token in the POST create order request to the Klarna checkout API. Add the key to the customer object as klarna_access_token key as shown in the example below.

JAVASCRIPT
fetch("https://api.klarna.com/checkout/v3/orders", {
	method: "POST",
	headers: {
		"Content-Type": "application/json"
	},
	body: {
	  ...
  	  "customer": {
    	    ...
    	    "klarna_access_token": "access_token",