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

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

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