Klarna Web SDK v2/r6
    Preparing search index...

    Interface KlarnaPayment

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

    Accepting a payment using the Klarna Payment button:

    payment-button mode=stack label="Integration"

    "Handle completion and mount the payment button with an initiate callback."

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

    payment-button mode=stack label="Integration"

    "Container element for the button."

    <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

    • Parameters

      Returns KlarnaPaymentButton

      Payment

      Payment.button

      general-availability

      true

      true

      acquiring_partner 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

      • paymentRequestId: string

        The ID of the payment request to fetch.

      Returns Promise<PaymentRequest>

      A Promise that resolves to a PaymentRequest.

      Payment

      Payment.cancel

      general-availability

      true

      true

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

      Payment

      Payment.fetch

      general-availability

      true

      true

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

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

      Payment

      Payment.initiate

      general-availability

      true

      true

      acquiring_partner 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

      • event: string

        The event name.

      • callback: Function

        Event callback handler.

      Returns void

      Payment

      Payment.off

      general-availability

      true

      true

      acquiring_partner Unregister an event handler for the given event.

    • Parameters

      • event: "abort"

        The event name ("abort").

      • callback: OnAbortCallback

        Event callback handler.

      Returns void

      Payment

      Payment.onAbort

      general-availability

      true

      true

      acquiring_partner 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: "complete"

        The event name ("complete").

      • callback: OnCompleteCallback

        Event callback handler.

      Returns void

      Payment

      Payment.onComplete

      general-availability

      true

      true

      acquiring_partner 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: "error"

        The event name ("error").

      • callback: OnErrorCallback

        Event callback handler.

      Returns void

      Payment

      Payment.onError

      general-availability

      true

      true

      acquiring_partner 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

      Returns void

      Payment

      Payment.onShippingAddressChange

      general-availability

      true

      true

      acquiring_partner Shipping address changed event handler, triggered when the consumer changes their shipping address during the payment flow.

      Depending on your implementation you can return 3 different payloads from the handler.

      1. If there is no preselected shipping option you should only provide a list of available shipping options.

      Example

      klarna.Payment.on("shippingaddresschange", (paymentRequest, shippingAddress) => {
      return {
      shippingOptions: [{
      shippingOptionReference: string;
      amount: number;
      displayName: string;
      description: string;
      shippingType?: ShippingType;
      }]
      }
      });
      1. If you can preselect one shipping option for the provided address, the whole flow is shorter. Then you should return not only the shipping option, but also the order payload updated with shipping details.

      Example

      klarna.Payment.on("shippingaddresschange", (paymentRequest, shippingAddress) => {
      const { shippingOptions } = await fetch("/shipping-options", {
      method: "POST",
      body: {
      shipping_address: shippingAddress
      }
      });
      const selectedShippingOption = shippingOptions[0];
      const { amount } = await fetch("/cart", {
      method: "POST",
      body: {
      shipping_option: shippingOptions[0]
      }
      });

      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. If the shipping address provided cannot be handled due to some constraints, you can reject it by returning the following.

      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, consumer will see the error screen and payment request will be aborted.

      future-release

    • Parameters

      Returns void

      Payment

      Payment.onShippingOptionSelect

      general-availability

      true

      true

      acquiring_partner Shipping option selected event handler, triggered when the consumer selects a shipping option during the payment flow.

      Depending on your implementation you can return 2 different payloads from the handler:

      1. If the shipping option is correct, 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. If the shipping option provided cannot be handled due to some constraints, you can reject it by returning the following.

      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, consumer will see the error screen and payment request will be aborted.

      future-release

    • 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

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

      Payment

      Payment.presentation

      general-availability

      true

      true

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