Klarna Web SDK v2
    Preparing search index...

    Interface KlarnaPayment

    The Klarna Payment interface provides access to the payment request API.

    Accepting a payment using the Klarna Payment button

    const klarna = ...;

    // Handle payment request completion
    klarna.Payment.on("complete", async (paymentRequest) => {
    await fetch("https://example.com/my-backend", {
    method: 'POST',
    body: JSON.stringify({
    klarnaPaymentToken: paymentRequest.stateContext.paymentToken
    });
    });
    });

    // Implement the initiate function to create a payment request.
    klarna.Payment.button({
    initiate: () => {
    return {
    currency: "USD",
    amount: 1000
    },
    }
    }).mount("#button-container");
     <div id="button-container"></div>
    
    interface KlarnaPayment {
        button(config: KlarnaPaymentButtonConfig): KlarnaPaymentButton;
        cancel(paymentRequestId: string): Promise<PaymentRequest>;
        fetch(paymentRequestId: string): Promise<PaymentRequest>;
        initiate(
            data:
                | (() => Promise<PaymentRequestData>)
                | (() => Promise<{ paymentRequestId: string }>)
                | (() => Promise<{ returnUrl?: string }>),
            options?: PaymentRequestOptions,
        ): Promise<PaymentRequest>;
        off(event: string, callback: Function): void;
        on(event: "abort", callback: OnAbortCallback): void;
        on(event: "complete", callback: OnCompleteCallback): void;
        on(event: "error", callback: OnErrorCallback): void;
        on(
            event: "shippingaddresschange",
            callback: ShippingAddressChangeCallback,
        ): void;
        on(
            event: "shippingoptionselect",
            callback: ShippingOptionSelectCallback,
        ): void;
        on(
            event: "presentationupdate",
            callback: OnPresentationUpdateCallback,
        ): void;
        presentation(data: PaymentPresentationData): Promise<PaymentPresentation>;
    }
    Index

    Methods

    • The button method allows creating a payment button. This is the recommended way to interact with Klarna Payment interface.

      klarna.Payment.button({
      initiate: () => {
      return {
      currency: "EUR",
      amount: 1000,
      paymentRequestReference: "pay-ref-123",
      supplementaryPurchaseData: {
      purchaseReference: "pay-ref-123",
      lineItems: [],
      shipping: [],
      customer: {}
      },
      customerInteractionConfig: {
      returnUrl: "https://example.com/success"
      }
      }
      },
      initiationMode: "DEVICE_BEST"
      }).mount("#klarna-button-container");

      Parameters

      Returns KlarnaPaymentButton

    • Cancels the payment request with the given ID. It's only possible to cancel payment requests created by the same client/credentials.

      Parameters

      • paymentRequestId: string

        The ID of the payment request to fetch.

      Returns Promise<PaymentRequest>

      A Promise that resolves to a PaymentRequest.

    • Fetches the payment request with the given ID. It's only possible to fetch payment requests created by the same client/credentials.

      Parameters

      • paymentRequestId: string

        The ID of the payment request to fetch.

      Returns Promise<PaymentRequest>

      A Promise that resolves to a PaymentRequest.

    • Initiates a payment with Klarna. Use this method only if you absolutely need to own your button. Otherwise, use the KlarnaPayment.button method. If you use this method along with initiationMode of DEVICE_BEST or ON_PAGE, it has to be called right after the button is clicked. If there are long running operations such as network requests, you can do that within the callback.

      Example:

      let isInitiating = false;

      // Suppose "payWithKlarnaButton" is your checkout button
      payWithKlarnaButton.addEventListener('click', async () => {
      // If it's already initiating, do nothing.
      // This is to prevent concurrent initiate calls
      if (isInitiating) {
      return;
      }

      try {
      // Set a flag to block subsequent calls
      isInitiating = true;

      // Optionally disable the button for extra safety
      payWithKlarnaButton.disabled = true;

      // Never put long running operations such as network requests before calling `initiate`.
      // This method should be called immediately (or close to immediately) after the button
      // is clicked to ensure the popup is not blocked by the browser.
      await klarna.Payment.initiate(async () => {
      // Do network requests inside the callback
      const paymentData = await myPaymentData();

      // Return the payment data
      return paymentData;
      }, {
      initiationMode: "DEVICE_BEST", // Controls how the payment flow is launched
      });
      } catch (error) {
      console.error('Payment initiation failed:', error);
      } finally {
      // Re-enable subsequent calls
      isInitiating = false;
      payWithKlarnaButton.disabled = false;
      }
      });

      Parameters

      • data:
            | (() => Promise<PaymentRequestData>)
            | (() => Promise<{ paymentRequestId: string }>)
            | (() => Promise<{ returnUrl?: string }>)

        It can be one of the following:

        • Return a promise that resolves to a PaymentRequestData object if you want to create a payment request on the client side.

        • Return a promise that resolves to a PaymentRequestId object if you have created a payment request on the server side.

        • Return a promise that resolves to an object with an optional returnUrl if you want Klarna to redirect the customer to a success page. This is typically done when you have custom logic on the server side which does not necessarily create a payment request. One example is when you use payment/authorize which returns an approved transaction.

      • Optionaloptions: PaymentRequestOptions

        Optional settings for the payment request:

        • initiationMode: Controls how the customer flow is launched (DEVICE_BEST, REDIRECT, ON_PAGE)

      Returns Promise<PaymentRequest>

      A Promise that resolves to a PaymentRequest or undefined if an error was thrown somewhere before completing.

    • Unregister an event handler for the given event.

      Parameters

      • event: string

        The event name.

      • callback: Function

        Event callback handler.

      Returns void

    • Register an event handler for the abort event. A payment request is aborted when the customer decides to cancel the payment request by closing the popup or somehow cancel the process.

      • Example
      klarna.Payment.on("abort", (paymentRequest) => {
      console.log(`The reason for the abort may be read by accessing ${paymentRequest.stateReason}`);
      });

      Parameters

      • event: "abort"

        The event name ("abort").

      • callback: OnAbortCallback

        Event callback handler.

      Returns void

    • Register an event handler for the complete event. A payment request is completed when the user has approved the purchase.

      During a redirection flow the complete handler will trigger once your page has loaded on the success page. Pending updates are triggered even if the event handler is registered after the page has loaded to avoid need for polling.

      Example

      klarna.Payment.on("complete", (paymentRequest) => {
      console.log(`Authorize the payment by sending the ${paymentRequest.stateContext.paymentToken} to your backend`);
      // Return false if you want to prevent the redirection to the success page, if not, return anything or true.
      return false
      });

      Parameters

      • event: "complete"

        The event name ("complete").

      • callback: OnCompleteCallback

        Event callback handler.

      Returns void

    • Register an event handler for the error event. Anytime an error occurs during the payment request lifecycle, the error event is triggered. If the error event handler is defined, all errors will be emitted to it instead of thrown upwards.

      Example

      klarna.Payment.on("error", (error, paymentRequest) => {
      // Handle the error
      });

      Parameters

      • event: "error"

        The event name ("error").

      • callback: OnErrorCallback

        Event callback handler.

      Returns void

    • The shipping address changed event handler is triggered when the consumer changes their shipping address during the payment flow. If the shipping address is present in the customer account, the event will be triggered immediately after the customer has logged in. Here, you are given the opportunity to accept or reject the shipping address.

      1. Accept the shipping address: If you accept the shipping address, you should return a list of available shipping options. The customer will be prompted to select one of the shipping options.

      Example

      klarna.Payment.on("shippingaddresschange", (paymentRequest, shippingAddress) => {
      return {
      shippingOptions: [{
      shippingOptionReference: string;
      amount: number;
      displayName: string;
      description: string;
      shippingType?: ShippingType;
      }]
      }
      });

      In case you want to preselect a shipping option for the provided address, you can do so by returning the shipping option in the selectedShippingOptionReference property. You should also update the amount and lineItems properties to reflect the selected shipping cost. Preselecting a shipping option skips the screen where the customer needs to select a shipping option and goes directly to the review screen. This will reduce the friction of the payment flow.

      Example

      klarna.Payment.on("shippingaddresschange", (paymentRequest, shippingAddress) => {
      return {
      amount,
      lineItems: [
      ...lineItems,
      {
      name: selectedShippingOption.name,
      quantity: 1,
      totalAmount: selectedShippingOption.amount
      }
      ],
      selectedShippingOptionReference: selectedShippingOption.reference,
      shippingOptions: [{
      shippingOptionReference: string;
      amount: number;
      displayName: string;
      description: string;
      shippingType?: ShippingType;
      }]
      };
      });
      1. Reject the shipping address:

      If the shipping address provided cannot be handled due to some constraints, you can reject it with a rejection reason. The customer will be prompted to enter a new shipping address.

      Example

      klarna.Payment.on("shippingaddresschange", (paymentRequest, shippingAddress) => {
      return {
      rejectionReason: `POSTAL_CODE_NOT_SUPPORTED`
      }
      });

      The available rejection reasons are:

      • POSTAL_CODE_NOT_SUPPORTED
      • CITY_NOT_SUPPORTED
      • REGION_NOT_SUPPORTED
      • COUNTRY_NOT_SUPPORTED
      • ADDRESS_NOT_SUPPORTED

      If you did not return anything during the 10 seconds after receiving this event, the customer will see the error screen and payment request will be aborted.

      Parameters

      Returns void

    • The shipping option selected event handler is triggered when the consumer selects a shipping option during the payment flow. Here, you are given the opportunity to accept or reject the shipping option.

      1. Accept the shipping option: If you accept the shipping option, you should return the order payload updated with shipping details.

      Example

      klarna.Payment.on("shippingoptionselect", (paymentRequest, shippingOption) => {
      const { amount } = await fetch("/cart", {
      method: "POST",
      body: {
      shipping_option: shippingOption
      }
      });

      return {
      amount,
      lineItems: [
      ...lineItems,
      {
      name: 'Shipping option 1',
      quantity: 1,
      totalAmount: 500
      }
      ]
      };
      });
      1. Reject the shipping option: If the shipping option provided cannot be handled due to some constraints, you can reject it with a rejection reason. The customer will be prompted to select a different shipping option.

      Example

      klarna.Payment.on("shippingoptionselect", (paymentRequest, shippingAddress) => {
      return {
      rejectionReason: `INVALID_OPTION`
      };
      });

      The available rejection reasons are:

      • INVALID_OPTION

      If you did not return anything during the 10 seconds after receiving this event, the customer will see the error screen and payment request will be aborted.

      Parameters

      Returns void

    • Presentation update event handler, triggered when there are changes to how Klarna should be presented in the payment selector.

      Example:

      klarna.Payment.on("presentationupdate", (presentation) => {
      // Handle updated presentation instructions
      switch (presentation.instruction) {
      case "SHOW_ONLY_KLARNA":
      // Update UI to show only Klarna
      break;
      case "PRESELECT_KLARNA":
      // Update UI to preselect Klarna
      break;
      // ... handle other cases
      }

      // Update texts if you don't use our components
      if (presentation.paymentButton.text) {
      updateButtonText(presentation.paymentButton.text);
      }
      if (presentation.header.text) {
      updateHeaderText(presentation.header.text);
      }
      if (presentation.subheader.enriched.text) {
      updateEnrichedSubheaderText(presentation.subheader.enriched.text);
      }
      });

      Parameters

      Returns void

    • The method returns instructions on how Klarna should be presented in the payment selector. Use this method along with the presentationupdate event handler to update the presentation instructions dynamically.

      Parameters

      • data: PaymentPresentationData

        The input data for the payment presentation.

        • amount: number
        • currency: string
        • Optionalintents?: ("PAY" | "SUBSCRIBE" | "SIGNUP" | "SIGNIN" | "DONATE")[]
        • locale: string

      Returns Promise<PaymentPresentation>

      a promise that resolves to a PaymentPresentation object.