Skip to navigation

Buy now, pay later

Accept Klarna, Afterpay, and Affirm payments in a popup window or by redirecting the customer.
View as Markdown

PaymentKit.js supports three buy now, pay later (BNPL) payment methods: Klarna, Afterpay, and Affirm. All three share the same flow — there are no input elements to mount. When you submit, the customer completes approval on the BNPL provider’s page. You choose how that page opens with the required flowType option: in a popup window, where PaymentKit.js polls for the result and resolves your onSuccess or onError callback, or by redirect, where the customer leaves your page and comes back on your checkout session’s success_url. See Popup or redirect.

Setup

Register only the BNPL methods you plan to offer — each one is independent.

<script src="https://unpkg.com/@payment-kit-js/vanilla/dist/cdn/paymentkit.min.js"></script>
<script>
const paymentKit = PaymentKit.default({
environment: 'sandbox',
secureToken: 'aBcDeFgHiJkLmNoPqRsTuVwXyZ123456', // From your backend
paymentMethods: [
PaymentKit.PaymentMethods.klarna,
PaymentKit.PaymentMethods.afterpay,
PaymentKit.PaymentMethods.affirm
]
});
</script>

Submit payment

Like PayPal, BNPL methods don’t need input elements. Submit directly when the customer clicks your Klarna, Afterpay, or Affirm button. Pass the matching paymentMethod name ('klarna', 'afterpay', or 'affirm') and the required flowType:

document.getElementById('klarna-button').addEventListener('click', () => {
paymentKit.submit({
fields: {
customer_name: 'Jane Smith',
customer_email: 'jane@example.com',
customer_country: 'US',
customer_zip_code: '94102'
},
paymentMethod: 'klarna', // or 'afterpay' / 'affirm'
options: {
processorId: 'proc_abc123',
customerInfo: {
first_name: 'Jane',
last_name: 'Smith',
email: 'jane@example.com'
},
flowType: 'popup' // required: 'popup' or 'redirect', see "Popup or redirect"
},
onSuccess: (result) => {
console.log('ID:', result.id);
console.log('Checkout Attempt ID:', result.checkoutAttemptId);
console.log('Checkout Session ID:', result.checkoutSessionId);
console.log('State:', result.state);
window.location.href = '/success';
},
onError: (errors) => {
console.error(errors);
}
});
});

With flowType: 'popup', PaymentKit.js opens the provider’s approval page in a 600×700 popup window and polls the payment status every 2 seconds. If the customer closes the popup without completing approval, the submission fails with a “popup closed by user” error after a grace period. The grace period is 3 seconds for Klarna and Affirm, and 5 minutes for Afterpay, because Afterpay’s popup can report closed while the customer is still paying. If status requests get no answer for the whole grace period plus 30 seconds, the error is “payment status could not be confirmed” instead, because the payment may have succeeded.

With flowType: 'popup', the submit must be triggered by a direct user action (button click) to avoid being blocked by popup blockers. If the browser blocks the popup, the submission fails with an error before any payment starts.

Need to run your own validation before the charge? Pass beforeConfirm in options. With flowType: 'popup', the popup opens synchronously on tap, but PaymentKit waits for beforeConfirm before navigating it to the provider. Reject and the popup closes without the provider ever seeing the request. See Pre-charge validation.

Popup or redirect

flowType is required on every BNPL submit, and PaymentKit.js never switches between the two on its own. You choose, because the two flows hand you the result in different ways:

flowType: 'popup'flowType: 'redirect'
Where the customer approvesA popup window; your page stays openThe provider’s page replaces your page (same tab)
How you get the resultonSuccess / onError on your pageYour checkout session’s success_url (or return_url), plus webhooks. onSuccess never fires. onError fires only for a failure before the customer leaves your page
When to use itRegular browsersBrowsers that block popups, such as in-app browsers

Some in-app browsers refuse to open popups at all. The Google app on iOS (user agent contains GSA/) does this every time, and some social-app in-app browsers such as Instagram and Facebook can too. In those browsers the popup flow fails with Failed to open Klarna popup. Please allow popups for this site., and the customer has no way to allow it. Detect those browsers yourself (for example from the user agent) and submit with flowType: 'redirect' instead:

const IN_APP_BROWSER = /\bGSA\/|FBAN|FBAV|Instagram/.test(navigator.userAgent);
paymentKit.submit({
fields: { /* ... */ },
paymentMethod: 'klarna',
options: {
processorId: 'proc_abc123',
customerInfo: { first_name: 'Jane', last_name: 'Smith', email: 'jane@example.com' },
flowType: IN_APP_BROWSER ? 'redirect' : 'popup'
},
onSuccess: (result) => { /* popup flow only */ },
onError: (errors) => { /* popup flow, or a redirect submit that failed before leaving the page */ }
});

With flowType: 'redirect':

  1. PaymentKit.js starts the payment and sends the customer to the provider in the same tab. Your page unloads, so onSuccess and onError never fire for a submit that left the page. onError still fires for a submit that fails before leaving: invalid options, a rejected beforeConfirm, or a failed start request.
  2. After the customer approves, cancels, or fails at the provider, PaymentKit verifies and records the outcome, then redirects the customer:
    • on success, to the checkout session’s success_url;
    • on cancel or failure, to the checkout session’s return_url. PaymentKit appends checkout_session_id and status (success, cancelled, or failed) to that URL as query parameters. It also replaces a {CHECKOUT_SESSION_ID} placeholder in either URL with the session id. Set these URLs when you create the checkout session.
  3. On that page, read the result from the query string and verify it on your backend (for example by fetching the checkout session or from your webhooks). Do not treat the landing alone as proof of payment.

If the customer comes back before the provider has settled the payment, PaymentKit shows a short “finishing your payment” page that keeps checking and redirects the customer as soon as the outcome is final.

If you route PaymentKit.js through your own custom domain (the apiBaseUrl constructor option), the return trip from the provider goes through that domain too, as long as it is your account’s active custom checkout domain. Otherwise the return trip uses the PaymentKit platform host.

Options

OptionTypeRequiredMethodsDescription
processorIdstringYesAllYour processor ID (BNPL payments are processed through your Stripe processor)
customerInfo.first_namestringYesAllCustomer’s first name
customerInfo.last_namestringYesAllCustomer’s last name
customerInfo.emailstringNoAllCustomer’s email address
flowType'popup' | 'redirect'YesAllHow the provider’s approval page opens. See Popup or redirect
setupFutureUsagebooleanNoKlarna onlySave the Klarna payment method for future use
beforeConfirmfunctionNoAllYour own check, run before PaymentKit starts the charge. Reject, throw, or return false or { ok: false } to stop the payment. See Pre-charge validation
beforeConfirmTimeoutMsnumberNoAllMilliseconds to wait for beforeConfirm before the payment stops. Default: 10000

Saving Klarna for future payments

Klarna supports saving the payment method during checkout for future off-session charges (for example, subscriptions). Pass setupFutureUsage: true in the submit options:

paymentKit.submit({
fields: { /* ... */ },
paymentMethod: 'klarna',
options: {
processorId: 'proc_abc123',
customerInfo: {
first_name: 'Jane',
last_name: 'Smith'
},
flowType: 'popup',
setupFutureUsage: true
},
onSuccess: (result) => { /* ... */ },
onError: (errors) => { /* ... */ }
});

setupFutureUsage is only supported by Klarna. Afterpay and Affirm do not support saving the payment method — their TypeScript submit option types omit the field, and the SDK never sends it for those methods.

Error handling

Each BNPL method returns its errors under its own key — errors.klarna, errors.afterpay, or errors.affirm — as descriptive strings. Validation errors use errors.processor_id and errors.customer_name; a missing or invalid flowType is reported under the method’s own key:

onError: (errors) => {
if (errors.processor_id) {
// Missing processor ID
console.error(errors.processor_id); // "Processor ID is required"
} else if (errors.customer_name) {
// Missing customer name
console.error(errors.customer_name); // "Customer first and last name are required"
} else if (errors.klarna) {
// Klarna-specific errors (same patterns apply to errors.afterpay / errors.affirm)
if (errors.klarna.includes('flowType is required')) {
// Integration bug: pass flowType: 'popup' or 'redirect'
} else if (errors.klarna.includes('Please allow popups')) {
// Popup was blocked
alert('Please allow popups for this site');
} else if (errors.klarna.includes('popup closed by user')) {
// Customer closed the popup without completing payment
} else if (errors.klarna.includes('cancelled')) {
// Customer cancelled in the provider's flow
} else if (errors.klarna.includes('could not be confirmed')) {
// The payment may have succeeded, so do not show a decline
}
console.error(errors.klarna);
}
}

The table below uses Klarna as the example; for Afterpay and Affirm the error field is afterpay / affirm and the provider name in the message changes accordingly. The popup-blocked, closed, status, and polling errors apply only to flowType: 'popup'. A flowType: 'redirect' submit reports only the errors that happen before the customer leaves your page: validation, start failed, no approval URL, could not start, and checkout error. After the page leaves, the outcome reaches your session’s return URL, not onError.

Error FieldError MessageCause
processor_idProcessor ID is requiredMissing processorId in options
customer_nameCustomer first and last name are requiredMissing customerInfo.first_name or customerInfo.last_name
klarnaflowType is required: "popup" or "redirect" (got {value})Missing or invalid flowType in options. {value} is the JSON of what you passed, for example undefined or "tab". Nothing is opened and no payment is started
klarnaFailed to open Klarna popup. Please allow popups for this site.Browser blocked the popup window (popup flow only). In-app browsers do this every time; use flowType: 'redirect' there
klarnaFailed to start Klarna checkout ({status})The start request failed. The backend error detail is used when available; if the response has no body, the HTTP status text is used. {status} is the HTTP status code
klarnaKlarna checkout did not return an approval URL. Please try again.The start request succeeded but the processor returned no approval URL. Nothing is opened for the customer
klarnaKlarna checkout could not start. Please try again.The SDK retried the start request and the retry got a conflict (409). An earlier request may still hold the checkout
klarnaKlarna popup closed by userCustomer closed the popup, and the payment did not complete during the grace period after the close. The grace period is about 3 seconds for Klarna and Affirm and 5 minutes for Afterpay. A payment that succeeds in that time is reported as a success
klarnaFailed to check Klarna statusThe status check returned a final error, such as a 404. Server errors (5xx), 408, 425, and 429 are not final: the SDK keeps polling
klarnaKlarna checkout cancelledPayment was cancelled by the customer. If the backend sends its own error text, that text is shown instead
klarnaKlarna checkout failedPayment failed on the provider’s side. If the backend sends its own error text, that text is shown instead
klarnaKlarna payment status could not be confirmedThe SDK could not read the payment status. It stops when status reads have failed for 15 minutes in a row, with the popup open or closed. It also stops sooner, after the customer closes the popup, when the grace period has passed since the close and status reads have failed for the grace period plus 30 seconds (about 33 seconds for Klarna and Affirm, 5.5 minutes for Afterpay). The payment may have succeeded, so do not treat this as a decline. If the customer submits again, the checkout does not charge twice
klarnaPolling error: {error}Unexpected SDK error during status polling. A network error does not end the payment: the SDK keeps polling
klarnaKlarna checkout error: {error}General checkout error, such as a network failure on the start request