Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Checkout Laravel Package

klarna/checkout

Deprecated Klarna Checkout PHP library/SDK for integrating Klarna Checkout. This package is no longer supported; use the maintained replacement klarna/kco_rest_php instead. Documentation and examples available at developers.klarna.com.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require klarna/checkout
    

    Note: Despite being archived, this remains the quickest way to integrate Klarna’s API in Laravel.

  2. Configuration: Add Klarna credentials to .env:

    KLARNA_CLIENT_ID=your_client_id
    KLARNA_CLIENT_SECRET=your_client_secret
    KLARNA_BASE_URL=https://api.klarna.com
    KLARNA_WEBHOOK_URL=https://your-app.com/klarna/webhook
    
  3. Service Provider: Register the Klarna client in AppServiceProvider.php:

    public function boot()
    {
        $this->app->singleton('klarna', function ($app) {
            return new \Klarna\Checkout($app['config']['klarna.client_id'], $app['config']['klarna.client_secret']);
        });
    }
    
  4. First Use Case: Create a checkout session in a controller:

    use Klarna\Checkout;
    
    public function checkout(Request $request, Checkout $klarna)
    {
        $order = $klarna->createOrder([
            'purchase_country' => 'SE',
            'purchase_currency' => 'SEK',
            'lines' => [
                ['type' => 'physical', 'reference' => 'order_123', 'quantity' => 1, 'unit_price' => 1000, 'tax_rate' => 25, 'total_amount' => 1250, 'total_tax_amount' => 250, 'discount_rate' => 0, 'type' => 'physical']
            ],
            'merchant_urls' => [
                'terms' => 'https://your-app.com/terms',
                'checkout' => 'https://your-app.com/checkout',
            ],
        ]);
        return redirect($order->checkout_url);
    }
    
  5. Webhook Endpoint: Add a route and handler for Klarna webhooks:

    Route::post('/klarna/webhook', [KlarnaWebhookController::class, 'handle']);
    

Implementation Patterns

Usage Patterns

1. Checkout Flow

  • Order Creation: Use createOrder() to generate a Klarna order with product lines, taxes, and merchant URLs.
  • Session Management: Store the order_id in the session or database to track the checkout process.
  • Redirect: Redirect users to checkout_url returned by Klarna.
$order = $klarna->createOrder($orderData);
session()->put('klarna_order_id', $order->order_id);
return redirect($order->checkout_url);

2. Webhook Handling

  • Signature Verification: Validate webhook payloads using Klarna’s signature header.
  • Event Dispatching: Map Klarna events (e.g., payment.authorized) to Laravel events or queue jobs.
public function handle(Request $request, Checkout $klarna)
{
    $payload = $request->getContent();
    $signature = $request->header('Klarna-Signature');

    if (!$klarna->verifyWebhook($payload, $signature)) {
        abort(401);
    }

    $event = json_decode($payload, true);
    // Dispatch event or process asynchronously
    HandleKlarnaWebhookJob::dispatch($event);
}

3. Payment Capture and Refunds

  • Capture Payments: Use captureOrder() to finalize authorized payments.
  • Refunds: Use createRefund() for partial or full refunds.
$klarna->captureOrder($orderId, ['amount' => 1250]);
$refund = $klarna->createRefund($orderId, ['amount' => 500]);

4. Order Status Checks

  • Poll Klarna’s API for order status updates if webhooks are unreliable.
  • Cache responses to avoid rate limits.
$order = $klarna->getOrder($orderId);
if ($order->status === 'checked_out') {
    // Update local database
}

Workflows

Subscription Payments

  • Use Klarna’s recurring payments feature by setting recurring in the order lines.
  • Handle payment.pending webhooks to trigger subscription activation.
'lines' => [
    [
        'type' => 'physical',
        'reference' => 'subscription_123',
        'quantity' => 1,
        'unit_price' => 999,
        'tax_rate' => 20,
        'total_amount' => 1198.8,
        'total_tax_amount' => 198.8,
        'type' => 'physical',
        'recurring' => [
            'interval' => 'month',
            'interval_unit' => 'month',
            'max_intervals' => 12,
        ],
    ],
],

Multi-Currency Support

  • Dynamically set purchase_currency based on user location.
  • Handle currency conversion in your backend if needed.
$currency = $user->preferred_currency ?? 'SEK';
$order = $klarna->createOrder([
    'purchase_country' => $user->country,
    'purchase_currency' => $currency,
    // ...
]);

Integration Tips

Laravel-Specific Integrations

  1. Service Container: Bind the Klarna client to an interface for easier testing/mocking:

    $this->app->bind(
        KlarnaCheckoutInterface::class,
        function ($app) {
            return new \Klarna\Checkout($app['config']['klarna.client_id'], $app['config']['klarna.client_secret']);
        }
    );
    
  2. Middleware for Auth: Protect Klarna-related routes with middleware to validate API tokens:

    Route::middleware(['klarna.auth'])->group(function () {
        Route::post('/klarna/webhook', [KlarnaWebhookController::class, 'handle']);
    });
    
  3. Queue Jobs for Webhooks: Offload webhook processing to a queue to avoid long-running requests:

    public function handle(Request $request)
    {
        $payload = $request->getContent();
        ProcessKlarnaWebhookJob::dispatch($payload);
        return response()->json(['status' => 'queued']);
    }
    
  4. Database Reconciliation: Store Klarna order_id and payment_id in your local database to sync statuses:

    // Migration
    Schema::create('klarna_orders', function (Blueprint $table) {
        $table->id();
        $table->string('klarna_order_id')->unique();
        $table->string('status')->nullable();
        $table->foreignId('user_id')->constrained();
        $table->timestamps();
    });
    
  5. Event Dispatching: Trigger Laravel events for Klarna webhooks to decouple business logic:

    event(new KlarnaPaymentAuthorized($eventData));
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • The package is archived and unsupported. Klarna’s official SDK (kco_rest_php) is the recommended alternative.
    • Workaround: Fork the repository and maintain it internally, or migrate to the official SDK.
  2. Webhook Signature Verification:

    • Always verify the Klarna-Signature header to prevent spoofing attacks.
    • The wrapper may not handle signature verification out-of-the-box; implement manually:
      $expectedSignature = hash_hmac('sha256', $payload, $app['config']['klarna.secret']);
      if (!hash_equals($expectedSignature, $signature)) {
          abort(401, 'Invalid webhook signature');
      }
      
  3. Rate Limiting:

    • Klarna enforces rate limits (e.g., 100 requests/minute). Exceeding limits may temporarily block your IP.
    • Solution: Implement exponential backoff in retries or use Laravel’s Illuminate\Cache\RateLimiter.
  4. Idempotency:

    • Webhook payloads may be retried. Design handlers to be idempotent (e.g., check if a payment already exists before creating it).
  5. Currency and Country Restrictions:

    • Klarna supports specific currency-country pairs. Invalid combinations (e.g., USD + SE) will fail.
    • Tip: Validate these pairs before making API calls.
  6. Order Reference Uniqueness:

    • The reference field in order lines must be unique per merchant. Reusing references may cause conflicts.
    • Solution: Use UUIDs or database-generated IDs for references.
  7. Webhook Retries:

    • Klarna retries failed webhook deliveries. Ensure your endpoint is resilient to duplicate payloads.
  8. PCI Compliance:

    • The wrapper may not handle PCI-DSS requirements (
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky