Klarna Docs - Klarna Payments JavaScript SDK

Klarna Payments JavaScript SDK

The following is the library reference for Klarna Payments Javascript SDK. Below you will find a description about the different methods included as well as required parameters and potential errors it can throw.

init

In this mandatory step, the Klarna Payments library is initialized. The method expects the client_token received when creating a session.

Example

JAVASCRIPT
try {
Klarna.Payments.init({
    client_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.dtxWM6MIcgoeMgH87tGvsNDY6cHWL6MGW4LeYvnm1JA'
})
} catch (e) {
// Handle error.
}

Initializing the Klarna Payments JS library

Parameters

options (Object)

Property NameDescription
options.client_token (String)The client token received when creating the session towards Klarna.

Throws

  • InvalidClientTokenError: If options.client_token is not a valid JSON Web Token.

load~callback

Called with the result of the load operation. You can find more examples of the potential responses in the load article.

Example

OutcomeResponse
Pre-assessment accepted{ show_form: true }
Pre-assessment rejected{ show_form: false }
Adjustable error{ show_form: true, Error: { invalid_fields: ["billing_address.email"] } }

Parameters

res (Object) Response

Property NameDescription
res.show_form (Boolean)A boolean indicating the result of the pre-assessment. If true you should display the widget, if false you can decide to hide it from the user.
res.error (Object)If there are any adjustable errors, these will be displayed here.

load

A load call must be done to display the Klarna widget to the customer. This will trigger a light pre-assessment by Klarna, based on the known order details, to see if Klarna might offer the customer credit. If the pre-assessment passes, the payment method details are rendered in the Klarna widget.

As a merchant, you choose when to present the form to the customer. It is recommended to do this as a customer selects the available Klarna payment method. If you have received new or additional information about the customer, or the cart details are updated, you can call the method again. This will update the current session.

Example

JAVASCRIPT
try {
Klarna.Payments.init({ client_token: '...' })
Klarna.Payments.load({
    container: '#klarna-payments-container',
    payment_method_category: 'pay_later'
}, { // Data to be updated
    billing_address: {
    // ...
    }
}, function (res) { // load~callback

Calling the load() method to display the Klarna widget

Parameters

Using payment_method_category lets you load one payment method per widget. This value will later be used to refer widget also when calling authorize().

options (Object)

Property NameDescription
options.container (HTMLElement/String)The container in which to render the application. Should be an HTML element or valid CSS selector.
options.preferred_payment_method (String)The payment method to be pre-selected, if possible.
options.payment_method_category (String)The category of payment methods that should be loaded. Only one can be included.

Throws

Error thrownApplicationNotInitializedError
ApplicationNotInitializedErrorIf load() is called without options and/or prior to init.
InvalidContainerSelectorErrorIf options.container is neither an HTML element nor a valid CSS selector.
PaymentMethodCategoryNotProvidedErrorIf options.payment_method_category is not provided as a parameter in the load() call.
PreferredPaymentMethodNotSupportedErrorIf options.preferred_payment_method is not supported.
This section only applies to:

Note: This is seldom used and only relevant if you have a multi-step checkout with an order review page.

If your checkout offers the customer an opportunity to review the order after the payment step, it can make sense to present the payment method the customer selected on a previous page. This gives the customer a chance to review the payment method and its terms to the user.

Klarna supports this by offering a payment review widget in which all relevant data around the customers payment method is presented.

Example

JAVASCRIPT
try {
Klarna.Payments.init({ client_token: '...' })
Klarna.Payments.loadPaymentReview({
    container: '#klarna-payments-container'
}, function (res) { // loadPaymentReview~callback
    // ...
})
} catch (e) {
// Handle error. The loadPaymentReview~callback will have been called
// with "{ show_form: false }" at this point.

loadPaymentReview() sample code

Parameters

options (Object)

Property NameDescription
options.container (HTMLElement/String)The container in which to render the application. Should be an HTML element or valid CSS selector.

callback (loadPaymentReview~callback) A function that will be called when the operation is completed.

Throws

Error thrownDescription
ApplicationNotInitializedErrorIf called without options and/or prior to init().
OperationNotSupportedErrorIf the operation is not supported for the current purchase country.
InvalidContainerSelectorErrorIf options.container is neither an HTML element nor a valid CSS selector.

loadPaymentReview~callback

Called with the result of the loadPaymentReview operation.

Parameters

res (Object) Response

Property NameDescription
res.show_form (Boolean)A boolean indicating the result of the pre-assessment.

authorize~callback

Called with the result of the authorize operation.

Examples

res (Object) Response

Successful authorization{ authorization_token: "b4bd3423-24e3", approved: true, javascript show_form: true }
Authorization that requires finalization{ approved: true, show_form: true, finalize_required: true }
Rejected authorization with solvable errors{ approved: false, show_form: true, error: {invalid_fields: ["billing_address.email"] } }
Rejected authorization (non-resolvable){ approved: false, show_form: false}

Parameters

res (Object) Response

Property NameDescription
res.authorization_token (String)If credit is approved, needed to place order.
res.show_form (Boolean)A boolean indicating whether to keep showing the form or to remove it.
res.approved (Boolean)A boolean indicating the result of the credit assessment.
res.finalize (Boolean)A boolean indicating that the finalize method should be called in order to complete the authorization.
res.error (Object)Object specifying a specific error. Only available in case of solvable errors.

authorize

This call triggers the credit risk and fraud assessment in Klarna’s system to decide whether or not a consumer will get the credit they applied for. Upon authorizing the credit, Klarna will validate the input in the credit form. If there are any errors, the relevant fields are highlighted and corresponding error messages are shown. The authorization is made with a client side call to authorize. The result of a successful authorization is an authorization_token that should be used when creating the order. The response object also includes a key called show_form, which indicates whether or not the Klarna payment option should remain available (i.e. success case or errors that the user can resolve) or if you should remove the option entirely (i.e. final rejection).

Note: A successful authorization guarantees that the order can be created within 60 minutes.

When new or additional information about the customer is received (e.g. billing address), authorize can be called again, which will update the current session.

Please note that the authorize call may trigger additional information requirements on the consumer. The callback can therefore be instant, take a very long time (i.e. the time it takes the customer to complete the form), or may never happen (if the consumer drops out). The integration should therefore not be relying on an immediate response, and should not implement any timeouts on the merchant side, but wait for the callback function to be called.

Best practice: To ensure that customers understand that some processing is going on in the background, when authorize() is called, it should be visually shown that something is happening (e.g. a spinner in the button that triggered the authorize call).

JAVASCRIPT
try {
Klarna.Payments.authorize({
    payment_method_category: 'pay_later'
}, { // Data to be updated
    billing_address: {
    // ...
    }
}, function (res) { // authorize~callback
    // ...
})

authorize() sample call

Parameters

options (Object)

Property NameDescription
options.auto_finalize (Boolean)An optional flag used to turn off auto-finalization for the direct bank transfer payment method.
data (Object)An optional object with data to update on the session.
callback (authorize~callback)A function that will be called when authorization is completed.
options.payment_method_category (String)The payment method category that was provided in the previous load call.

Throws

Error thrownDescription
PaymentMethodCategoryNotSupportedErrorIf options.payment_method_category is not supported.
ApplicationNotLoadedErrorIf called prior to load

reauthorize~callback

res (Object) Response

Successful reauthorize{ authorization_token: "b4bd3423-24e3", approved: true }
Rejected reauthorize{ approved: false }
Rejected reauthorization due to an invalid update{ approved: false, error: { invalid_fields: ["billing_address.email"] } }

Note: Reauthorize currently also includes { show_form: true/false } in the response. This is deprecated and shall not be used. Instead only a { approved: true, authorization_token: string } response should require any action for reauthorize.

Parameters

res (Object) Response

Property NameDescription
res.show_form (Boolean)A boolean indicating whether to keep showing the form or to remove it.
res.authorization_token (String)If credit is approved, needed to place order.
res.approved (Boolean)A boolean indicating the result of the credit assessment.
res.error (Object)Only available in case of solvable errors.

reauthorize

If you have a multi-step checkout which offers the customer to change any details of the order (e.g. customer details, shopping cart, shipping, discount code, gift cards etc.) after the payment step you will need to reauthorize if the customer changes anything. This is due to the authorization_token you received originally is only valid for that specific state of the order. If you attempt to place an order without doing an reauthorize, it will fail.

On such an order review page you typically don’t have a payment selector, and hence the standard way of authorizing (init + load+ authorize) is not possible here. Reauthorize can be used without a payment selector, and any necessary customer communication will be handled in fullscreen modals.

Note: if the payment method widget is still visible. Use a regular authorize instead.

We recommend that you trigger reauthorize as few times as possible, but as many times as necessary. We would suggest that you store when a change has happened, and if so is the case, you trigger reauthorize once the customer clicks on “Complete order” (i.e. only if a change has happened). As with authorize(), you can provide an optional update object including all order details. It is however also possible to chain this in a way where you start with a server-side session update per REST API, followed by an empty client-side call to reauthorize. Please note that the reauthorize call may trigger confirmation from the consumer on changed financing details. The callback can therefore be instant, take a very long time (i.e. the time it takes the customer to complete the form), or may never happen (if the consumer drops out). The integration should therefore not be relying on an immediate response, and should not implement any timeouts on the merchant side, but wait for the callback function to be called.

Best Practice: To ensure that customers understand that some processing is going on in the background, when reauthorize is called, it should be visually shown that something is happening (e.g. a spinner in the button that triggered the reauthorize call).

If on a different page than where you originally ran init, Klarna Payments needs to be initialized before doing reauthorize.

JAVASCRIPT
try {
Klarna.Payments.init({ client_token: '...' })
Klarna.Payments.reauthorize({
    payment_method_category: 'pay_later'
}, { // Data to be updated
    billing_address: {
    // ...
    }
}, function (res) { // reauthorize~callback
    // ...

reauthorize() sample call

Parameters

options (Object)

Property NameDescription
data (Object)An optional object with data to update on the session.
callback (Object)A function that will be called when the reauthorization is completed.
options.payment_method_category (String)The category of payment methods that should be loaded. Only one can be included.

Throws

Error thrownDescription
ApplicationNotInitializedErrorIf called prior to init() .
PaymentMethodCategoryNotSupportedErrorIf options.payment_method_category is not supported.
PaymentMethodCategoryNotProvidedErrorIf options.payment_method_category is not provided when required.

finalize~callback

Called with the result of the finalize operation.

Note: This is only relevant if you have a multi-step checkout and are offering direct debit through Klarna’s widget.

Example

res (Object) Response

OutcomeResponse
Successful finalization{ authorization_token: "b4bd3423-24e3", approved: true, show_form: true }
Rejected or aborted finalization{ approved: false, show_form: false }
Rejected finalization due to an invalid update{ approved: false, show_form: true, error: { invalid_fields: ["billing_address.email"] } }

Parameters

res (Object) Response

Property NameDescription
res.show_form (Boolean)A boolean indicating whether to keep showing the form or to remove it.
res.authorization_token (String)If credit is approved, needed to place order.
res.approved (Boolean)A boolean indicating the result of the credit assessment.
res.error (Object)Only available in case of solvable errors.

finalize

A finalization will be required for some payment methods. Whenever a finalization is required, the authorize call will return finalize_required: true. The finalize response will then contain the authorization token if the user successfully completes required steps.

The finalization should be done just before the purchase is completed, meaning the last step in a multi-step checkout.

Note: This section is only relevant if you have a multi-step checkout and offer direct debit in the Klarna widget.

Example

JAVASCRIPT
try {
Klarna.Payments.init({ client_token: '...' })
Klarna.Payments.finalize({
    payment_method_category: 'pay_later'
}, { // Data to be updated
    billing_address: {
    // ...
    }
}, function (res) { // finalize~callback
    // ...

finalize() sample call

options (Object)

Property NameDescription
data (Object)An optional object with data to update on the session.
callback (authorize~callback)A function that will be called when authorization is completed.
options.payment_method_category (String)The payment method category that was provided in the previous load call.

Throws

Error thrownDescription
ApplicationNotInitializedErrorIf called prior to init.
ApplicationNotLoadedErrorIf called prior to load
PaymentMethodCategoryNotProvidedErrorIf options.payment_method_category is not provided when required.
PaymentMethodCategoryNotSupportedErrorIf options.payment_method_category is not supported.

on~eventHandler

Called whenever the associated event is emitted inside Klarna Payments.

Parameters

res (Object) Response

Property NameDescription
payload (Boolean)The payload may vary between events. See the list of supported events for details.

on

Registers an event handler for the given eventName. The events are triggered internally in Klarna Payments. The supported events are:

EventComment
heightChangedEmitted when the height of the iframe changes. The registered event handler is called with the new height (in pixels) as a number (integer).
fullscreenOverlayShownEmitted when the fullscreen overlay is shown.
fullscreenOverlayHiddenEmitted when the fullscreen overlay is hidden.
JAVASCRIPT
Klarna.Payments.on('heightChanged', function (newHeight) {
console.log('got new iframe height', newHeight)
})

Sample event listener definition for heightChanged

Parameters

NameDescription
eventName (String)The name of the event to which you want to subscribe.
eventHandler (on~eventHandler)The function that should be called when the event is emitted.

Throws

Error thrownComment
EventNotSupportedErrorIf trying to register an unsupported event.

off

Unregisters an event handler for the given eventName.

Examples

JAVASCRIPT
var theEventHandler = function () { ... }
Klarna.Payments.on('heightChanged', theEventHandler)

// unregister this specific listener for heightChanged
Klarna.Payments.off('heightChanged', theEventHandler)

// unregister _all_ listeners for heightChanged
Klarna.Payments.off('heightChanged')

De-registering event listeners sample

Parameters

NameDescription
eventName (String)The name of the event to which you want to subscribe.
eventHandler (on~eventHandler)The function that was previously registered for the eventName . Omit if you want to unregisterall handlers for the eventName.