Getting started overview
Integrating Klarna into an application or e-commerce platform involves a sequence of steps, beginning with account creation and credential acquisition, followed by initial API interactions. Klarna provides various payment options, including 'Pay in 4' and 'Pay in 30 days', which allow consumers to manage payments over time Klarna's core payment products. The integration process aims to enable these options within a merchant's checkout flow.
Before initiating any API calls, developers must establish a merchant account to gain access to the Klarna Merchant Portal. This portal serves as the control center for managing orders, refunds, and generating API keys. Klarna supports direct API integrations and offers pre-built modules for common e-commerce platforms such as Shopify, WooCommerce, and Magento Klarna platform integrations guide. For custom integrations, SDKs are available for several programming languages, streamlining the development process by handling authentication and request formatting.
The typical first engagement with the Klarna API involves creating a payment session or an order. This action usually requires sending customer and cart details to Klarna's endpoints. A successful response often includes a redirect URL or a client token, which is then used to present Klarna's checkout experience to the end user. Testing should be conducted in Klarna's sandbox environment throughout the development phase to simulate transactions without financial implications Klarna testing and go-live procedures.
| Step | What to Do | Where |
|---|---|---|
| 1. Sign Up | Create a merchant account. | Klarna Business Signup |
| 2. Get API Keys | Generate API credentials (Username/Password). | Klarna Merchant Portal > Settings > Klarna API Credentials |
| 3. Choose Integration Method | Decide between direct API, SDK, or platform plugin. | Klarna platform integrations overview or Klarna API reference |
| 4. Configure Environment | Set up development environment and install chosen SDK. | Klarna testing environment details |
| 5. Make First Request | Create a test order or payment session. | Klarna Payments API documentation |
Create an account and get keys
To begin using Klarna's services, merchants must first register for a business account. This process typically involves providing business details such as company name, registration number, contact information, and banking details Klarna business registration form. Upon successful registration and approval, access to the Klarna Merchant Portal is granted.
Within the Klarna Merchant Portal, API credentials are generated. These credentials typically consist of a unique API Username (often referred to as your Merchant ID or EID) and an API Password. These are essential for authenticating all requests made to Klarna's API endpoints. It is critical to treat these keys as sensitive information, similar to how one would manage AWS access key best practices, to prevent unauthorized access to your Klarna account and customer data.
The steps to retrieve these keys are:
- Log in to the Klarna Merchant Portal using your merchant account credentials.
- Navigate to the 'Settings' section, usually found in the sidebar or top menu.
- Look for an option labeled 'Klarna API Credentials' or similar.
- Generate new credentials if none exist, or view existing ones. Note that API Passwords are often only displayed once upon generation for security reasons, requiring you to copy and store them securely immediately.
- Distinguish between API keys for the production environment and the sandbox/test environment. Klarna provides separate credentials for each, allowing for safe development and testing without affecting live transactions. Ensure you are using the correct set of keys for your current development phase.
Having separate credentials for different environments is a standard security practice. For instance, Stripe's documentation on API keys also emphasizes the use of distinct publishable and secret keys for test and live modes. This isolation helps prevent accidental live transactions during development and reduces the risk of exposing sensitive production credentials in development environments.
Your first request
Once you have obtained your API credentials, the next step is to make a programmatic call to the Klarna API. This section assumes a direct API integration using a language like Python, though similar concepts apply to other SDKs.
A common first request is to create a new Klarna order or a payment session. This involves sending a POST request to the relevant Klarna endpoint with details about the consumer, the order items, and the total amount. Klarna's API typically uses JSON for request and response payloads.
Example: Creating a Payment Session (Python)
This example demonstrates how to create a payment session using a basic Python script. You would replace your_merchant_id and your_api_password with your actual Klarna API credentials for the test environment.
import requests
import base64
# Klarna Sandbox Endpoints (adjust for chosen region, e.g., NA for North America)
# For a full list of regional endpoints, refer to Klarna's API documentation
KLARNA_API_BASE_URL = "https://api.playground.klarna.com"
# Your Klarna API Credentials (from Merchant Portal - Sandbox)
MERCHANT_ID = "your_merchant_id" # E.g., "K123456"
API_PASSWORD = "your_api_password" # E.g., "aBcDeFgHiJkLmNoPqRsTuVwXyZ"
AUTH_STRING = base64.b64encode(f"{MERCHANT_ID}:{API_PASSWORD}".encode()).decode()
HEADERS = {
"Authorization": f"Basic {AUTH_STRING}",
"Content-Type": "application/json"
}
# Example Order Data
ORDER_DATA = {
"purchase_country": "US",
"purchase_currency": "USD",
"locale": "en-US",
"order_amount": 25000, # 250.00 USD (in cents)
"order_tax_amount": 2500, # 25.00 USD (in cents)
"order_lines": [
{
"type": "physical",
"reference": "123050",
"name": "Klarna T-Shirt",
"quantity": 1,
"unit_price": 20000, # 200.00 USD
"tax_rate": 1000, # 10.00% (in basis points)
"total_amount": 20000,
"total_tax_amount": 2000
},
{
"type": "shipping_fee",
"reference": "shipping",
"name": "Shipping Fee",
"quantity": 1,
"unit_price": 5000, # 50.00 USD
"tax_rate": 1000, # 10.00%
"total_amount": 5000,
"total_tax_amount": 500
}
],
"merchant_urls": {
"checkout": "https://www.example.com/checkout",
"confirmation": "https://www.example.com/confirmation",
"push": "https://www.example.com/klarna-push-callback"
},
"customer": {
"date_of_birth": "1990-01-01",
"gender": "male"
}
}
# Endpoint for creating a payment session (adjust based on API version/product)
# Always refer to the latest Klarna API documentation for endpoint specifics.
CREATE_SESSION_ENDPOINT = f"{KLARNA_API_BASE_URL}/payments/v1/sessions"
print(f"Attempting to create a payment session at: {CREATE_SESSION_ENDPOINT}")
try:
response = requests.post(CREATE_SESSION_ENDPOINT, json=ORDER_DATA, headers=HEADERS)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
session_data = response.json()
print("Payment Session created successfully:")
print(f"Session ID: {session_data.get('session_id')}")
print(f"Client Token: {session_data.get('client_token')}")
print(f"Redirect URL: {session_data.get('redirect_url')}") # If applicable for the flow
except requests.exceptions.HTTPError as err:
print(f"HTTP Error occurred: {err}")
print(f"Response Status Code: {response.status_code}")
print(f"Response Body: {response.text}")
except requests.exceptions.RequestException as err:
print(f"An error occurred: {err}")
After executing this script in your sandbox environment, a successful response will typically contain a client_token and a session_id. The client_token is crucial for rendering the Klarna widget on your frontend, enabling the consumer to select their preferred payment option. The redirect_url, if provided, is used when Klarna's experience is hosted directly by Klarna and the consumer needs to be redirected there. This initial successful call confirms that your credentials are correct and your basic API setup is functional.
Common next steps
After successfully making your first API call and understanding the foundational request-response cycle, several common next steps will evolve your Klarna integration:
-
Implement the Frontend Widget: Use the
client_tokenobtained from the payment session creation to initialize Klarna's JavaScript SDK on your checkout page. This renders the Klarna payment widget, allowing customers to choose their Klarna payment method (e.g., Pay in 4, Pay in 30 days, Financing) directly within your site. For detailed instructions, consult the Klarna Payments client-side implementation guide. - Handle Callbacks and Webhooks: Klarna communicates the status of an order (e.g., authorized, captured, refunded) back to your system via webhooks. It is essential to develop robust webhook handlers that can securely receive and process these notifications. This involves setting up endpoints on your server to listen for Klarna's push notifications and update your order management system accordingly. Twilio provides webhook security guidance that can be adapted for general webhook implementations.
-
Order Management (Capture, Refund, Cancel): Beyond initial authorization, you will need to implement API calls for managing the lifecycle of an order. This includes capturing authorized funds once goods are shipped, initiating refunds for returns, and canceling orders if necessary. These operations typically involve POST requests to specific order management endpoints, referencing the
order_idreceived after a successful checkout. - Testing in Sandbox: Continuously test all integration flows, including edge cases like failed payments, partial refunds, and order cancellations, within the Klarna sandbox environment. This ensures that your system behaves as expected under various scenarios before deploying to production. The Klarna Go-Live checklist provides a comprehensive list of items to verify.
- Go Live: Once testing is complete and satisfactory, switch to your production API credentials and endpoints. Review the Klarna Go-Live documentation for any final requirements or checks before launching your integration to live customers.
Troubleshooting the first call
Encountering issues during your initial Klarna API call is a common part of the integration process. Here are some frequent problems and their solutions:
-
401 Unauthorized Error:
- Issue: This almost always indicates incorrect API credentials.
- Solution: Double-check your Merchant ID (Username) and API Password. Ensure you are using the correct set of credentials for the environment (sandbox vs. production) you are targeting. Remember that API Passwords are case-sensitive and may include special characters. Verify the base64 encoding of your credentials if constructing the Authorization header manually.
-
400 Bad Request Error:
- Issue: The request body contains invalid or missing data according to Klarna's API specification.
- Solution: Review the request payload against the Klarna Payments API reference for the specific endpoint you are calling. Common culprits include incorrect data types, missing required fields (e.g.,
purchase_country,order_amount,order_lines), or incorrect formatting (e.g., amounts not in minor units like cents). Examine the error message in the API response body, as Klarna often provides specific details about validation failures.
-
Incorrect API Endpoint or Region:
- Issue: You might be sending requests to the wrong regional endpoint (e.g., targeting the EU API with a US merchant account) or an outdated API version.
- Solution: Confirm the correct Klarna API base URL for your merchant country and the API version you intend to use. Klarna has distinct endpoints for different geographical regions (e.g.,
api.playground.klarna.comfor US sandbox,api.klarna.comfor US production). Refer to the Klarna regions and currencies guide to ensure you are pointing to the correct environment.
-
Network or Firewall Issues:
- Issue: Your server or local development environment might be blocked from reaching Klarna's API endpoints.
- Solution: Check local firewall settings, corporate network policies, or proxy configurations that could be preventing outbound HTTPS requests. Ensure that your environment can resolve and connect to Klarna's domain. Basic network tests like
pingorcurlfrom your server can help diagnose connectivity issues.
-
SDK-specific Errors:
- Issue: If using an SDK, errors might arise from incorrect SDK initialization, method usage, or version compatibility.
- Solution: Consult the specific Klarna SDK reference documentation for the language you are using. Ensure the SDK is installed correctly and that you are passing parameters in the expected format. Updating to the latest stable SDK version can sometimes resolve known issues.
When troubleshooting, always log the full request (headers and body) and the full API response (status code, headers, and body). This detailed information is invaluable for pinpointing the exact cause of an error or for providing context when seeking support from Klarna's developer community or support team. Klarna also provides a debug mode or logging within its SDKs that can offer more verbose output during development.