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

Klarna Invoice Laravel Package

solidworx/klarna-invoice

Laravel package for Klarna Invoice payments. Provides helpers and integration scaffolding to create invoices, handle checkout/payment flows, and manage customer/order details within your Laravel app.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require solidworx/klarna-invoice

Ensure you also install the companion package for integration with Payum:

composer require payum/klarna-invoice
  1. First Use Case:

    • Use this package alongside Payum to handle Klarna Invoice payments. The package itself is a low-level wrapper for Klarna’s API, while Payum/KlarnaInvoice provides the payment gateway integration.
    • Example: Initialize a Klarna Invoice client in a Laravel service:
      use SolidWorx\KlarnaInvoice\Client;
      
      $client = new Client(
          config('services.klarna.secret_key'),
          config('services.klarna.public_key'),
          config('services.klarna.test_mode') // Set to true for sandbox
      );
      
  2. Where to Look First:

    • Documentation: The package is minimal, so refer to Payum/KlarnaInvoice for high-level workflows.
    • Source Code: Focus on src/Client.php for API interactions and src/Invoice.php for invoice creation/modification.
    • Config: No built-in Laravel config; define Klarna credentials in config/services.php:
      'klarna' => [
          'secret_key' => env('KLARNA_SECRET_KEY'),
          'public_key' => env('KLARNA_PUBLIC_KEY'),
          'test_mode' => env('KLARNA_TEST_MODE', false),
      ],
      

Implementation Patterns

Core Workflow: Creating and Managing Invoices

  1. Invoice Creation: Use the Client to create an invoice via Payum’s KlarnaInvoice gateway:

    $gateway = $payum->getGateway('klarna_invoice');
    $invoice = $gateway->createInvoice([
        'amount' => 100.00,
        'currency' => 'SEK',
        'description' => 'Order #12345',
        'purchase_country' => 'SE',
        'purchase_city' => 'Stockholm',
        'order_amount' => 100.00,
        'order_tax_amount' => 25.00,
        'order_vat_percent' => 25,
        'order_lines' => [
            ['type' => 'physical', 'reference' => 'book-123', 'name' => 'Book', 'quantity' => 1, 'unit_price' => 100.00, 'tax_rate' => 25, 'total_amount' => 100.00, 'total_tax_amount' => 25.00],
        ],
        'customer' => [
            'title' => 'Mr',
            'given_name' => 'John',
            'family_name' => 'Doe',
            'email' => 'john.doe@example.com',
            'date_of_birth' => '1980-01-01',
            'personal_identity_number' => '198001011234', // Required for SE invoices
        ],
    ]);
    
    • Note: The Client class alone won’t handle this; Payum’s gateway abstracts the process.
  2. Fetching Invoice Status:

    $invoice = $client->fetchInvoice($invoiceId);
    $status = $invoice->getStatus(); // 'created', 'paid', 'cancelled', etc.
    
  3. Cancelling an Invoice:

    $client->cancelInvoice($invoiceId);
    
  4. Webhook Handling:

    • Klarna sends webhooks for status updates. Use Laravel’s HandleIncomingWebhook trait or a middleware to validate and process them:
      use SolidWorx\KlarnaInvoice\Webhook\HandleIncomingWebhook;
      
      class KlarnaWebhookController extends Controller
      {
          use HandleIncomingWebhook;
      
          public function handle(Request $request)
          {
              $this->validateWebhook($request, config('services.klarna.secret_key'));
              // Process the webhook event (e.g., update order status in DB)
          }
      }
      

Integration Tips

  • Laravel Service Provider: Bind the Client to the container for dependency injection:

    $this->app->singleton(Client::class, function ($app) {
        return new Client(
            config('services.klarna.secret_key'),
            config('services.klarna.public_key'),
            config('services.klarna.test_mode')
        );
    });
    
  • Form Integration: Use the public_key to initialize Klarna’s hosted checkout in your Blade view:

    <klarna-invoice
        data-payment-method="invoice"
        data-merchant-id="{{ config('services.klarna.merchant_id') }}"
        data-payment-id="{{ $invoice->getId() }}"
        data-init="true"
        data-locale="en-GB">
    </klarna-invoice>
    <script src="https://cdn.klarna.com/js/klarna.js"></script>
    
  • Testing: Use Klarna’s sandbox environment (set test_mode => true) and mock the Client in tests:

    $mockClient = Mockery::mock(Client::class);
    $mockClient->shouldReceive('createInvoice')->andReturn($mockInvoice);
    $this->app->instance(Client::class, $mockClient);
    

Gotchas and Tips

Pitfalls

  1. Missing Dependencies:

    • This package requires payum/klarna-invoice for full functionality. Install both:
      composer require solidworx/klarna-invoice payum/klarna-invoice
      
  2. PHP 8 Compatibility:

    • The package is PHP 8+ only (due to #[ReturnTypeWillChange]). Ensure your project uses PHP 8.x.
  3. Webhook Validation:

    • Always validate webhook signatures to prevent spoofing. Use the validateWebhook method from HandleIncomingWebhook:
      $this->validateWebhook($request, config('services.klarna.secret_key'));
      
    • Error: If the signature fails, Klarna’s server will return a 401 Unauthorized.
  4. Country-Specific Requirements:

    • Some countries (e.g., Sweden) require personal identity numbers (personal_identity_number) for invoices. Omit this field for unsupported countries, but expect Klarna to reject the invoice.
  5. Rate Limiting:

    • Klarna’s API has rate limits. Cache responses for frequently accessed invoices:
      $invoice = Cache::remember("klarna_invoice_{$invoiceId}", now()->addHours(1), function () use ($client, $invoiceId) {
          return $client->fetchInvoice($invoiceId);
      });
      
  6. Deprecated Methods:

    • The ArrayAccess methods in Invoice are marked with #[ReturnTypeWillChange]. Avoid relying on return types in older PHP versions.

Debugging Tips

  1. Enable API Logging: Configure the Client to log requests/responses:

    $client = new Client($secretKey, $publicKey, $testMode, [
        'logger' => new \Monolog\Logger('klarna', [$handler]),
        'debug' => true,
    ]);
    
  2. Test Mode Quirks:

    • Sandbox invoices expire after 30 days. Use real credentials for long-term testing if needed.
    • Sandbox webhooks use a different endpoint (https://webhook-test.klarna.com).
  3. Common Errors:

    • InvalidParameter: Validate all required fields (e.g., purchase_country, order_lines).
    • AuthenticationFailed: Double-check secret_key and public_key in your config.
    • InvoiceNotFound: Ensure the invoice_id matches Klarna’s format (e.g., inv_123abc).

Extension Points

  1. Custom Invoice Data: Extend the Invoice class to add project-specific fields:

    class CustomInvoice extends \SolidWorx\KlarnaInvoice\Invoice
    {
        public function setCustomField(string $key, $value): self
        {
            $this->data['custom'][$key] = $value;
            return $this;
        }
    }
    
  2. Override Webhook Handling: Extend HandleIncomingWebhook to add custom logic:

    class CustomWebhookHandler
    {
        use HandleIncomingWebhook;
    
        protected function handlePaidEvent($data)
        {
            // Custom logic for paid invoices
            event(new InvoicePaid($data['invoice']['invoice_number']));
        }
    }
    
  3. Add Middleware: Use Laravel middleware to pre-process requests/responses:

    $client->setMiddleware(function ($request, callable $next) {
        $request->
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor